Merge
authorduke
Wed, 05 Jul 2017 19:33:51 +0200
changeset 23384 beb36a817426
parent 23383 be22d398982c (current diff)
parent 23379 ea49d2995f89 (diff)
child 23389 e47ead3d6a3c
Merge
corba/make/src/classes/build/tools/stripproperties/StripPropertiesCorba.java
jdk/make/src/classes/build/tools/stripproperties/StripProperties.java
jdk/src/macosx/classes/sun/lwawt/macosx/event/NSEvent.java
jdk/src/macosx/native/sun/awt/CWrapper.h
jdk/src/share/classes/sun/swing/AbstractFilterComboBoxModel.java
jdk/src/share/classes/sun/tools/serialver/serialver.properties
jdk/src/share/classes/sun/tools/serialver/serialver_ja.properties
jdk/src/share/classes/sun/tools/serialver/serialver_zh_CN.properties
jdk/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h
jdk/test/java/lang/ClassLoader/Assert.sh
jdk/test/javax/swing/text/AbstractDocument/7146146/bug7146146.java
nashorn/src/jdk/nashorn/internal/runtime/GlobalObject.java
--- a/.hgtags-top-repo	Tue Mar 25 12:31:49 2014 -0700
+++ b/.hgtags-top-repo	Wed Jul 05 19:33:51 2017 +0200
@@ -247,3 +247,4 @@
 135f0c7af57ebace31383d8877f47e32172759ff jdk9-b02
 fd8d51bdf9aadf7ae83e65e8655c53581017c363 jdk9-b03
 cb4c3440bc2748101923e2488506e61009ab1bf5 jdk9-b04
+8c63f0b6ada282f27e3a80125e53c3be603f9af7 jdk9-b05
--- a/common/autoconf/boot-jdk.m4	Tue Mar 25 12:31:49 2014 -0700
+++ b/common/autoconf/boot-jdk.m4	Wed Jul 05 19:33:51 2017 +0200
@@ -350,8 +350,23 @@
 
   AC_MSG_CHECKING([flags for boot jdk java command] )
 
+  # Disable special log output when a debug build is used as Boot JDK...
+  ADD_JVM_ARG_IF_OK([-XX:-PrintVMOptions -XX:-UnlockDiagnosticVMOptions -XX:-LogVMOutput],boot_jdk_jvmargs,[$JAVA])
+
+  # Apply user provided options.
+  ADD_JVM_ARG_IF_OK([$with_boot_jdk_jvmargs],boot_jdk_jvmargs,[$JAVA])
+
+  AC_MSG_RESULT([$boot_jdk_jvmargs])
+
+  # For now, general JAVA_FLAGS are the same as the boot jdk jvmargs
+  JAVA_FLAGS=$boot_jdk_jvmargs
+  AC_SUBST(JAVA_FLAGS)
+
+
+  AC_MSG_CHECKING([flags for boot jdk java command for big workloads])
+
   # Starting amount of heap memory.
-  ADD_JVM_ARG_IF_OK([-Xms64M],boot_jdk_jvmargs,[$JAVA])
+  ADD_JVM_ARG_IF_OK([-Xms64M],boot_jdk_jvmargs_big,[$JAVA])
 
   # Maximum amount of heap memory.
   # Maximum stack size.
@@ -366,20 +381,24 @@
     JVM_MAX_HEAP=1600M
     STACK_SIZE=1536
   fi
-  ADD_JVM_ARG_IF_OK([-Xmx$JVM_MAX_HEAP],boot_jdk_jvmargs,[$JAVA])
-  ADD_JVM_ARG_IF_OK([-XX:ThreadStackSize=$STACK_SIZE],boot_jdk_jvmargs,[$JAVA])
+  ADD_JVM_ARG_IF_OK([-Xmx$JVM_MAX_HEAP],boot_jdk_jvmargs_big,[$JAVA])
+  ADD_JVM_ARG_IF_OK([-XX:ThreadStackSize=$STACK_SIZE],boot_jdk_jvmargs_big,[$JAVA])
+
+  AC_MSG_RESULT([$boot_jdk_jvmargs_big])
 
-  # Disable special log output when a debug build is used as Boot JDK...
-  ADD_JVM_ARG_IF_OK([-XX:-PrintVMOptions -XX:-UnlockDiagnosticVMOptions -XX:-LogVMOutput],boot_jdk_jvmargs,[$JAVA])
+  JAVA_FLAGS_BIG=$boot_jdk_jvmargs_big
+  AC_SUBST(JAVA_FLAGS_BIG)
 
-  # Apply user provided options.
-  ADD_JVM_ARG_IF_OK([$with_boot_jdk_jvmargs],boot_jdk_jvmargs,[$JAVA])
+
+  AC_MSG_CHECKING([flags for boot jdk java command for small workloads])
 
-  AC_MSG_RESULT([$boot_jdk_jvmargs])
+  # Use serial gc for small short lived tools if possible
+  ADD_JVM_ARG_IF_OK([-XX:+UseSerialGC],boot_jdk_jvmargs_small,[$JAVA])
+  ADD_JVM_ARG_IF_OK([-Xms32M],boot_jdk_jvmargs_small,[$JAVA])
+  ADD_JVM_ARG_IF_OK([-Xmx512M],boot_jdk_jvmargs_small,[$JAVA])
 
-  # For now, general JAVA_FLAGS are the same as the boot jdk jvmargs
-  JAVA_FLAGS=$boot_jdk_jvmargs
+  AC_MSG_RESULT([$boot_jdk_jvmargs_small])
 
-  AC_SUBST(BOOT_JDK_JVMARGS, $boot_jdk_jvmargs)
-  AC_SUBST(JAVA_FLAGS, $JAVA_FLAGS)
+  JAVA_FLAGS_SMALL=$boot_jdk_jvmargs_small
+  AC_SUBST(JAVA_FLAGS_SMALL)
 ])
--- a/common/autoconf/flags.m4	Tue Mar 25 12:31:49 2014 -0700
+++ b/common/autoconf/flags.m4	Wed Jul 05 19:33:51 2017 +0200
@@ -148,6 +148,26 @@
       SET_SHARED_LIBRARY_NAME='-Xlinker -soname=[$]1'
       SET_SHARED_LIBRARY_MAPFILE='-Xlinker -version-script=[$]1'
     fi
+  elif test "x$TOOLCHAIN_TYPE" = xclang; then
+    PICFLAG=''
+    C_FLAG_REORDER=''
+    CXX_FLAG_REORDER=''
+
+    if test "x$OPENJDK_TARGET_OS" = xmacosx; then
+      # Linking is different on MacOSX
+      SHARED_LIBRARY_FLAGS="-dynamiclib -compatibility_version 1.0.0 -current_version 1.0.0 $PICFLAG"
+      SET_EXECUTABLE_ORIGIN='-Xlinker -rpath -Xlinker @loader_path/.'
+      SET_SHARED_LIBRARY_ORIGIN="$SET_EXECUTABLE_ORIGIN"
+      SET_SHARED_LIBRARY_NAME='-Xlinker -install_name -Xlinker @rpath/[$]1'
+      SET_SHARED_LIBRARY_MAPFILE=''
+    else
+      # Default works for linux, might work on other platforms as well.
+      SHARED_LIBRARY_FLAGS='-shared'
+      SET_EXECUTABLE_ORIGIN='-Xlinker -rpath -Xlinker \$$$$ORIGIN[$]1'
+      SET_SHARED_LIBRARY_ORIGIN="-Xlinker -z -Xlinker origin $SET_EXECUTABLE_ORIGIN"
+      SET_SHARED_LIBRARY_NAME='-Xlinker -soname=[$]1'
+      SET_SHARED_LIBRARY_MAPFILE='-Xlinker -version-script=[$]1'
+    fi
   elif test "x$TOOLCHAIN_TYPE" = xsolstudio; then
     PICFLAG="-KPIC"
     C_FLAG_REORDER='-xF'
@@ -242,6 +262,8 @@
   # Generate make dependency files
   if test "x$TOOLCHAIN_TYPE" = xgcc; then
     C_FLAG_DEPS="-MMD -MF"
+  elif test "x$TOOLCHAIN_TYPE" = xclang; then
+    C_FLAG_DEPS="-MMD -MF"
   elif test "x$TOOLCHAIN_TYPE" = xsolstudio; then
     C_FLAG_DEPS="-xMMD -xMF"
   elif test "x$TOOLCHAIN_TYPE" = xxlc; then
@@ -260,6 +282,9 @@
       CFLAGS_DEBUG_SYMBOLS="-g"
       CXXFLAGS_DEBUG_SYMBOLS="-g"
     fi
+  elif test "x$TOOLCHAIN_TYPE" = xclang; then
+    CFLAGS_DEBUG_SYMBOLS="-g"
+    CXXFLAGS_DEBUG_SYMBOLS="-g"
   elif test "x$TOOLCHAIN_TYPE" = xsolstudio; then
     CFLAGS_DEBUG_SYMBOLS="-g -xs"
     CXXFLAGS_DEBUG_SYMBOLS="-g0 -xs"
@@ -315,6 +340,20 @@
         C_O_FLAG_NORM="-O2"
         C_O_FLAG_NONE="-O0"
       fi
+    elif test "x$TOOLCHAIN_TYPE" = xclang; then
+      if test "x$OPENJDK_TARGET_OS" = xmacosx; then
+        # On MacOSX we optimize for size, something
+        # we should do for all platforms?
+        C_O_FLAG_HIGHEST="-Os"
+        C_O_FLAG_HI="-Os"
+        C_O_FLAG_NORM="-Os"
+        C_O_FLAG_NONE=""
+      else
+        C_O_FLAG_HIGHEST="-O3"
+        C_O_FLAG_HI="-O3"
+        C_O_FLAG_NORM="-O2"
+        C_O_FLAG_NONE="-O0"
+      fi
     elif test "x$TOOLCHAIN_TYPE" = xxlc; then
       C_O_FLAG_HIGHEST="-O3"
       C_O_FLAG_HI="-O3 -qstrict"
--- a/common/autoconf/generated-configure.sh	Tue Mar 25 12:31:49 2014 -0700
+++ b/common/autoconf/generated-configure.sh	Wed Jul 05 19:33:51 2017 +0200
@@ -653,6 +653,9 @@
 LIBM
 LIBZIP_CAN_USE_MMAP
 USE_EXTERNAL_LIBZ
+USE_EXTERNAL_LIBPNG
+PNG_LIBS
+PNG_CFLAGS
 USE_EXTERNAL_LIBGIF
 USE_EXTERNAL_LIBJPEG
 ALSA_LIBS
@@ -793,8 +796,9 @@
 JAXP_TOPDIR
 CORBA_TOPDIR
 LANGTOOLS_TOPDIR
+JAVA_FLAGS_SMALL
+JAVA_FLAGS_BIG
 JAVA_FLAGS
-BOOT_JDK_JVMARGS
 JAVAC_FLAGS
 BOOT_JDK_SOURCETARGET
 JARSIGNER
@@ -1071,6 +1075,7 @@
 with_alsa_include
 with_alsa_lib
 with_giflib
+with_libpng
 with_zlib
 with_stdc__lib
 with_msvcr_dll
@@ -1183,6 +1188,8 @@
 FREETYPE_LIBS
 ALSA_CFLAGS
 ALSA_LIBS
+PNG_CFLAGS
+PNG_LIBS
 LIBFFI_CFLAGS
 LIBFFI_LIBS
 CCACHE'
@@ -1921,6 +1928,8 @@
   --with-alsa-lib         specify directory for the alsa library
   --with-giflib           use giflib from build system or OpenJDK source
                           (system, bundled) [bundled]
+  --with-libpng           use libpng from build system or OpenJDK source
+                          (system, bundled) [bundled]
   --with-zlib             use zlib from build system or OpenJDK source
                           (system, bundled) [bundled]
   --with-stdc++lib=<static>,<dynamic>,<default>
@@ -2045,6 +2054,8 @@
               linker flags for FREETYPE, overriding pkg-config
   ALSA_CFLAGS C compiler flags for ALSA, overriding pkg-config
   ALSA_LIBS   linker flags for ALSA, overriding pkg-config
+  PNG_CFLAGS  C compiler flags for PNG, overriding pkg-config
+  PNG_LIBS    linker flags for PNG, overriding pkg-config
   LIBFFI_CFLAGS
               C compiler flags for LIBFFI, overriding pkg-config
   LIBFFI_LIBS linker flags for LIBFFI, overriding pkg-config
@@ -4221,7 +4232,7 @@
 #CUSTOM_AUTOCONF_INCLUDE
 
 # Do not change or remove the following line, it is needed for consistency checks:
-DATE_WHEN_GENERATED=1394011255
+DATE_WHEN_GENERATED=1394794899
 
 ###############################################################################
 #
@@ -25856,67 +25867,6 @@
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking flags for boot jdk java command " >&5
 $as_echo_n "checking flags for boot jdk java command ... " >&6; }
 
-  # Starting amount of heap memory.
-
-  $ECHO "Check if jvm arg is ok: -Xms64M" >&5
-  $ECHO "Command: $JAVA -Xms64M -version" >&5
-  OUTPUT=`$JAVA -Xms64M -version 2>&1`
-  FOUND_WARN=`$ECHO "$OUTPUT" | grep -i warn`
-  FOUND_VERSION=`$ECHO $OUTPUT | grep " version \""`
-  if test "x$FOUND_VERSION" != x && test "x$FOUND_WARN" = x; then
-    boot_jdk_jvmargs="$boot_jdk_jvmargs -Xms64M"
-    JVM_ARG_OK=true
-  else
-    $ECHO "Arg failed:" >&5
-    $ECHO "$OUTPUT" >&5
-    JVM_ARG_OK=false
-  fi
-
-
-  # Maximum amount of heap memory.
-  # Maximum stack size.
-  if test "x$BUILD_NUM_BITS" = x32; then
-    JVM_MAX_HEAP=1100M
-    STACK_SIZE=768
-  else
-    # Running Javac on a JVM on a 64-bit machine, takes more space since 64-bit
-    # pointers are used. Apparently, we need to increase the heap and stack
-    # space for the jvm. More specifically, when running javac to build huge
-    # jdk batch
-    JVM_MAX_HEAP=1600M
-    STACK_SIZE=1536
-  fi
-
-  $ECHO "Check if jvm arg is ok: -Xmx$JVM_MAX_HEAP" >&5
-  $ECHO "Command: $JAVA -Xmx$JVM_MAX_HEAP -version" >&5
-  OUTPUT=`$JAVA -Xmx$JVM_MAX_HEAP -version 2>&1`
-  FOUND_WARN=`$ECHO "$OUTPUT" | grep -i warn`
-  FOUND_VERSION=`$ECHO $OUTPUT | grep " version \""`
-  if test "x$FOUND_VERSION" != x && test "x$FOUND_WARN" = x; then
-    boot_jdk_jvmargs="$boot_jdk_jvmargs -Xmx$JVM_MAX_HEAP"
-    JVM_ARG_OK=true
-  else
-    $ECHO "Arg failed:" >&5
-    $ECHO "$OUTPUT" >&5
-    JVM_ARG_OK=false
-  fi
-
-
-  $ECHO "Check if jvm arg is ok: -XX:ThreadStackSize=$STACK_SIZE" >&5
-  $ECHO "Command: $JAVA -XX:ThreadStackSize=$STACK_SIZE -version" >&5
-  OUTPUT=`$JAVA -XX:ThreadStackSize=$STACK_SIZE -version 2>&1`
-  FOUND_WARN=`$ECHO "$OUTPUT" | grep -i warn`
-  FOUND_VERSION=`$ECHO $OUTPUT | grep " version \""`
-  if test "x$FOUND_VERSION" != x && test "x$FOUND_WARN" = x; then
-    boot_jdk_jvmargs="$boot_jdk_jvmargs -XX:ThreadStackSize=$STACK_SIZE"
-    JVM_ARG_OK=true
-  else
-    $ECHO "Arg failed:" >&5
-    $ECHO "$OUTPUT" >&5
-    JVM_ARG_OK=false
-  fi
-
-
   # Disable special log output when a debug build is used as Boot JDK...
 
   $ECHO "Check if jvm arg is ok: -XX:-PrintVMOptions -XX:-UnlockDiagnosticVMOptions -XX:-LogVMOutput" >&5
@@ -25957,9 +25907,133 @@
   # For now, general JAVA_FLAGS are the same as the boot jdk jvmargs
   JAVA_FLAGS=$boot_jdk_jvmargs
 
-  BOOT_JDK_JVMARGS=$boot_jdk_jvmargs
-
-  JAVA_FLAGS=$JAVA_FLAGS
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking flags for boot jdk java command for big workloads" >&5
+$as_echo_n "checking flags for boot jdk java command for big workloads... " >&6; }
+
+  # Starting amount of heap memory.
+
+  $ECHO "Check if jvm arg is ok: -Xms64M" >&5
+  $ECHO "Command: $JAVA -Xms64M -version" >&5
+  OUTPUT=`$JAVA -Xms64M -version 2>&1`
+  FOUND_WARN=`$ECHO "$OUTPUT" | grep -i warn`
+  FOUND_VERSION=`$ECHO $OUTPUT | grep " version \""`
+  if test "x$FOUND_VERSION" != x && test "x$FOUND_WARN" = x; then
+    boot_jdk_jvmargs_big="$boot_jdk_jvmargs_big -Xms64M"
+    JVM_ARG_OK=true
+  else
+    $ECHO "Arg failed:" >&5
+    $ECHO "$OUTPUT" >&5
+    JVM_ARG_OK=false
+  fi
+
+
+  # Maximum amount of heap memory.
+  # Maximum stack size.
+  if test "x$BUILD_NUM_BITS" = x32; then
+    JVM_MAX_HEAP=1100M
+    STACK_SIZE=768
+  else
+    # Running Javac on a JVM on a 64-bit machine, takes more space since 64-bit
+    # pointers are used. Apparently, we need to increase the heap and stack
+    # space for the jvm. More specifically, when running javac to build huge
+    # jdk batch
+    JVM_MAX_HEAP=1600M
+    STACK_SIZE=1536
+  fi
+
+  $ECHO "Check if jvm arg is ok: -Xmx$JVM_MAX_HEAP" >&5
+  $ECHO "Command: $JAVA -Xmx$JVM_MAX_HEAP -version" >&5
+  OUTPUT=`$JAVA -Xmx$JVM_MAX_HEAP -version 2>&1`
+  FOUND_WARN=`$ECHO "$OUTPUT" | grep -i warn`
+  FOUND_VERSION=`$ECHO $OUTPUT | grep " version \""`
+  if test "x$FOUND_VERSION" != x && test "x$FOUND_WARN" = x; then
+    boot_jdk_jvmargs_big="$boot_jdk_jvmargs_big -Xmx$JVM_MAX_HEAP"
+    JVM_ARG_OK=true
+  else
+    $ECHO "Arg failed:" >&5
+    $ECHO "$OUTPUT" >&5
+    JVM_ARG_OK=false
+  fi
+
+
+  $ECHO "Check if jvm arg is ok: -XX:ThreadStackSize=$STACK_SIZE" >&5
+  $ECHO "Command: $JAVA -XX:ThreadStackSize=$STACK_SIZE -version" >&5
+  OUTPUT=`$JAVA -XX:ThreadStackSize=$STACK_SIZE -version 2>&1`
+  FOUND_WARN=`$ECHO "$OUTPUT" | grep -i warn`
+  FOUND_VERSION=`$ECHO $OUTPUT | grep " version \""`
+  if test "x$FOUND_VERSION" != x && test "x$FOUND_WARN" = x; then
+    boot_jdk_jvmargs_big="$boot_jdk_jvmargs_big -XX:ThreadStackSize=$STACK_SIZE"
+    JVM_ARG_OK=true
+  else
+    $ECHO "Arg failed:" >&5
+    $ECHO "$OUTPUT" >&5
+    JVM_ARG_OK=false
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $boot_jdk_jvmargs_big" >&5
+$as_echo "$boot_jdk_jvmargs_big" >&6; }
+
+  JAVA_FLAGS_BIG=$boot_jdk_jvmargs_big
+
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking flags for boot jdk java command for small workloads" >&5
+$as_echo_n "checking flags for boot jdk java command for small workloads... " >&6; }
+
+  # Use serial gc for small short lived tools if possible
+
+  $ECHO "Check if jvm arg is ok: -XX:+UseSerialGC" >&5
+  $ECHO "Command: $JAVA -XX:+UseSerialGC -version" >&5
+  OUTPUT=`$JAVA -XX:+UseSerialGC -version 2>&1`
+  FOUND_WARN=`$ECHO "$OUTPUT" | grep -i warn`
+  FOUND_VERSION=`$ECHO $OUTPUT | grep " version \""`
+  if test "x$FOUND_VERSION" != x && test "x$FOUND_WARN" = x; then
+    boot_jdk_jvmargs_small="$boot_jdk_jvmargs_small -XX:+UseSerialGC"
+    JVM_ARG_OK=true
+  else
+    $ECHO "Arg failed:" >&5
+    $ECHO "$OUTPUT" >&5
+    JVM_ARG_OK=false
+  fi
+
+
+  $ECHO "Check if jvm arg is ok: -Xms32M" >&5
+  $ECHO "Command: $JAVA -Xms32M -version" >&5
+  OUTPUT=`$JAVA -Xms32M -version 2>&1`
+  FOUND_WARN=`$ECHO "$OUTPUT" | grep -i warn`
+  FOUND_VERSION=`$ECHO $OUTPUT | grep " version \""`
+  if test "x$FOUND_VERSION" != x && test "x$FOUND_WARN" = x; then
+    boot_jdk_jvmargs_small="$boot_jdk_jvmargs_small -Xms32M"
+    JVM_ARG_OK=true
+  else
+    $ECHO "Arg failed:" >&5
+    $ECHO "$OUTPUT" >&5
+    JVM_ARG_OK=false
+  fi
+
+
+  $ECHO "Check if jvm arg is ok: -Xmx512M" >&5
+  $ECHO "Command: $JAVA -Xmx512M -version" >&5
+  OUTPUT=`$JAVA -Xmx512M -version 2>&1`
+  FOUND_WARN=`$ECHO "$OUTPUT" | grep -i warn`
+  FOUND_VERSION=`$ECHO $OUTPUT | grep " version \""`
+  if test "x$FOUND_VERSION" != x && test "x$FOUND_WARN" = x; then
+    boot_jdk_jvmargs_small="$boot_jdk_jvmargs_small -Xmx512M"
+    JVM_ARG_OK=true
+  else
+    $ECHO "Arg failed:" >&5
+    $ECHO "$OUTPUT" >&5
+    JVM_ARG_OK=false
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $boot_jdk_jvmargs_small" >&5
+$as_echo "$boot_jdk_jvmargs_small" >&6; }
+
+  JAVA_FLAGS_SMALL=$boot_jdk_jvmargs_small
 
 
 
@@ -26297,8 +26371,28 @@
   # Use indirect variable referencing
   toolchain_var_name=VALID_TOOLCHAINS_$OPENJDK_BUILD_OS
   VALID_TOOLCHAINS=${!toolchain_var_name}
-  # First toolchain type in the list is the default
-  DEFAULT_TOOLCHAIN=${VALID_TOOLCHAINS%% *}
+
+  if test "x$OPENJDK_TARGET_OS" = xmacosx; then
+    # On Mac OS X, default toolchain to clang after Xcode 5
+    XCODE_VERSION_OUTPUT=`xcodebuild -version 2>&1 | $HEAD -n 1`
+    $ECHO "$XCODE_VERSION_OUTPUT" | $GREP "Xcode " > /dev/null
+    if test $? -ne 0; then
+      as_fn_error $? "Failed to determine Xcode version." "$LINENO" 5
+    fi
+    XCODE_MAJOR_VERSION=`$ECHO $XCODE_VERSION_OUTPUT | \
+        $SED -e 's/^Xcode \([1-9][0-9.]*\)/\1/' | \
+        $CUT -f 1 -d .`
+    { $as_echo "$as_me:${as_lineno-$LINENO}: Xcode major version: $XCODE_MAJOR_VERSION" >&5
+$as_echo "$as_me: Xcode major version: $XCODE_MAJOR_VERSION" >&6;}
+    if test $XCODE_MAJOR_VERSION -ge 5; then
+        DEFAULT_TOOLCHAIN="clang"
+    else
+        DEFAULT_TOOLCHAIN="gcc"
+    fi
+  else
+    # First toolchain type in the list is the default
+    DEFAULT_TOOLCHAIN=${VALID_TOOLCHAINS%% *}
+  fi
 
   if test "x$with_toolchain_type" = xlist; then
     # List all toolchains
@@ -41236,6 +41330,26 @@
       SET_SHARED_LIBRARY_NAME='-Xlinker -soname=$1'
       SET_SHARED_LIBRARY_MAPFILE='-Xlinker -version-script=$1'
     fi
+  elif test "x$TOOLCHAIN_TYPE" = xclang; then
+    PICFLAG=''
+    C_FLAG_REORDER=''
+    CXX_FLAG_REORDER=''
+
+    if test "x$OPENJDK_TARGET_OS" = xmacosx; then
+      # Linking is different on MacOSX
+      SHARED_LIBRARY_FLAGS="-dynamiclib -compatibility_version 1.0.0 -current_version 1.0.0 $PICFLAG"
+      SET_EXECUTABLE_ORIGIN='-Xlinker -rpath -Xlinker @loader_path/.'
+      SET_SHARED_LIBRARY_ORIGIN="$SET_EXECUTABLE_ORIGIN"
+      SET_SHARED_LIBRARY_NAME='-Xlinker -install_name -Xlinker @rpath/$1'
+      SET_SHARED_LIBRARY_MAPFILE=''
+    else
+      # Default works for linux, might work on other platforms as well.
+      SHARED_LIBRARY_FLAGS='-shared'
+      SET_EXECUTABLE_ORIGIN='-Xlinker -rpath -Xlinker \$$$$ORIGIN$1'
+      SET_SHARED_LIBRARY_ORIGIN="-Xlinker -z -Xlinker origin $SET_EXECUTABLE_ORIGIN"
+      SET_SHARED_LIBRARY_NAME='-Xlinker -soname=$1'
+      SET_SHARED_LIBRARY_MAPFILE='-Xlinker -version-script=$1'
+    fi
   elif test "x$TOOLCHAIN_TYPE" = xsolstudio; then
     PICFLAG="-KPIC"
     C_FLAG_REORDER='-xF'
@@ -41297,6 +41411,8 @@
   # Generate make dependency files
   if test "x$TOOLCHAIN_TYPE" = xgcc; then
     C_FLAG_DEPS="-MMD -MF"
+  elif test "x$TOOLCHAIN_TYPE" = xclang; then
+    C_FLAG_DEPS="-MMD -MF"
   elif test "x$TOOLCHAIN_TYPE" = xsolstudio; then
     C_FLAG_DEPS="-xMMD -xMF"
   elif test "x$TOOLCHAIN_TYPE" = xxlc; then
@@ -41315,6 +41431,9 @@
       CFLAGS_DEBUG_SYMBOLS="-g"
       CXXFLAGS_DEBUG_SYMBOLS="-g"
     fi
+  elif test "x$TOOLCHAIN_TYPE" = xclang; then
+    CFLAGS_DEBUG_SYMBOLS="-g"
+    CXXFLAGS_DEBUG_SYMBOLS="-g"
   elif test "x$TOOLCHAIN_TYPE" = xsolstudio; then
     CFLAGS_DEBUG_SYMBOLS="-g -xs"
     CXXFLAGS_DEBUG_SYMBOLS="-g0 -xs"
@@ -41370,6 +41489,20 @@
         C_O_FLAG_NORM="-O2"
         C_O_FLAG_NONE="-O0"
       fi
+    elif test "x$TOOLCHAIN_TYPE" = xclang; then
+      if test "x$OPENJDK_TARGET_OS" = xmacosx; then
+        # On MacOSX we optimize for size, something
+        # we should do for all platforms?
+        C_O_FLAG_HIGHEST="-Os"
+        C_O_FLAG_HI="-Os"
+        C_O_FLAG_NORM="-Os"
+        C_O_FLAG_NONE=""
+      else
+        C_O_FLAG_HIGHEST="-O3"
+        C_O_FLAG_HI="-O3"
+        C_O_FLAG_NORM="-O2"
+        C_O_FLAG_NONE="-O0"
+      fi
     elif test "x$TOOLCHAIN_TYPE" = xxlc; then
       C_O_FLAG_HIGHEST="-O3"
       C_O_FLAG_HI="-O3 -qstrict"
@@ -46791,6 +46924,118 @@
 
   ###############################################################################
   #
+  # Check for the png library
+  #
+
+
+# Check whether --with-libpng was given.
+if test "${with_libpng+set}" = set; then :
+  withval=$with_libpng;
+fi
+
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for which libpng to use" >&5
+$as_echo_n "checking for which libpng to use... " >&6; }
+
+  # default is bundled
+  DEFAULT_LIBPNG=bundled
+
+  #
+  # if user didn't specify, use DEFAULT_LIBPNG
+  #
+  if test "x${with_libpng}" = "x"; then
+      with_libpng=${DEFAULT_LIBPNG}
+  fi
+
+  if test "x${with_libpng}" = "xbundled"; then
+      USE_EXTERNAL_LIBPNG=false
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: bundled" >&5
+$as_echo "bundled" >&6; }
+  elif test "x${with_libpng}" = "xsystem"; then
+
+pkg_failed=no
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for PNG" >&5
+$as_echo_n "checking for PNG... " >&6; }
+
+if test -n "$PNG_CFLAGS"; then
+    pkg_cv_PNG_CFLAGS="$PNG_CFLAGS"
+ elif test -n "$PKG_CONFIG"; then
+    if test -n "$PKG_CONFIG" && \
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libpng\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "libpng") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+  pkg_cv_PNG_CFLAGS=`$PKG_CONFIG --cflags "libpng" 2>/dev/null`
+else
+  pkg_failed=yes
+fi
+ else
+    pkg_failed=untried
+fi
+if test -n "$PNG_LIBS"; then
+    pkg_cv_PNG_LIBS="$PNG_LIBS"
+ elif test -n "$PKG_CONFIG"; then
+    if test -n "$PKG_CONFIG" && \
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libpng\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "libpng") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+  pkg_cv_PNG_LIBS=`$PKG_CONFIG --libs "libpng" 2>/dev/null`
+else
+  pkg_failed=yes
+fi
+ else
+    pkg_failed=untried
+fi
+
+
+
+if test $pkg_failed = yes; then
+
+if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
+        _pkg_short_errors_supported=yes
+else
+        _pkg_short_errors_supported=no
+fi
+        if test $_pkg_short_errors_supported = yes; then
+	        PNG_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors "libpng" 2>&1`
+        else
+	        PNG_PKG_ERRORS=`$PKG_CONFIG --print-errors "libpng" 2>&1`
+        fi
+	# Put the nasty error message in config.log where it belongs
+	echo "$PNG_PKG_ERRORS" >&5
+
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+                 LIBPNG_FOUND=no
+elif test $pkg_failed = untried; then
+	 LIBPNG_FOUND=no
+else
+	PNG_CFLAGS=$pkg_cv_PNG_CFLAGS
+	PNG_LIBS=$pkg_cv_PNG_LIBS
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+	 LIBPNG_FOUND=yes
+fi
+      if test "x${LIBPNG_FOUND}" = "xyes"; then
+          USE_EXTERNAL_LIBPNG=true
+          { $as_echo "$as_me:${as_lineno-$LINENO}: result: system" >&5
+$as_echo "system" >&6; }
+      else
+          { $as_echo "$as_me:${as_lineno-$LINENO}: result: system not found" >&5
+$as_echo "system not found" >&6; }
+          as_fn_error $? "--with-libpng=system specified, but no libpng found!" "$LINENO" 5
+      fi
+  else
+      as_fn_error $? "Invalid value of --with-libpng: ${with_libpng}, use 'system' or 'bundled'" "$LINENO" 5
+  fi
+
+
+  ###############################################################################
+  #
   # Check for the zlib library
   #
 
--- a/common/autoconf/libraries.m4	Tue Mar 25 12:31:49 2014 -0700
+++ b/common/autoconf/libraries.m4	Wed Jul 05 19:33:51 2017 +0200
@@ -654,6 +654,46 @@
 
   ###############################################################################
   #
+  # Check for the png library
+  #
+
+  AC_ARG_WITH(libpng, [AS_HELP_STRING([--with-libpng],
+     [use libpng from build system or OpenJDK source (system, bundled) @<:@bundled@:>@])])
+
+
+  AC_MSG_CHECKING([for which libpng to use])
+
+  # default is bundled
+  DEFAULT_LIBPNG=bundled
+
+  #
+  # if user didn't specify, use DEFAULT_LIBPNG
+  #
+  if test "x${with_libpng}" = "x"; then
+      with_libpng=${DEFAULT_LIBPNG}
+  fi
+
+  if test "x${with_libpng}" = "xbundled"; then
+      USE_EXTERNAL_LIBPNG=false
+      AC_MSG_RESULT([bundled])
+  elif test "x${with_libpng}" = "xsystem"; then
+      PKG_CHECK_MODULES(PNG, libpng,
+                   [ LIBPNG_FOUND=yes ],
+                   [ LIBPNG_FOUND=no ])
+      if test "x${LIBPNG_FOUND}" = "xyes"; then
+          USE_EXTERNAL_LIBPNG=true
+          AC_MSG_RESULT([system])
+      else
+          AC_MSG_RESULT([system not found])
+          AC_MSG_ERROR([--with-libpng=system specified, but no libpng found!])
+      fi
+  else
+      AC_MSG_ERROR([Invalid value of --with-libpng: ${with_libpng}, use 'system' or 'bundled'])
+  fi
+  AC_SUBST(USE_EXTERNAL_LIBPNG)
+
+  ###############################################################################
+  #
   # Check for the zlib library
   #
 
--- a/common/autoconf/spec.gmk.in	Tue Mar 25 12:31:49 2014 -0700
+++ b/common/autoconf/spec.gmk.in	Wed Jul 05 19:33:51 2017 +0200
@@ -254,7 +254,6 @@
 
 # The boot jdk to use
 BOOT_JDK:=@BOOT_JDK@
-BOOT_JDK_JVMARGS:=@BOOT_JDK_JVMARGS@
 BOOT_RTJAR:=@BOOT_RTJAR@
 BOOT_TOOLSJAR=$(BOOT_JDK)/lib/tools.jar
 
@@ -442,8 +441,11 @@
 POST_MCS_CMD:=@POST_MCS_CMD@
 
 JAVA_FLAGS:=@JAVA_FLAGS@
+JAVA_FLAGS_BIG:=@JAVA_FLAGS_BIG@
+JAVA_FLAGS_SMALL:=@JAVA_FLAGS_SMALL@
 
-JAVA=@FIXPATH@ @JAVA@ $(JAVA_FLAGS)
+JAVA=@FIXPATH@ @JAVA@ $(JAVA_FLAGS_BIG) $(JAVA_FLAGS)
+JAVA_SMALL=@FIXPATH@ @JAVA@ $(JAVA_FLAGS_SMALL) $(JAVA_FLAGS)
 
 JAVAC:=@FIXPATH@ @JAVAC@
 # Hotspot sets this variable before reading the SPEC when compiling sa-jdi.jar. Avoid
@@ -454,7 +456,7 @@
 
 JAR:=@FIXPATH@ @JAR@
 
-NATIVE2ASCII:=@FIXPATH@ @NATIVE2ASCII@
+NATIVE2ASCII:=@FIXPATH@ @NATIVE2ASCII@ $(addprefix -J, $(JAVA_FLAGS_SMALL))
 
 JARSIGNER:=@FIXPATH@ @JARSIGNER@
 
@@ -645,6 +647,15 @@
 # Read-only single-machine data
 INSTALL_SYSCONFDIR=@sysconfdir@
 
+####################################################
+#
+# Libraries
+#
+
+USE_EXTERNAL_LIBPNG:=@USE_EXTERNAL_LIBPNG@
+PNG_LIBS:=@PNG_LIBS@
+PNG_CFLAGS:=@PNG_CFLAGS@
+
 
 ####################################################
 #
--- a/common/autoconf/toolchain.m4	Tue Mar 25 12:31:49 2014 -0700
+++ b/common/autoconf/toolchain.m4	Wed Jul 05 19:33:51 2017 +0200
@@ -96,8 +96,27 @@
   # Use indirect variable referencing
   toolchain_var_name=VALID_TOOLCHAINS_$OPENJDK_BUILD_OS
   VALID_TOOLCHAINS=${!toolchain_var_name}
-  # First toolchain type in the list is the default
-  DEFAULT_TOOLCHAIN=${VALID_TOOLCHAINS%% *}
+
+  if test "x$OPENJDK_TARGET_OS" = xmacosx; then
+    # On Mac OS X, default toolchain to clang after Xcode 5
+    XCODE_VERSION_OUTPUT=`xcodebuild -version 2>&1 | $HEAD -n 1`
+    $ECHO "$XCODE_VERSION_OUTPUT" | $GREP "Xcode " > /dev/null
+    if test $? -ne 0; then
+      AC_MSG_ERROR([Failed to determine Xcode version.])
+    fi
+    XCODE_MAJOR_VERSION=`$ECHO $XCODE_VERSION_OUTPUT | \
+        $SED -e 's/^Xcode \(@<:@1-9@:>@@<:@0-9.@:>@*\)/\1/' | \
+        $CUT -f 1 -d .`
+    AC_MSG_NOTICE([Xcode major version: $XCODE_MAJOR_VERSION])
+    if test $XCODE_MAJOR_VERSION -ge 5; then
+        DEFAULT_TOOLCHAIN="clang"
+    else
+        DEFAULT_TOOLCHAIN="gcc"
+    fi
+  else
+    # First toolchain type in the list is the default
+    DEFAULT_TOOLCHAIN=${VALID_TOOLCHAINS%% *}
+  fi
   
   if test "x$with_toolchain_type" = xlist; then
     # List all toolchains
--- a/corba/.hgtags	Tue Mar 25 12:31:49 2014 -0700
+++ b/corba/.hgtags	Wed Jul 05 19:33:51 2017 +0200
@@ -247,3 +247,4 @@
 8394993063135a42b63a94473280399fb2a13aa7 jdk9-b02
 d338b892a13db19b093f85cf5f949a4504e4d31f jdk9-b03
 1ed19de263e1e0772da0269118cdd9deeb9fff04 jdk9-b04
+167c39eb44731a5d66770d0f00e231164653a2ff jdk9-b05
--- a/corba/make/CompileCorba.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/corba/make/CompileCorba.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -45,16 +45,18 @@
         org/omg/PortableInterceptor/UNKNOWN.java \
         com/sun/tools/corba/se/idl/ResourceBundleUtil.java \
         com/sun/corba/se/impl/presentation/rmi/jndi.properties, \
-    COPY := .prp LogStrings.properties, \
+    COPY := .prp, \
+    CLEAN := .properties, \
     BIN := $(CORBA_OUTPUTDIR)/classes, \
     JAR := $(CORBA_OUTPUTDIR)/dist/lib/classes.jar))
 
+# For the interim version, don't bother cleaning the properties.
 $(eval $(call SetupJavaCompilation,BUILD_INTERIM_CORBA, \
     SETUP := GENERATE_OLDBYTECODE, \
     SRC := $(BUILD_CORBA_SRC), \
     EXCLUDES := $(BUILD_CORBA_EXCLUDES), \
     EXCLUDE_FILES := $(BUILD_CORBA_EXCLUDE_FILES), \
-    COPY := $(BUILD_CORBA_COPY), \
+    COPY := $(BUILD_CORBA_COPY) $(BUILD_CORBA_CLEAN), \
     BIN := $(CORBA_OUTPUTDIR)/interim_classes, \
     JAR := $(INTERIM_CORBA_JAR)))
 
@@ -63,7 +65,6 @@
 $(eval $(call SetupZipArchive,ARCHIVE_CORBA_SRC, \
     SRC := $(CORBA_TOPDIR)/src/share/classes $(CORBA_OUTPUTDIR)/gensrc, \
     ZIP := $(CORBA_OUTPUTDIR)/dist/lib/src.zip))
-    JAR := $(CORBA_OUTPUTDIR)/dist/lib/classes.jar))
 
 ################################################################################
 # Create bin.zip containing the corba specific binaries: orb.idl, ir.idl
@@ -81,6 +82,5 @@
 
 ################################################################################
 
-
 all: $(BUILD_CORBA) $(BUILD_INTERIM_CORBA) $(ARCHIVE_CORBA_SRC) \
     $(CORBA_OUTPUTDIR)/dist/lib/bin.zip
--- a/corba/make/GensrcCorba.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/corba/make/GensrcCorba.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -39,9 +39,6 @@
     SRC := $(CORBA_TOPDIR)/make/src/classes, \
     BIN := $(CORBA_OUTPUTDIR)/tools_classes))
 
-TOOL_STRIPPROP_CMD := $(JAVA) -cp $(CORBA_OUTPUTDIR)/tools_classes \
-    build.tools.stripproperties.StripPropertiesCorba
-
 TOOL_LOGUTIL_CMD := $(JAVA) -cp $(CORBA_OUTPUTDIR)/tools_classes \
     build.tools.logutil.MC
 
@@ -230,27 +227,14 @@
 $(BUILD_IDLS): $(BUILD_IDLJ)
 
 ################################################################################
-# Run stripproperties on all sunorb resource files.
+# zh_HK is just a copy of zh_TW
 
-STRIP_PROP_SRC_FILES := $(shell $(FIND) $(CORBA_TOPDIR)/src/share/classes -name "sunorb*.properties")
-STRIP_PROP_FILES := $(patsubst $(CORBA_TOPDIR)/src/share/classes/%, $(CORBA_OUTPUTDIR)/classes/%, \
-    $(STRIP_PROP_SRC_FILES))
-# Simple delivery of zh_HK properties files just copies zh_TW properties files
-STRIP_PROP_SRC_FILE_ZH_TW := $(shell $(FIND) $(CORBA_TOPDIR)/src/share/classes -name "sunorb_zh_TW.properties")
-STRIP_PROP_SRC_FILES += $(STRIP_PROP_SRC_FILE_ZH_TW)
-STRIP_PROP_FILES += $(patsubst $(CORBA_TOPDIR)/src/share/classes/%_zh_TW.properties, \
-    $(CORBA_OUTPUTDIR)/classes/%_zh_HK.properties, $(STRIP_PROP_SRC_FILE_ZH_TW))
-STRIP_PROP_CMDLINE := $(subst _SPACE_, $(SPACE), \
-    $(join $(addprefix -clean_SPACE_, $(STRIP_PROP_SRC_FILES)), \
-    $(addprefix _SPACE_, $(STRIP_PROP_FILES))))
-
-$(CORBA_OUTPUTDIR)/_the.stripped_properties: $(STRIP_PROP_SRC_FILES) \
-    $(BUILD_TOOLS)
-	$(MKDIR) -p $(sort $(dir $(STRIP_PROP_FILES)))
-	$(call ListPathsSafely,STRIP_PROP_CMDLINE,\n, >> $(CORBA_OUTPUTDIR)/_the.strip_prop.cmdline)
-	$(TOOL_STRIPPROP_CMD) @$(CORBA_OUTPUTDIR)/_the.strip_prop.cmdline
-	$(TOUCH) $@
+$(CORBA_OUTPUTDIR)/gensrc/com/sun/corba/se/impl/orbutil/resources/sunorb_zh_HK.properties: \
+    $(CORBA_TOPDIR)/src/share/classes/com/sun/corba/se/impl/orbutil/resources/sunorb_zh_TW.properties
+	$(install-file)
 
 ################################################################################
 
-all: $(BUILD_IDLS) $(CORBA_OUTPUTDIR)/_the.stripped_properties $(LOGWRAPPER_TARGETS)
+all: $(BUILD_IDLS) $(LOGWRAPPER_TARGETS) \
+    $(CORBA_OUTPUTDIR)/gensrc/com/sun/corba/se/impl/orbutil/resources/sunorb_zh_HK.properties
+
--- a/corba/make/src/classes/build/tools/stripproperties/StripPropertiesCorba.java	Tue Mar 25 12:31:49 2014 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,288 +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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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 build.tools.stripproperties;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedWriter;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-
-/**
- * Reads a properties file from standard input and writes an equivalent
- * properties file without comments to standard output.
- */
-public class StripPropertiesCorba {
-
-    private static void error(String msg, Exception e) {
-        System.err.println("ERROR: stripproperties: " + msg);
-        if ( e != null ) {
-            System.err.println("EXCEPTION: " + e.toString());
-            e.printStackTrace();
-        }
-    }
-
-    private static List<String> infiles = new ArrayList<String>();
-    private static List<String> outfiles = new ArrayList<String>();
-
-    private static boolean parseOptions(String args[]) {
-        boolean ok = true;
-
-        for ( int i = 0; i < args.length ; i++ ) {
-            if ( "-clean".equals(args[i]) && i+2 < args.length ) {
-                infiles.add(args[++i]);
-                outfiles.add(args[++i]);
-            } else if ( args[i].charAt(0)=='@') {
-                String filename = args[i].substring(1);
-                FileInputStream finput = null;
-                byte contents[] = null;
-                try {
-                    finput = new FileInputStream(filename);
-                    int byteCount = finput.available();
-                    if ( byteCount <= 0 ) {
-                        error("The @file is empty", null);
-                        ok = false;
-                    } else {
-                        contents = new byte[byteCount];
-                        int bytesRead = finput.read(contents);
-                        if ( byteCount != bytesRead ) {
-                            error("Cannot read all of @file", null);
-                            ok = false;
-                        }
-                    }
-                } catch ( IOException e ) {
-                    error("cannot open " + filename, e);
-                    ok = false;
-                }
-                if ( finput != null ) {
-                    try {
-                        finput.close();
-                    } catch ( IOException e ) {
-                        ok = false;
-                        error("cannot close " + filename, e);
-                    }
-                }
-                if ( ok && contents != null ) {
-                    String tokens[] = (new String(contents)).split("\\s+");
-                    if ( tokens.length > 0 ) {
-                        ok = parseOptions(tokens);
-                    }
-                }
-                if ( !ok ) {
-                    break;
-                }
-            } else {
-                infiles.add(args[i]);
-                outfiles.add(args[i]);
-            }
-        }
-        return ok;
-    }
-
-    private static boolean stripFiles(List<String> infiles, List<String> outfiles) {
-        boolean ok = true;
-        Iterator<String> inIter  = infiles.iterator();
-        Iterator<String> outIter = outfiles.iterator();
-
-        for (; inIter.hasNext(); ) {
-            String infile = inIter.next();
-            String outfile = outIter.next();
-
-            Properties prop = new Properties();
-            InputStream in = null;
-            try {
-                in = new BufferedInputStream(new FileInputStream(infile));
-                prop.load(in);
-            } catch ( FileNotFoundException e ) {
-                error("Cannot access file " + infile, e);
-                ok = false;
-            } catch ( IOException e ) {
-                error("IO exception processing file " + infile, e);
-                ok = false;
-            }
-            if ( in != null ) {
-                try {
-                    in.close();
-                } catch ( IOException e ) {
-                    error("IO exception closing file " + infile, e);
-                    ok = false;
-                }
-            }
-            if ( !ok ) {
-                break;
-            }
-
-            OutputStream out = null;
-            try {
-                out = new FileOutputStream(outfile);
-                storeProperties(prop, out);
-                out.flush();
-            } catch ( IOException e ) {
-                error("IO exception processing file " + outfile, e);
-                ok = false;
-            }
-            if ( out != null ) {
-                try {
-                    out.close();
-                } catch ( IOException e ) {
-                    error("IO exception closing file " + outfile, e);
-                    ok = false;
-                }
-            }
-            if ( !ok ) {
-                break;
-            }
-
-        }
-        return ok;
-    }
-
-    /**
-     * Strip the properties filenames supplied, replacing their contents.
-     * @param args Names of properties files to process and replace contents
-     */
-    public static void main(String args[]) {
-        boolean ok = parseOptions(args);
-        if ( !ok || !stripFiles(infiles, outfiles) ) {
-            System.exit(1);
-        }
-    }
-
-    // --- code below here is adapted from java.util.Properties ---
-
-    private static final String specialSaveChars = "=: \t\r\n\f#!";
-
-    /*
-     * Converts unicodes to encoded &#92;uxxxx
-     * and writes out any of the characters in specialSaveChars
-     * with a preceding slash
-     */
-    private static String saveConvert(String theString, boolean escapeSpace) {
-        int len = theString.length();
-        StringBuffer outBuffer = new StringBuffer(len*2);
-
-        for(int x=0; x<len; x++) {
-            char aChar = theString.charAt(x);
-            switch(aChar) {
-                case ' ':
-                    if (x == 0 || escapeSpace) {
-                        outBuffer.append('\\');
-                    }
-                    outBuffer.append(' ');
-                    break;
-                case '\\':
-                    outBuffer.append('\\');
-                    outBuffer.append('\\');
-                    break;
-                case '\t':
-                    outBuffer.append('\\');
-                    outBuffer.append('t');
-                    break;
-                case '\n':
-                    outBuffer.append('\\');
-                    outBuffer.append('n');
-                    break;
-                case '\r':
-                    outBuffer.append('\\');
-                    outBuffer.append('r');
-                    break;
-                case '\f':
-                    outBuffer.append('\\');
-                    outBuffer.append('f');
-                    break;
-                default:
-                    if ((aChar < 0x0020) || (aChar == 0x007e) || (aChar > 0x00ff)) {
-                        outBuffer.append('\\');
-                        outBuffer.append('u');
-                        outBuffer.append(toHex((aChar >> 12) & 0xF));
-                        outBuffer.append(toHex((aChar >>  8) & 0xF));
-                        outBuffer.append(toHex((aChar >>  4) & 0xF));
-                        outBuffer.append(toHex( aChar        & 0xF));
-                    } else {
-                        if (specialSaveChars.indexOf(aChar) != -1) {
-                            outBuffer.append('\\');
-                        }
-                        outBuffer.append(aChar);
-                    }
-            }
-        }
-        return outBuffer.toString();
-    }
-
-    /**
-     * Writes the content of <code>properties</code> to <code>out</code>.
-     * The format is that of Properties.store with the following modifications:
-     * <ul>
-     * <li>No header or date is written
-     * <li>Latin-1 characters are written as single bytes, not escape sequences
-     * <li>Line breaks are indicated by a single \n independent of platform
-     * <ul>
-     */
-    private static void storeProperties(Properties properties, OutputStream out)
-    throws IOException {
-        BufferedWriter awriter;
-        awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
-        for (Enumeration<Object> e = properties.keys(); e.hasMoreElements();) {
-            String key = (String)e.nextElement();
-            String val = (String)properties.get(key);
-            key = saveConvert(key, true);
-
-            /* No need to escape embedded and trailing spaces for value, hence
-             * pass false to flag.
-             */
-            val = saveConvert(val, false);
-            writeln(awriter, key + "=" + val);
-        }
-        awriter.flush();
-    }
-
-    private static void writeln(BufferedWriter bw, String s) throws IOException {
-        bw.write(s);
-        bw.write("\n");
-    }
-
-    /**
-     * Convert a nibble to a hex character
-     * @param   nibble  the nibble to convert.
-     */
-    private static char toHex(int nibble) {
-        return hexDigit[(nibble & 0xF)];
-    }
-
-    /** A table of hex digits */
-    private static final char[] hexDigit = {
-        '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
-    };
-}
--- a/hotspot/.hgtags	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/.hgtags	Wed Jul 05 19:33:51 2017 +0200
@@ -407,3 +407,4 @@
 b188446de75bda5fc52d102cddf242c3ef5ecbdf jdk9-b02
 b2fee789d23f3cdabb3db4e51af43038e5692d3a jdk9-b03
 3812c088b9456ee22c933e88aee1ece71f4e783a jdk9-b04
+bdc5311e1db7598589b77015119b821bf8c828bd jdk9-b05
--- a/hotspot/make/aix/Makefile	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/make/aix/Makefile	Wed Jul 05 19:33:51 2017 +0200
@@ -70,6 +70,10 @@
     FORCE_TIERED=1
   endif
 endif
+# C1 is not ported on ppc64(le), so we cannot build a tiered VM:
+ifneq (,$(filter $(ARCH),ppc64 pp64le))
+  FORCE_TIERED=0
+endif
 
 ifdef LP64
   ifeq ("$(filter $(LP64_ARCH),$(BUILDARCH))","")
--- a/hotspot/make/aix/makefiles/adjust-mflags.sh	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/make/aix/makefiles/adjust-mflags.sh	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 #! /bin/sh
 #
-# Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -64,7 +64,7 @@
 	echo "$MFLAGS" \
 	| sed '
 		s/^-/ -/
-		s/ -\([^ 	][^ 	]*\)j/ -\1 -j/
+		s/ -\([^ 	I][^ 	I]*\)j/ -\1 -j/
 		s/ -j[0-9][0-9]*/ -j/
 		s/ -j\([^ 	]\)/ -j -\1/
 		s/ -j/ -j'${HOTSPOT_BUILD_JOBS:-${default_build_jobs}}'/
--- a/hotspot/make/bsd/makefiles/gcc.make	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/make/bsd/makefiles/gcc.make	Wed Jul 05 19:33:51 2017 +0200
@@ -260,7 +260,7 @@
   WARNINGS_ARE_ERRORS += -Wno-empty-body
 endif
 
-WARNING_FLAGS = -Wpointer-arith -Wsign-compare -Wundef -Wunused-function -Wformat=2 -Wno-error=format-nonliteral
+WARNING_FLAGS = -Wpointer-arith -Wsign-compare -Wundef -Wunused-function -Wformat=2
 
 ifeq ($(USE_CLANG),)
   # Since GCC 4.3, -Wconversion has changed its meanings to warn these implicit
--- a/hotspot/make/linux/Makefile	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/make/linux/Makefile	Wed Jul 05 19:33:51 2017 +0200
@@ -66,6 +66,10 @@
     FORCE_TIERED=1
   endif
 endif
+# C1 is not ported on ppc64(le), so we cannot build a tiered VM:
+ifneq (,$(filter $(ARCH),ppc64 pp64le))
+  FORCE_TIERED=0
+endif
 
 ifdef LP64
   ifeq ("$(filter $(LP64_ARCH),$(BUILDARCH))","")
--- a/hotspot/make/linux/makefiles/gcc.make	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/make/linux/makefiles/gcc.make	Wed Jul 05 19:33:51 2017 +0200
@@ -215,7 +215,7 @@
   WARNINGS_ARE_ERRORS += -Wno-return-type -Wno-empty-body
 endif
 
-WARNING_FLAGS = -Wpointer-arith -Wsign-compare -Wundef -Wunused-function -Wunused-value -Wformat=2 -Wno-error=format-nonliteral
+WARNING_FLAGS = -Wpointer-arith -Wsign-compare -Wundef -Wunused-function -Wunused-value -Wformat=2
 
 ifeq ($(USE_CLANG),)
   # Since GCC 4.3, -Wconversion has changed its meanings to warn these implicit
--- a/hotspot/make/linux/makefiles/zeroshark.make	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/make/linux/makefiles/zeroshark.make	Wed Jul 05 19:33:51 2017 +0200
@@ -25,6 +25,9 @@
 
 # Setup common to Zero (non-Shark) and Shark versions of VM
 
+# override this from the main file because some version of llvm do not like -Wundef
+WARNING_FLAGS = -Wpointer-arith -Wsign-compare -Wunused-function -Wunused-value
+
 # The copied fdlibm routines in sharedRuntimeTrig.o must not be optimized
 OPT_CFLAGS/sharedRuntimeTrig.o = $(OPT_CFLAGS/NOOPT)
 # The copied fdlibm routines in sharedRuntimeTrans.o must not be optimized
--- a/hotspot/make/solaris/makefiles/gcc.make	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/make/solaris/makefiles/gcc.make	Wed Jul 05 19:33:51 2017 +0200
@@ -118,7 +118,7 @@
 # Compiler warnings are treated as errors 
 WARNINGS_ARE_ERRORS = -Werror 
 # Enable these warnings. See 'info gcc' about details on these options
-WARNING_FLAGS = -Wpointer-arith -Wconversion -Wsign-compare -Wundef -Wformat=2 -Wno-error=format-nonliteral
+WARNING_FLAGS = -Wpointer-arith -Wconversion -Wsign-compare -Wundef -Wformat=2
 CFLAGS_WARN/DEFAULT = $(WARNINGS_ARE_ERRORS) $(WARNING_FLAGS)
 # Special cases 
 CFLAGS_WARN/BYFILE = $(CFLAGS_WARN/$@)$(CFLAGS_WARN/DEFAULT$(CFLAGS_WARN/$@))  
--- a/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -124,6 +124,7 @@
   }
 };
 
+#if !defined(ABI_ELFv2)
 // A ppc64 function descriptor.
 struct FunctionDescriptor VALUE_OBJ_CLASS_SPEC {
  private:
@@ -161,6 +162,7 @@
     _env   = (address) 0xbad;
   }
 };
+#endif
 
 class Assembler : public AbstractAssembler {
  protected:
@@ -1067,6 +1069,7 @@
   // Emit an address.
   inline address emit_addr(const address addr = NULL);
 
+#if !defined(ABI_ELFv2)
   // Emit a function descriptor with the specified entry point, TOC,
   // and ENV. If the entry point is NULL, the descriptor will point
   // just past the descriptor.
@@ -1074,6 +1077,7 @@
   inline address emit_fd(address entry = NULL,
                          address toc = (address) FunctionDescriptor::friend_toc,
                          address env = (address) FunctionDescriptor::friend_env);
+#endif
 
   /////////////////////////////////////////////////////////////////////////////////////
   // PPC instructions
--- a/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -55,6 +55,7 @@
   return start;
 }
 
+#if !defined(ABI_ELFv2)
 // Emit a function descriptor with the specified entry point, TOC, and
 // ENV. If the entry point is NULL, the descriptor will point just
 // past the descriptor.
@@ -73,6 +74,7 @@
 
   return (address)fd;
 }
+#endif
 
 // Issue an illegal instruction. 0 is guaranteed to be an illegal instruction.
 inline void Assembler::illtrap() { Assembler::emit_int32(0); }
--- a/hotspot/src/cpu/ppc/vm/cppInterpreter_ppc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/cppInterpreter_ppc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1136,7 +1136,9 @@
   // (outgoing C args), R3_ARG1 to R10_ARG8, and F1_ARG1 to
   // F13_ARG13.
   __ mr(R3_ARG1, R18_locals);
+#if !defined(ABI_ELFv2)
   __ ld(signature_handler_fd, 0, signature_handler_fd);
+#endif
   __ call_stub(signature_handler_fd);
   // reload method
   __ ld(R19_method, state_(_method));
@@ -1295,8 +1297,13 @@
   // native result acrosss the call. No oop is present
 
   __ mr(R3_ARG1, R16_thread);
+#if defined(ABI_ELFv2)
+  __ call_c(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans),
+            relocInfo::none);
+#else
   __ call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, JavaThread::check_special_condition_for_native_trans),
             relocInfo::none);
+#endif
   __ bind(sync_check_done);
 
   //=============================================================================
@@ -1346,9 +1353,9 @@
   // notify here, we'll drop it on the floor.
 
   __ notify_method_exit(true/*native method*/,
-                        ilgl /*illegal state (not used for native methods)*/);
-
-
+                        ilgl /*illegal state (not used for native methods)*/,
+                        InterpreterMacroAssembler::NotifyJVMTI,
+                        false /*check_exceptions*/);
 
   //=============================================================================
   // Handle exceptions
@@ -1413,7 +1420,7 @@
   // First, pop to caller's frame.
   __ pop_interpreter_frame(R11_scratch1, R12_scratch2, R21_tmp1  /* set to return pc */, R22_tmp2);
 
-  __ push_frame_abi112(0, R11_scratch1);
+  __ push_frame_reg_args(0, R11_scratch1);
   // Get the address of the exception handler.
   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address),
                   R16_thread,
@@ -2545,7 +2552,7 @@
   __ mr(R4_ARG2, R3_ARG1);  // ARG2 := ARG1
 
   // Find the address of the "catch_exception" stub.
-  __ push_frame_abi112(0, R11_scratch1);
+  __ push_frame_reg_args(0, R11_scratch1);
   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address),
                   R16_thread,
                   R4_ARG2);
--- a/hotspot/src/cpu/ppc/vm/frame_ppc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/frame_ppc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright 2012, 2014 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
@@ -42,10 +42,6 @@
 #include "runtime/vframeArray.hpp"
 #endif
 
-#ifndef CC_INTERP
-#error "CC_INTERP must be defined on PPC64"
-#endif
-
 #ifdef ASSERT
 void RegisterMap::check_location_valid() {
 }
@@ -89,7 +85,10 @@
 
 frame frame::sender_for_interpreter_frame(RegisterMap *map) const {
   // Pass callers initial_caller_sp as unextended_sp.
-  return frame(sender_sp(), sender_pc(), (intptr_t*)((parent_ijava_frame_abi *)callers_abi())->initial_caller_sp);
+  return frame(sender_sp(), sender_pc(),
+               CC_INTERP_ONLY((intptr_t*)((parent_ijava_frame_abi *)callers_abi())->initial_caller_sp)
+               NOT_CC_INTERP((intptr_t*)get_ijava_state()->sender_sp)
+               );
 }
 
 frame frame::sender_for_compiled_frame(RegisterMap *map) const {
@@ -183,6 +182,9 @@
     interpreterState istate = get_interpreterState();
     address lresult = (address)istate + in_bytes(BytecodeInterpreter::native_lresult_offset());
     address fresult = (address)istate + in_bytes(BytecodeInterpreter::native_fresult_offset());
+#else
+    address lresult = (address)&(get_ijava_state()->lresult);
+    address fresult = (address)&(get_ijava_state()->fresult);
 #endif
 
     switch (method->result_type()) {
@@ -259,7 +261,21 @@
     values.describe(frame_no, (intptr_t*)&(istate->_native_fresult), " native_fresult");
     values.describe(frame_no, (intptr_t*)&(istate->_native_lresult), " native_lresult");
 #else
-    Unimplemented();
+#define DESCRIBE_ADDRESS(name) \
+  values.describe(frame_no, (intptr_t*)&(get_ijava_state()->name), #name);
+
+      DESCRIBE_ADDRESS(method);
+      DESCRIBE_ADDRESS(locals);
+      DESCRIBE_ADDRESS(monitors);
+      DESCRIBE_ADDRESS(cpoolCache);
+      DESCRIBE_ADDRESS(bcp);
+      DESCRIBE_ADDRESS(esp);
+      DESCRIBE_ADDRESS(mdx);
+      DESCRIBE_ADDRESS(top_frame_sp);
+      DESCRIBE_ADDRESS(sender_sp);
+      DESCRIBE_ADDRESS(oop_tmp);
+      DESCRIBE_ADDRESS(lresult);
+      DESCRIBE_ADDRESS(fresult);
 #endif
   }
 }
--- a/hotspot/src/cpu/ppc/vm/frame_ppc.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/frame_ppc.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright 2012, 2014 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
@@ -29,10 +29,6 @@
 #include "runtime/synchronizer.hpp"
 #include "utilities/top.hpp"
 
-#ifndef CC_INTERP
-#error "CC_INTERP must be defined on PPC64"
-#endif
-
   //  C frame layout on PPC-64.
   //
   //  In this figure the stack grows upwards, while memory grows
@@ -50,7 +46,7 @@
   //            [C_FRAME]
   //
   //  C_FRAME:
-  //    0       [ABI_112]
+  //    0       [ABI_REG_ARGS]
   //    112     CARG_9: outgoing arg 9 (arg_1 ... arg_8 via gpr_3 ... gpr_{10})
   //            ...
   //    40+M*8  CARG_M: outgoing arg M (M is the maximum of outgoing args taken over all call sites in the procedure)
@@ -77,7 +73,7 @@
   //    32      reserved
   //    40      space for TOC (=R2) register for next call
   //
-  //  ABI_112:
+  //  ABI_REG_ARGS:
   //    0       [ABI_48]
   //    48      CARG_1: spill slot for outgoing arg 1. used by next callee.
   //    ...     ...
@@ -95,23 +91,25 @@
     log_2_of_alignment_in_bits = 7
   };
 
-  // ABI_48:
-  struct abi_48 {
+  // ABI_MINFRAME:
+  struct abi_minframe {
     uint64_t callers_sp;
     uint64_t cr;                                  //_16
     uint64_t lr;
+#if !defined(ABI_ELFv2)
     uint64_t reserved1;                           //_16
     uint64_t reserved2;
+#endif
     uint64_t toc;                                 //_16
     // nothing to add here!
     // aligned to frame::alignment_in_bytes (16)
   };
 
   enum {
-    abi_48_size = sizeof(abi_48)
+    abi_minframe_size = sizeof(abi_minframe)
   };
 
-  struct abi_112 : abi_48 {
+  struct abi_reg_args : abi_minframe {
     uint64_t carg_1;
     uint64_t carg_2;                              //_16
     uint64_t carg_3;
@@ -124,13 +122,13 @@
   };
 
   enum {
-    abi_112_size = sizeof(abi_112)
+    abi_reg_args_size = sizeof(abi_reg_args)
   };
 
   #define _abi(_component) \
-          (offset_of(frame::abi_112, _component))
+          (offset_of(frame::abi_reg_args, _component))
 
-  struct abi_112_spill : abi_112 {
+  struct abi_reg_args_spill : abi_reg_args {
     // additional spill slots
     uint64_t spill_ret;
     uint64_t spill_fret;                          //_16
@@ -138,11 +136,11 @@
   };
 
   enum {
-    abi_112_spill_size = sizeof(abi_112_spill)
+    abi_reg_args_spill_size = sizeof(abi_reg_args_spill)
   };
 
-  #define _abi_112_spill(_component) \
-          (offset_of(frame::abi_112_spill, _component))
+  #define _abi_reg_args_spill(_component) \
+          (offset_of(frame::abi_reg_args_spill, _component))
 
   // non-volatile GPRs:
 
@@ -195,7 +193,85 @@
   #define _spill_nonvolatiles_neg(_component) \
      (int)(-frame::spill_nonvolatiles_size + offset_of(frame::spill_nonvolatiles, _component))
 
-  //  Frame layout for the Java interpreter on PPC64.
+
+
+#ifndef CC_INTERP
+  //  Frame layout for the Java template interpreter on PPC64.
+  //
+  //  Diffs to the CC_INTERP are marked with 'X'.
+  //
+  //  TOP_IJAVA_FRAME:
+  //
+  //    0       [TOP_IJAVA_FRAME_ABI]
+  //            alignment (optional)
+  //            [operand stack]
+  //            [monitors] (optional)
+  //           X[IJAVA_STATE]
+  //            note: own locals are located in the caller frame.
+  //
+  //  PARENT_IJAVA_FRAME:
+  //
+  //    0       [PARENT_IJAVA_FRAME_ABI]
+  //            alignment (optional)
+  //            [callee's Java result]
+  //            [callee's locals w/o arguments]
+  //            [outgoing arguments]
+  //            [used part of operand stack w/o arguments]
+  //            [monitors]      (optional)
+  //           X[IJAVA_STATE]
+  //
+
+  struct parent_ijava_frame_abi : abi_minframe {
+  };
+
+  enum {
+    parent_ijava_frame_abi_size = sizeof(parent_ijava_frame_abi)
+  };
+
+#define _parent_ijava_frame_abi(_component) \
+        (offset_of(frame::parent_ijava_frame_abi, _component))
+
+  struct top_ijava_frame_abi : abi_reg_args {
+  };
+
+  enum {
+    top_ijava_frame_abi_size = sizeof(top_ijava_frame_abi)
+  };
+
+#define _top_ijava_frame_abi(_component) \
+        (offset_of(frame::top_ijava_frame_abi, _component))
+
+  struct ijava_state {
+#ifdef ASSERT
+    uint64_t ijava_reserved;  // Used for assertion.
+    uint64_t ijava_reserved2; // Inserted for alignment.
+#endif
+    uint64_t method;
+    uint64_t locals;
+    uint64_t monitors;
+    uint64_t cpoolCache;
+    uint64_t bcp;
+    uint64_t esp;
+    uint64_t mdx;
+    uint64_t top_frame_sp; // Maybe define parent_frame_abi and move there.
+    uint64_t sender_sp;
+    // Slots only needed for native calls. Maybe better to move elsewhere.
+    uint64_t oop_tmp;
+    uint64_t lresult;
+    uint64_t fresult;
+    // Aligned to frame::alignment_in_bytes (16).
+  };
+
+  enum {
+    ijava_state_size = sizeof(ijava_state)
+  };
+
+#define _ijava_state_neg(_component) \
+        (int) (-frame::ijava_state_size + offset_of(frame::ijava_state, _component))
+
+#else // CC_INTERP:
+
+  //  Frame layout for the Java C++ interpreter on PPC64.
   //
   //  This frame layout provides a C-like frame for every Java frame.
   //
@@ -242,7 +318,7 @@
   //            [ENTRY_FRAME_LOCALS]
   //
   //  PARENT_IJAVA_FRAME_ABI:
-  //    0       [ABI_48]
+  //    0       [ABI_MINFRAME]
   //            top_frame_sp
   //            initial_caller_sp
   //
@@ -258,7 +334,7 @@
 
   // PARENT_IJAVA_FRAME_ABI
 
-  struct parent_ijava_frame_abi : abi_48 {
+  struct parent_ijava_frame_abi : abi_minframe {
     // SOE registers.
     // C2i adapters spill their top-frame stack-pointer here.
     uint64_t top_frame_sp;                        //      carg_1
@@ -285,7 +361,7 @@
     uint64_t carg_6_unused;                       //_16   carg_6
     uint64_t carg_7_unused;                       //      carg_7
     // Use arg8 for storing frame_manager_lr. The size of
-    // top_ijava_frame_abi must match abi_112.
+    // top_ijava_frame_abi must match abi_reg_args.
     uint64_t frame_manager_lr;                    //_16   carg_8
     // nothing to add here!
     // aligned to frame::alignment_in_bytes (16)
@@ -298,6 +374,8 @@
   #define _top_ijava_frame_abi(_component) \
           (offset_of(frame::top_ijava_frame_abi, _component))
 
+#endif // CC_INTERP
+
   // ENTRY_FRAME
 
   struct entry_frame_locals {
@@ -395,8 +473,8 @@
   intptr_t* fp() const { return _fp; }
 
   // Accessors for ABIs
-  inline abi_48* own_abi()     const { return (abi_48*) _sp; }
-  inline abi_48* callers_abi() const { return (abi_48*) _fp; }
+  inline abi_minframe* own_abi()     const { return (abi_minframe*) _sp; }
+  inline abi_minframe* callers_abi() const { return (abi_minframe*) _fp; }
 
  private:
 
@@ -421,6 +499,14 @@
 #ifdef CC_INTERP
   // Additional interface for interpreter frames:
   inline interpreterState get_interpreterState() const;
+#else
+  inline ijava_state* get_ijava_state() const;
+  // Some convenient register frame setters/getters for deoptimization.
+  inline intptr_t* interpreter_frame_esp() const;
+  inline void interpreter_frame_set_cpcache(ConstantPoolCache* cp);
+  inline void interpreter_frame_set_esp(intptr_t* esp);
+  inline void interpreter_frame_set_top_frame_sp(intptr_t* top_frame_sp);
+  inline void interpreter_frame_set_sender_sp(intptr_t* sender_sp);
 #endif // CC_INTERP
 
   // Size of a monitor in bytes.
--- a/hotspot/src/cpu/ppc/vm/frame_ppc.inline.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/frame_ppc.inline.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright 2012, 2014 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
@@ -26,10 +26,6 @@
 #ifndef CPU_PPC_VM_FRAME_PPC_INLINE_HPP
 #define CPU_PPC_VM_FRAME_PPC_INLINE_HPP
 
-#ifndef CC_INTERP
-#error "CC_INTERP must be defined on PPC64"
-#endif
-
 // Inline functions for ppc64 frames:
 
 // Find codeblob and set deopt_state.
@@ -199,6 +195,75 @@
   interpreterState istate = get_interpreterState();
   return &istate->_constants;
 }
+
+#else // !CC_INTERP
+
+// Template Interpreter frame value accessors.
+
+inline frame::ijava_state* frame::get_ijava_state() const {
+  return (ijava_state*) ((uintptr_t)fp() - ijava_state_size);
+}
+
+inline intptr_t** frame::interpreter_frame_locals_addr() const {
+  return (intptr_t**) &(get_ijava_state()->locals);
+}
+inline intptr_t* frame::interpreter_frame_bcx_addr() const {
+  return (intptr_t*) &(get_ijava_state()->bcp);
+}
+inline intptr_t* frame::interpreter_frame_mdx_addr() const {
+  return (intptr_t*) &(get_ijava_state()->mdx);
+}
+// Pointer beyond the "oldest/deepest" BasicObjectLock on stack.
+inline BasicObjectLock* frame::interpreter_frame_monitor_end() const {
+  return (BasicObjectLock *) get_ijava_state()->monitors;
+}
+
+inline BasicObjectLock* frame::interpreter_frame_monitor_begin() const {
+  return (BasicObjectLock *) get_ijava_state();
+}
+
+// SAPJVM ASc 2012-11-21. Return register stack slot addr at which currently interpreted method is found
+inline Method** frame::interpreter_frame_method_addr() const {
+  return (Method**) &(get_ijava_state()->method);
+}
+inline ConstantPoolCache** frame::interpreter_frame_cpoolcache_addr() const {
+  return (ConstantPoolCache**) &(get_ijava_state()->cpoolCache);
+}
+inline ConstantPoolCache** frame::interpreter_frame_cache_addr() const {
+  return (ConstantPoolCache**) &(get_ijava_state()->cpoolCache);
+}
+
+inline oop* frame::interpreter_frame_temp_oop_addr() const {
+  return (oop *) &(get_ijava_state()->oop_tmp);
+}
+inline intptr_t* frame::interpreter_frame_esp() const {
+  return (intptr_t*) get_ijava_state()->esp;
+}
+
+// Convenient setters
+inline void frame::interpreter_frame_set_monitor_end(BasicObjectLock* end)    { get_ijava_state()->monitors = (intptr_t) end;}
+inline void frame::interpreter_frame_set_cpcache(ConstantPoolCache* cp)       { *frame::interpreter_frame_cpoolcache_addr() = cp; }
+inline void frame::interpreter_frame_set_esp(intptr_t* esp)                   { get_ijava_state()->esp = (intptr_t) esp; }
+inline void frame::interpreter_frame_set_top_frame_sp(intptr_t* top_frame_sp) { get_ijava_state()->top_frame_sp = (intptr_t) top_frame_sp; }
+inline void frame::interpreter_frame_set_sender_sp(intptr_t* sender_sp)       { get_ijava_state()->sender_sp = (intptr_t) sender_sp; }
+
+inline intptr_t* frame::interpreter_frame_expression_stack() const {
+  return (intptr_t*)interpreter_frame_monitor_end() - 1;
+}
+
+inline jint frame::interpreter_frame_expression_stack_direction() {
+  return -1;
+}
+
+// top of expression stack
+inline intptr_t* frame::interpreter_frame_tos_address() const {
+  return ((intptr_t*) get_ijava_state()->esp) + Interpreter::stackElementWords;
+}
+
+inline intptr_t* frame::interpreter_frame_tos_at(jint offset) const {
+  return &interpreter_frame_tos_address()[offset];
+}
+
 #endif // CC_INTERP
 
 inline int frame::interpreter_frame_monitor_size() {
--- a/hotspot/src/cpu/ppc/vm/interp_masm_ppc_64.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/interp_masm_ppc_64.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright 2012, 2014 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
@@ -29,6 +29,7 @@
 #include "asm/macroAssembler.inline.hpp"
 #include "interp_masm_ppc_64.hpp"
 #include "interpreter/interpreterRuntime.hpp"
+#include "prims/jvmtiThreadState.hpp"
 
 #ifdef PRODUCT
 #define BLOCK_COMMENT(str) // nothing
@@ -45,6 +46,691 @@
   MacroAssembler::null_check_throw(a, offset, temp_reg, exception_entry);
 }
 
+void InterpreterMacroAssembler::branch_to_entry(address entry, Register Rscratch) {
+  assert(entry, "Entry must have been generated by now");
+  if (is_within_range_of_b(entry, pc())) {
+    b(entry);
+  } else {
+    load_const_optimized(Rscratch, entry, R0);
+    mtctr(Rscratch);
+    bctr();
+  }
+}
+
+#ifndef CC_INTERP
+
+void InterpreterMacroAssembler::dispatch_next(TosState state, int bcp_incr) {
+  Register bytecode = R12_scratch2;
+  if (bcp_incr != 0) {
+    lbzu(bytecode, bcp_incr, R14_bcp);
+  } else {
+    lbz(bytecode, 0, R14_bcp);
+  }
+
+  dispatch_Lbyte_code(state, bytecode, Interpreter::dispatch_table(state));
+}
+
+void InterpreterMacroAssembler::dispatch_via(TosState state, address* table) {
+  // Load current bytecode.
+  Register bytecode = R12_scratch2;
+  lbz(bytecode, 0, R14_bcp);
+  dispatch_Lbyte_code(state, bytecode, table);
+}
+
+// Dispatch code executed in the prolog of a bytecode which does not do it's
+// own dispatch. The dispatch address is computed and placed in R24_dispatch_addr.
+void InterpreterMacroAssembler::dispatch_prolog(TosState state, int bcp_incr) {
+  Register bytecode = R12_scratch2;
+  lbz(bytecode, bcp_incr, R14_bcp);
+
+  load_dispatch_table(R24_dispatch_addr, Interpreter::dispatch_table(state));
+
+  sldi(bytecode, bytecode, LogBytesPerWord);
+  ldx(R24_dispatch_addr, R24_dispatch_addr, bytecode);
+}
+
+// Dispatch code executed in the epilog of a bytecode which does not do it's
+// own dispatch. The dispatch address in R24_dispatch_addr is used for the
+// dispatch.
+void InterpreterMacroAssembler::dispatch_epilog(TosState state, int bcp_incr) {
+  mtctr(R24_dispatch_addr);
+  addi(R14_bcp, R14_bcp, bcp_incr);
+  bctr();
+}
+
+void InterpreterMacroAssembler::check_and_handle_popframe(Register scratch_reg) {
+  assert(scratch_reg != R0, "can't use R0 as scratch_reg here");
+  if (JvmtiExport::can_pop_frame()) {
+    Label L;
+
+    // Check the "pending popframe condition" flag in the current thread.
+    lwz(scratch_reg, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
+
+    // Initiate popframe handling only if it is not already being
+    // processed. If the flag has the popframe_processing bit set, it
+    // means that this code is called *during* popframe handling - we
+    // don't want to reenter.
+    andi_(R0, scratch_reg, JavaThread::popframe_pending_bit);
+    beq(CCR0, L);
+
+    andi_(R0, scratch_reg, JavaThread::popframe_processing_bit);
+    bne(CCR0, L);
+
+    // Call the Interpreter::remove_activation_preserving_args_entry()
+    // func to get the address of the same-named entrypoint in the
+    // generated interpreter code.
+    call_c(CAST_FROM_FN_PTR(FunctionDescriptor*,
+                            Interpreter::remove_activation_preserving_args_entry),
+           relocInfo::none);
+
+    // Jump to Interpreter::_remove_activation_preserving_args_entry.
+    mtctr(R3_RET);
+    bctr();
+
+    align(32, 12);
+    bind(L);
+  }
+}
+
+void InterpreterMacroAssembler::check_and_handle_earlyret(Register scratch_reg) {
+  const Register Rthr_state_addr = scratch_reg;
+  if (JvmtiExport::can_force_early_return()) {
+    Label Lno_early_ret;
+    ld(Rthr_state_addr, in_bytes(JavaThread::jvmti_thread_state_offset()), R16_thread);
+    cmpdi(CCR0, Rthr_state_addr, 0);
+    beq(CCR0, Lno_early_ret);
+
+    lwz(R0, in_bytes(JvmtiThreadState::earlyret_state_offset()), Rthr_state_addr);
+    cmpwi(CCR0, R0, JvmtiThreadState::earlyret_pending);
+    bne(CCR0, Lno_early_ret);
+
+    // Jump to Interpreter::_earlyret_entry.
+    lwz(R3_ARG1, in_bytes(JvmtiThreadState::earlyret_tos_offset()), Rthr_state_addr);
+    call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_early_entry));
+    mtlr(R3_RET);
+    blr();
+
+    align(32, 12);
+    bind(Lno_early_ret);
+  }
+}
+
+void InterpreterMacroAssembler::load_earlyret_value(TosState state, Register Rscratch1) {
+  const Register RjvmtiState = Rscratch1;
+  const Register Rscratch2   = R0;
+
+  ld(RjvmtiState, in_bytes(JavaThread::jvmti_thread_state_offset()), R16_thread);
+  li(Rscratch2, 0);
+
+  switch (state) {
+    case atos: ld(R17_tos, in_bytes(JvmtiThreadState::earlyret_oop_offset()), RjvmtiState);
+               std(Rscratch2, in_bytes(JvmtiThreadState::earlyret_oop_offset()), RjvmtiState);
+               break;
+    case ltos: ld(R17_tos, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
+               break;
+    case btos: // fall through
+    case ctos: // fall through
+    case stos: // fall through
+    case itos: lwz(R17_tos, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
+               break;
+    case ftos: lfs(F15_ftos, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
+               break;
+    case dtos: lfd(F15_ftos, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
+               break;
+    case vtos: break;
+    default  : ShouldNotReachHere();
+  }
+
+  // Clean up tos value in the jvmti thread state.
+  std(Rscratch2, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
+  // Set tos state field to illegal value.
+  li(Rscratch2, ilgl);
+  stw(Rscratch2, in_bytes(JvmtiThreadState::earlyret_tos_offset()), RjvmtiState);
+}
+
+// Common code to dispatch and dispatch_only.
+// Dispatch value in Lbyte_code and increment Lbcp.
+
+void InterpreterMacroAssembler::load_dispatch_table(Register dst, address* table) {
+  address table_base = (address)Interpreter::dispatch_table((TosState)0);
+  intptr_t table_offs = (intptr_t)table - (intptr_t)table_base;
+  if (is_simm16(table_offs)) {
+    addi(dst, R25_templateTableBase, (int)table_offs);
+  } else {
+    load_const_optimized(dst, table, R0);
+  }
+}
+
+void InterpreterMacroAssembler::dispatch_Lbyte_code(TosState state, Register bytecode, address* table, bool verify) {
+  if (verify) {
+    unimplemented("dispatch_Lbyte_code: verify"); // See Sparc Implementation to implement this
+  }
+
+#ifdef FAST_DISPATCH
+  unimplemented("dispatch_Lbyte_code FAST_DISPATCH");
+#else
+  assert_different_registers(bytecode, R11_scratch1);
+
+  // Calc dispatch table address.
+  load_dispatch_table(R11_scratch1, table);
+
+  sldi(R12_scratch2, bytecode, LogBytesPerWord);
+  ldx(R11_scratch1, R11_scratch1, R12_scratch2);
+
+  // Jump off!
+  mtctr(R11_scratch1);
+  bctr();
+#endif
+}
+
+void InterpreterMacroAssembler::load_receiver(Register Rparam_count, Register Rrecv_dst) {
+  sldi(Rrecv_dst, Rparam_count, Interpreter::logStackElementSize);
+  ldx(Rrecv_dst, Rrecv_dst, R15_esp);
+}
+
+// helpers for expression stack
+
+void InterpreterMacroAssembler::pop_i(Register r) {
+  lwzu(r, Interpreter::stackElementSize, R15_esp);
+}
+
+void InterpreterMacroAssembler::pop_ptr(Register r) {
+  ldu(r, Interpreter::stackElementSize, R15_esp);
+}
+
+void InterpreterMacroAssembler::pop_l(Register r) {
+  ld(r, Interpreter::stackElementSize, R15_esp);
+  addi(R15_esp, R15_esp, 2 * Interpreter::stackElementSize);
+}
+
+void InterpreterMacroAssembler::pop_f(FloatRegister f) {
+  lfsu(f, Interpreter::stackElementSize, R15_esp);
+}
+
+void InterpreterMacroAssembler::pop_d(FloatRegister f) {
+  lfd(f, Interpreter::stackElementSize, R15_esp);
+  addi(R15_esp, R15_esp, 2 * Interpreter::stackElementSize);
+}
+
+void InterpreterMacroAssembler::push_i(Register r) {
+  stw(r, 0, R15_esp);
+  addi(R15_esp, R15_esp, - Interpreter::stackElementSize );
+}
+
+void InterpreterMacroAssembler::push_ptr(Register r) {
+  std(r, 0, R15_esp);
+  addi(R15_esp, R15_esp, - Interpreter::stackElementSize );
+}
+
+void InterpreterMacroAssembler::push_l(Register r) {
+  std(r, - Interpreter::stackElementSize, R15_esp);
+  addi(R15_esp, R15_esp, - 2 * Interpreter::stackElementSize );
+}
+
+void InterpreterMacroAssembler::push_f(FloatRegister f) {
+  stfs(f, 0, R15_esp);
+  addi(R15_esp, R15_esp, - Interpreter::stackElementSize );
+}
+
+void InterpreterMacroAssembler::push_d(FloatRegister f)   {
+  stfd(f, - Interpreter::stackElementSize, R15_esp);
+  addi(R15_esp, R15_esp, - 2 * Interpreter::stackElementSize );
+}
+
+void InterpreterMacroAssembler::push_2ptrs(Register first, Register second) {
+  std(first, 0, R15_esp);
+  std(second, -Interpreter::stackElementSize, R15_esp);
+  addi(R15_esp, R15_esp, - 2 * Interpreter::stackElementSize );
+}
+
+void InterpreterMacroAssembler::push_l_pop_d(Register l, FloatRegister d) {
+  std(l, 0, R15_esp);
+  lfd(d, 0, R15_esp);
+}
+
+void InterpreterMacroAssembler::push_d_pop_l(FloatRegister d, Register l) {
+  stfd(d, 0, R15_esp);
+  ld(l, 0, R15_esp);
+}
+
+void InterpreterMacroAssembler::push(TosState state) {
+  switch (state) {
+    case atos: push_ptr();                break;
+    case btos:
+    case ctos:
+    case stos:
+    case itos: push_i();                  break;
+    case ltos: push_l();                  break;
+    case ftos: push_f();                  break;
+    case dtos: push_d();                  break;
+    case vtos: /* nothing to do */        break;
+    default  : ShouldNotReachHere();
+  }
+}
+
+void InterpreterMacroAssembler::pop(TosState state) {
+  switch (state) {
+    case atos: pop_ptr();            break;
+    case btos:
+    case ctos:
+    case stos:
+    case itos: pop_i();              break;
+    case ltos: pop_l();              break;
+    case ftos: pop_f();              break;
+    case dtos: pop_d();              break;
+    case vtos: /* nothing to do */   break;
+    default  : ShouldNotReachHere();
+  }
+  verify_oop(R17_tos, state);
+}
+
+void InterpreterMacroAssembler::empty_expression_stack() {
+  addi(R15_esp, R26_monitor, - Interpreter::stackElementSize);
+}
+
+void InterpreterMacroAssembler::get_2_byte_integer_at_bcp(int         bcp_offset,
+                                                          Register    Rdst,
+                                                          signedOrNot is_signed) {
+  // Read Java big endian format.
+  if (is_signed == Signed) {
+    lha(Rdst, bcp_offset, R14_bcp);
+  } else {
+    lhz(Rdst, bcp_offset, R14_bcp);
+  }
+#if 0
+  assert(Rtmp != Rdst, "need separate temp register");
+  Register Rfirst = Rtmp;
+  lbz(Rfirst, bcp_offset, R14_bcp); // first byte
+  lbz(Rdst, bcp_offset+1, R14_bcp); // second byte
+
+  // Rdst = ((Rfirst<<8) & 0xFF00) | (Rdst &~ 0xFF00)
+  rldimi(/*RA=*/Rdst, /*RS=*/Rfirst, /*sh=*/8, /*mb=*/48);
+  if (is_signed == Signed) {
+    extsh(Rdst, Rdst);
+  }
+#endif
+}
+
+void InterpreterMacroAssembler::get_4_byte_integer_at_bcp(int         bcp_offset,
+                                                          Register    Rdst,
+                                                          signedOrNot is_signed) {
+  // Read Java big endian format.
+  if (bcp_offset & 3) { // Offset unaligned?
+    load_const_optimized(Rdst, bcp_offset);
+    if (is_signed == Signed) {
+      lwax(Rdst, R14_bcp, Rdst);
+    } else {
+      lwzx(Rdst, R14_bcp, Rdst);
+    }
+  } else {
+    if (is_signed == Signed) {
+      lwa(Rdst, bcp_offset, R14_bcp);
+    } else {
+      lwz(Rdst, bcp_offset, R14_bcp);
+    }
+  }
+}
+
+// Load the constant pool cache index from the bytecode stream.
+//
+// Kills / writes:
+//   - Rdst, Rscratch
+void InterpreterMacroAssembler::get_cache_index_at_bcp(Register Rdst, int bcp_offset, size_t index_size) {
+  assert(bcp_offset > 0, "bcp is still pointing to start of bytecode");
+  if (index_size == sizeof(u2)) {
+    get_2_byte_integer_at_bcp(bcp_offset, Rdst, Unsigned);
+  } else if (index_size == sizeof(u4)) {
+    assert(EnableInvokeDynamic, "giant index used only for JSR 292");
+    get_4_byte_integer_at_bcp(bcp_offset, Rdst, Signed);
+    assert(ConstantPool::decode_invokedynamic_index(~123) == 123, "else change next line");
+    nand(Rdst, Rdst, Rdst); // convert to plain index
+  } else if (index_size == sizeof(u1)) {
+    lbz(Rdst, bcp_offset, R14_bcp);
+  } else {
+    ShouldNotReachHere();
+  }
+  // Rdst now contains cp cache index.
+}
+
+void InterpreterMacroAssembler::get_cache_and_index_at_bcp(Register cache, int bcp_offset, size_t index_size) {
+  get_cache_index_at_bcp(cache, bcp_offset, index_size);
+  sldi(cache, cache, exact_log2(in_words(ConstantPoolCacheEntry::size()) * BytesPerWord));
+  add(cache, R27_constPoolCache, cache);
+}
+
+// Load object from cpool->resolved_references(index).
+void InterpreterMacroAssembler::load_resolved_reference_at_index(Register result, Register index) {
+  assert_different_registers(result, index);
+  get_constant_pool(result);
+
+  // Convert from field index to resolved_references() index and from
+  // word index to byte offset. Since this is a java object, it can be compressed.
+  Register tmp = index;  // reuse
+  sldi(tmp, index, LogBytesPerHeapOop);
+  // Load pointer for resolved_references[] objArray.
+  ld(result, ConstantPool::resolved_references_offset_in_bytes(), result);
+  // JNIHandles::resolve(result)
+  ld(result, 0, result);
+#ifdef ASSERT
+  Label index_ok;
+  lwa(R0, arrayOopDesc::length_offset_in_bytes(), result);
+  sldi(R0, R0, LogBytesPerHeapOop);
+  cmpd(CCR0, tmp, R0);
+  blt(CCR0, index_ok);
+  stop("resolved reference index out of bounds", 0x09256);
+  bind(index_ok);
+#endif
+  // Add in the index.
+  add(result, tmp, result);
+  load_heap_oop(result, arrayOopDesc::base_offset_in_bytes(T_OBJECT), result);
+}
+
+// Generate a subtype check: branch to ok_is_subtype if sub_klass is
+// a subtype of super_klass. Blows registers Rsub_klass, tmp1, tmp2.
+void InterpreterMacroAssembler::gen_subtype_check(Register Rsub_klass, Register Rsuper_klass, Register Rtmp1,
+                                                  Register Rtmp2, Register Rtmp3, Label &ok_is_subtype) {
+  // Profile the not-null value's klass.
+  profile_typecheck(Rsub_klass, Rtmp1, Rtmp2);
+  check_klass_subtype(Rsub_klass, Rsuper_klass, Rtmp1, Rtmp2, ok_is_subtype);
+  profile_typecheck_failed(Rtmp1, Rtmp2);
+}
+
+void InterpreterMacroAssembler::generate_stack_overflow_check_with_compare_and_throw(Register Rmem_frame_size, Register Rscratch1) {
+  Label done;
+  sub(Rmem_frame_size, R1_SP, Rmem_frame_size);
+  ld(Rscratch1, thread_(stack_overflow_limit));
+  cmpld(CCR0/*is_stack_overflow*/, Rmem_frame_size, Rscratch1);
+  bgt(CCR0/*is_stack_overflow*/, done);
+
+  // Load target address of the runtime stub.
+  assert(StubRoutines::throw_StackOverflowError_entry() != NULL, "generated in wrong order");
+  load_const_optimized(Rscratch1, (StubRoutines::throw_StackOverflowError_entry()), R0);
+  mtctr(Rscratch1);
+  // Restore caller_sp.
+#ifdef ASSERT
+  ld(Rscratch1, 0, R1_SP);
+  ld(R0, 0, R21_sender_SP);
+  cmpd(CCR0, R0, Rscratch1);
+  asm_assert_eq("backlink", 0x547);
+#endif // ASSERT
+  mr(R1_SP, R21_sender_SP);
+  bctr();
+
+  align(32, 12);
+  bind(done);
+}
+
+// Separate these two to allow for delay slot in middle.
+// These are used to do a test and full jump to exception-throwing code.
+
+// Check that index is in range for array, then shift index by index_shift,
+// and put arrayOop + shifted_index into res.
+// Note: res is still shy of address by array offset into object.
+
+void InterpreterMacroAssembler::index_check_without_pop(Register Rarray, Register Rindex, int index_shift, Register Rtmp, Register Rres) {
+  // Check that index is in range for array, then shift index by index_shift,
+  // and put arrayOop + shifted_index into res.
+  // Note: res is still shy of address by array offset into object.
+  // Kills:
+  //   - Rindex
+  // Writes:
+  //   - Rres: Address that corresponds to the array index if check was successful.
+  verify_oop(Rarray);
+  const Register Rlength   = R0;
+  const Register RsxtIndex = Rtmp;
+  Label LisNull, LnotOOR;
+
+  // Array nullcheck
+  if (!ImplicitNullChecks) {
+    cmpdi(CCR0, Rarray, 0);
+    beq(CCR0, LisNull);
+  } else {
+    null_check_throw(Rarray, arrayOopDesc::length_offset_in_bytes(), /*temp*/RsxtIndex);
+  }
+
+  // Rindex might contain garbage in upper bits (remember that we don't sign extend
+  // during integer arithmetic operations). So kill them and put value into same register
+  // where ArrayIndexOutOfBounds would expect the index in.
+  rldicl(RsxtIndex, Rindex, 0, 32); // zero extend 32 bit -> 64 bit
+
+  // Index check
+  lwz(Rlength, arrayOopDesc::length_offset_in_bytes(), Rarray);
+  cmplw(CCR0, Rindex, Rlength);
+  sldi(RsxtIndex, RsxtIndex, index_shift);
+  blt(CCR0, LnotOOR);
+  load_dispatch_table(Rtmp, (address*)Interpreter::_throw_ArrayIndexOutOfBoundsException_entry);
+  mtctr(Rtmp);
+  bctr();
+
+  if (!ImplicitNullChecks) {
+    bind(LisNull);
+    load_dispatch_table(Rtmp, (address*)Interpreter::_throw_NullPointerException_entry);
+    mtctr(Rtmp);
+    bctr();
+  }
+
+  align(32, 16);
+  bind(LnotOOR);
+
+  // Calc address
+  add(Rres, RsxtIndex, Rarray);
+}
+
+void InterpreterMacroAssembler::index_check(Register array, Register index, int index_shift, Register tmp, Register res) {
+  // pop array
+  pop_ptr(array);
+
+  // check array
+  index_check_without_pop(array, index, index_shift, tmp, res);
+}
+
+void InterpreterMacroAssembler::get_const(Register Rdst) {
+  ld(Rdst, in_bytes(Method::const_offset()), R19_method);
+}
+
+void InterpreterMacroAssembler::get_constant_pool(Register Rdst) {
+  get_const(Rdst);
+  ld(Rdst, in_bytes(ConstMethod::constants_offset()), Rdst);
+}
+
+void InterpreterMacroAssembler::get_constant_pool_cache(Register Rdst) {
+  get_constant_pool(Rdst);
+  ld(Rdst, ConstantPool::cache_offset_in_bytes(), Rdst);
+}
+
+void InterpreterMacroAssembler::get_cpool_and_tags(Register Rcpool, Register Rtags) {
+  get_constant_pool(Rcpool);
+  ld(Rtags, ConstantPool::tags_offset_in_bytes(), Rcpool);
+}
+
+// Unlock if synchronized method.
+//
+// Unlock the receiver if this is a synchronized method.
+// Unlock any Java monitors from synchronized blocks.
+//
+// If there are locked Java monitors
+//   If throw_monitor_exception
+//     throws IllegalMonitorStateException
+//   Else if install_monitor_exception
+//     installs IllegalMonitorStateException
+//   Else
+//     no error processing
+void InterpreterMacroAssembler::unlock_if_synchronized_method(TosState state,
+                                                              bool throw_monitor_exception,
+                                                              bool install_monitor_exception) {
+  Label Lunlocked, Lno_unlock;
+  {
+    Register Rdo_not_unlock_flag = R11_scratch1;
+    Register Raccess_flags       = R12_scratch2;
+
+    // Check if synchronized method or unlocking prevented by
+    // JavaThread::do_not_unlock_if_synchronized flag.
+    lbz(Rdo_not_unlock_flag, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
+    lwz(Raccess_flags, in_bytes(Method::access_flags_offset()), R19_method);
+    li(R0, 0);
+    stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread); // reset flag
+
+    push(state);
+
+    // Skip if we don't have to unlock.
+    rldicl_(R0, Raccess_flags, 64-JVM_ACC_SYNCHRONIZED_BIT, 63); // Extract bit and compare to 0.
+    beq(CCR0, Lunlocked);
+
+    cmpwi(CCR0, Rdo_not_unlock_flag, 0);
+    bne(CCR0, Lno_unlock);
+  }
+
+  // Unlock
+  {
+    Register Rmonitor_base = R11_scratch1;
+
+    Label Lunlock;
+    // If it's still locked, everything is ok, unlock it.
+    ld(Rmonitor_base, 0, R1_SP);
+    addi(Rmonitor_base, Rmonitor_base, - (frame::ijava_state_size + frame::interpreter_frame_monitor_size_in_bytes())); // Monitor base
+
+    ld(R0, BasicObjectLock::obj_offset_in_bytes(), Rmonitor_base);
+    cmpdi(CCR0, R0, 0);
+    bne(CCR0, Lunlock);
+
+    // If it's already unlocked, throw exception.
+    if (throw_monitor_exception) {
+      call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_illegal_monitor_state_exception));
+      should_not_reach_here();
+    } else {
+      if (install_monitor_exception) {
+        call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::new_illegal_monitor_state_exception));
+        b(Lunlocked);
+      }
+    }
+
+    bind(Lunlock);
+    unlock_object(Rmonitor_base);
+  }
+
+  // Check that all other monitors are unlocked. Throw IllegelMonitorState exception if not.
+  bind(Lunlocked);
+  {
+    Label Lexception, Lrestart;
+    Register Rcurrent_obj_addr = R11_scratch1;
+    const int delta = frame::interpreter_frame_monitor_size_in_bytes();
+    assert((delta & LongAlignmentMask) == 0, "sizeof BasicObjectLock must be even number of doublewords");
+
+    bind(Lrestart);
+    // Set up search loop: Calc num of iterations.
+    {
+      Register Riterations = R12_scratch2;
+      Register Rmonitor_base = Rcurrent_obj_addr;
+      ld(Rmonitor_base, 0, R1_SP);
+      addi(Rmonitor_base, Rmonitor_base, - frame::ijava_state_size);  // Monitor base
+
+      subf_(Riterations, R26_monitor, Rmonitor_base);
+      ble(CCR0, Lno_unlock);
+
+      addi(Rcurrent_obj_addr, Rmonitor_base, BasicObjectLock::obj_offset_in_bytes() - frame::interpreter_frame_monitor_size_in_bytes());
+      // Check if any monitor is on stack, bail out if not
+      srdi(Riterations, Riterations, exact_log2(delta));
+      mtctr(Riterations);
+    }
+
+    // The search loop: Look for locked monitors.
+    {
+      const Register Rcurrent_obj = R0;
+      Label Lloop;
+
+      ld(Rcurrent_obj, 0, Rcurrent_obj_addr);
+      addi(Rcurrent_obj_addr, Rcurrent_obj_addr, -delta);
+      bind(Lloop);
+
+      // Check if current entry is used.
+      cmpdi(CCR0, Rcurrent_obj, 0);
+      bne(CCR0, Lexception);
+      // Preload next iteration's compare value.
+      ld(Rcurrent_obj, 0, Rcurrent_obj_addr);
+      addi(Rcurrent_obj_addr, Rcurrent_obj_addr, -delta);
+      bdnz(Lloop);
+    }
+    // Fell through: Everything's unlocked => finish.
+    b(Lno_unlock);
+
+    // An object is still locked => need to throw exception.
+    bind(Lexception);
+    if (throw_monitor_exception) {
+      call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_illegal_monitor_state_exception));
+      should_not_reach_here();
+    } else {
+      // Stack unrolling. Unlock object and if requested, install illegal_monitor_exception.
+      // Unlock does not block, so don't have to worry about the frame.
+      Register Rmonitor_addr = R11_scratch1;
+      addi(Rmonitor_addr, Rcurrent_obj_addr, -BasicObjectLock::obj_offset_in_bytes() + delta);
+      unlock_object(Rmonitor_addr);
+      if (install_monitor_exception) {
+        call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::new_illegal_monitor_state_exception));
+      }
+      b(Lrestart);
+    }
+  }
+
+  align(32, 12);
+  bind(Lno_unlock);
+  pop(state);
+}
+
+// Support function for remove_activation & Co.
+void InterpreterMacroAssembler::merge_frames(Register Rsender_sp, Register return_pc, Register Rscratch1, Register Rscratch2) {
+  // Pop interpreter frame.
+  ld(Rscratch1, 0, R1_SP); // *SP
+  ld(Rsender_sp, _ijava_state_neg(sender_sp), Rscratch1); // top_frame_sp
+  ld(Rscratch2, 0, Rscratch1); // **SP
+#ifdef ASSERT
+  {
+    Label Lok;
+    ld(R0, _ijava_state_neg(ijava_reserved), Rscratch1);
+    cmpdi(CCR0, R0, 0x5afe);
+    beq(CCR0, Lok);
+    stop("frame corrupted (remove activation)", 0x5afe);
+    bind(Lok);
+  }
+#endif
+  if (return_pc!=noreg) {
+    ld(return_pc, _abi(lr), Rscratch1); // LR
+  }
+
+  // Merge top frames.
+  subf(Rscratch1, R1_SP, Rsender_sp); // top_frame_sp - SP
+  stdux(Rscratch2, R1_SP, Rscratch1); // atomically set *(SP = top_frame_sp) = **SP
+}
+
+// Remove activation.
+//
+// Unlock the receiver if this is a synchronized method.
+// Unlock any Java monitors from synchronized blocks.
+// Remove the activation from the stack.
+//
+// If there are locked Java monitors
+//    If throw_monitor_exception
+//       throws IllegalMonitorStateException
+//    Else if install_monitor_exception
+//       installs IllegalMonitorStateException
+//    Else
+//       no error processing
+void InterpreterMacroAssembler::remove_activation(TosState state,
+                                                  bool throw_monitor_exception,
+                                                  bool install_monitor_exception) {
+  unlock_if_synchronized_method(state, throw_monitor_exception, install_monitor_exception);
+
+  // Save result (push state before jvmti call and pop it afterwards) and notify jvmti.
+  notify_method_exit(false, state, NotifyJVMTI, true);
+
+  verify_oop(R17_tos, state);
+  verify_thread();
+
+  merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ R0, R11_scratch1, R12_scratch2);
+  mtlr(R0);
+}
+
+#endif // !CC_INTERP
+
 // Lock object
 //
 // Registers alive
@@ -81,7 +767,6 @@
 
     assert_different_registers(displaced_header, object_mark_addr, current_header, tmp);
 
-
     // markOop displaced_header = obj->mark().set_unlocked();
 
     // Load markOop from object into displaced_header.
@@ -94,7 +779,6 @@
     // Set displaced_header to be (markOop of object | UNLOCK_VALUE).
     ori(displaced_header, displaced_header, markOopDesc::unlocked_value);
 
-
     // monitor->lock()->set_displaced_header(displaced_header);
 
     // Initialize the box (Must happen before we update the object mark!).
@@ -147,7 +831,6 @@
         BasicLock::displaced_header_offset_in_bytes(), monitor);
     b(done);
 
-
     // } else {
     //   // Slow path.
     //   InterpreterRuntime::monitorenter(THREAD, monitor);
@@ -158,7 +841,7 @@
     call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
             monitor, /*check_for_exceptions=*/true CC_INTERP_ONLY(&& false));
     // }
-
+    align(32, 12);
     bind(done);
   }
 }
@@ -173,13 +856,13 @@
 void InterpreterMacroAssembler::unlock_object(Register monitor, bool check_for_exceptions) {
   if (UseHeavyMonitors) {
     call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit),
-            monitor, /*check_for_exceptions=*/false);
+            monitor, check_for_exceptions CC_INTERP_ONLY(&& false));
   } else {
 
     // template code:
     //
     // if ((displaced_header = monitor->displaced_header()) == NULL) {
-    //   // Recursive unlock.  Mark the monitor unlocked by setting the object field to NULL.
+    //   // Recursive unlock. Mark the monitor unlocked by setting the object field to NULL.
     //   monitor->set_obj(NULL);
     // } else if (Atomic::cmpxchg_ptr(displaced_header, obj->mark_addr(), monitor) == monitor) {
     //   // We swapped the unlocked mark in displaced_header into the object's mark word.
@@ -221,7 +904,7 @@
     // If we still have a lightweight lock, unlock the object and be done.
 
     // The object address from the monitor is in object.
-    if (!UseBiasedLocking) ld(object, BasicObjectLock::obj_offset_in_bytes(), monitor);
+    if (!UseBiasedLocking) { ld(object, BasicObjectLock::obj_offset_in_bytes(), monitor); }
     addi(object_mark_addr, object, oopDesc::mark_offset_in_bytes());
 
     // We have the displaced header in displaced_header. If the lock is still
@@ -261,6 +944,959 @@
   }
 }
 
+#ifndef CC_INTERP
+
+// Load compiled (i2c) or interpreter entry when calling from interpreted and
+// do the call. Centralized so that all interpreter calls will do the same actions.
+// If jvmti single stepping is on for a thread we must not call compiled code.
+//
+// Input:
+//   - Rtarget_method: method to call
+//   - Rret_addr:      return address
+//   - 2 scratch regs
+//
+void InterpreterMacroAssembler::call_from_interpreter(Register Rtarget_method, Register Rret_addr, Register Rscratch1, Register Rscratch2) {
+  assert_different_registers(Rscratch1, Rscratch2, Rtarget_method, Rret_addr);
+  // Assume we want to go compiled if available.
+  const Register Rtarget_addr = Rscratch1;
+  const Register Rinterp_only = Rscratch2;
+
+  ld(Rtarget_addr, in_bytes(Method::from_interpreted_offset()), Rtarget_method);
+
+  if (JvmtiExport::can_post_interpreter_events()) {
+    lwz(Rinterp_only, in_bytes(JavaThread::interp_only_mode_offset()), R16_thread);
+
+    // JVMTI events, such as single-stepping, are implemented partly by avoiding running
+    // compiled code in threads for which the event is enabled. Check here for
+    // interp_only_mode if these events CAN be enabled.
+    Label done;
+    verify_thread();
+    cmpwi(CCR0, Rinterp_only, 0);
+    beq(CCR0, done);
+    ld(Rtarget_addr, in_bytes(Method::interpreter_entry_offset()), Rtarget_method);
+    align(32, 12);
+    bind(done);
+  }
+
+#ifdef ASSERT
+  {
+    Label Lok;
+    cmpdi(CCR0, Rtarget_addr, 0);
+    bne(CCR0, Lok);
+    stop("null entry point");
+    bind(Lok);
+  }
+#endif // ASSERT
+
+  mr(R21_sender_SP, R1_SP);
+
+  // Calc a precise SP for the call. The SP value we calculated in
+  // generate_fixed_frame() is based on the max_stack() value, so we would waste stack space
+  // if esp is not max. Also, the i2c adapter extends the stack space without restoring
+  // our pre-calced value, so repeating calls via i2c would result in stack overflow.
+  // Since esp already points to an empty slot, we just have to sub 1 additional slot
+  // to meet the abi scratch requirements.
+  // The max_stack pointer will get restored by means of the GR_Lmax_stack local in
+  // the return entry of the interpreter.
+  addi(Rscratch2, R15_esp, Interpreter::stackElementSize - frame::abi_reg_args_size);
+  clrrdi(Rscratch2, Rscratch2, exact_log2(frame::alignment_in_bytes)); // round towards smaller address
+  resize_frame_absolute(Rscratch2, Rscratch2, R0);
+
+  mr_if_needed(R19_method, Rtarget_method);
+  mtctr(Rtarget_addr);
+  mtlr(Rret_addr);
+
+  save_interpreter_state(Rscratch2);
+#ifdef ASSERT
+  ld(Rscratch1, _ijava_state_neg(top_frame_sp), Rscratch2); // Rscratch2 contains fp
+  cmpd(CCR0, R21_sender_SP, Rscratch1);
+  asm_assert_eq("top_frame_sp incorrect", 0x951);
+#endif
+
+  bctr();
+}
+
+// Set the method data pointer for the current bcp.
+void InterpreterMacroAssembler::set_method_data_pointer_for_bcp() {
+  assert(ProfileInterpreter, "must be profiling interpreter");
+  Label get_continue;
+  ld(R28_mdx, in_bytes(Method::method_data_offset()), R19_method);
+  test_method_data_pointer(get_continue);
+  call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::bcp_to_di), R19_method, R14_bcp);
+
+  addi(R28_mdx, R28_mdx, in_bytes(MethodData::data_offset()));
+  add(R28_mdx, R28_mdx, R3_RET);
+  bind(get_continue);
+}
+
+// Test ImethodDataPtr. If it is null, continue at the specified label.
+void InterpreterMacroAssembler::test_method_data_pointer(Label& zero_continue) {
+  assert(ProfileInterpreter, "must be profiling interpreter");
+  cmpdi(CCR0, R28_mdx, 0);
+  beq(CCR0, zero_continue);
+}
+
+void InterpreterMacroAssembler::verify_method_data_pointer() {
+  assert(ProfileInterpreter, "must be profiling interpreter");
+#ifdef ASSERT
+  Label verify_continue;
+  test_method_data_pointer(verify_continue);
+
+  // If the mdp is valid, it will point to a DataLayout header which is
+  // consistent with the bcp. The converse is highly probable also.
+  lhz(R11_scratch1, in_bytes(DataLayout::bci_offset()), R28_mdx);
+  ld(R12_scratch2, in_bytes(Method::const_offset()), R19_method);
+  addi(R11_scratch1, R11_scratch1, in_bytes(ConstMethod::codes_offset()));
+  add(R11_scratch1, R12_scratch2, R12_scratch2);
+  cmpd(CCR0, R11_scratch1, R14_bcp);
+  beq(CCR0, verify_continue);
+
+  call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::verify_mdp ), R19_method, R14_bcp, R28_mdx);
+
+  bind(verify_continue);
+#endif
+}
+
+void InterpreterMacroAssembler::test_invocation_counter_for_mdp(Register invocation_count,
+                                                                Register Rscratch,
+                                                                Label &profile_continue) {
+  assert(ProfileInterpreter, "must be profiling interpreter");
+  // Control will flow to "profile_continue" if the counter is less than the
+  // limit or if we call profile_method().
+  Label done;
+
+  // If no method data exists, and the counter is high enough, make one.
+  int ipl_offs = load_const_optimized(Rscratch, &InvocationCounter::InterpreterProfileLimit, R0, true);
+  lwz(Rscratch, ipl_offs, Rscratch);
+
+  cmpdi(CCR0, R28_mdx, 0);
+  // Test to see if we should create a method data oop.
+  cmpd(CCR1, Rscratch /* InterpreterProfileLimit */, invocation_count);
+  bne(CCR0, done);
+  bge(CCR1, profile_continue);
+
+  // Build it now.
+  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::profile_method));
+  set_method_data_pointer_for_bcp();
+  b(profile_continue);
+
+  align(32, 12);
+  bind(done);
+}
+
+void InterpreterMacroAssembler::test_backedge_count_for_osr(Register backedge_count, Register branch_bcp, Register Rtmp) {
+  assert_different_registers(backedge_count, Rtmp, branch_bcp);
+  assert(UseOnStackReplacement,"Must UseOnStackReplacement to test_backedge_count_for_osr");
+
+  Label did_not_overflow;
+  Label overflow_with_error;
+
+  int ibbl_offs = load_const_optimized(Rtmp, &InvocationCounter::InterpreterBackwardBranchLimit, R0, true);
+  lwz(Rtmp, ibbl_offs, Rtmp);
+  cmpw(CCR0, backedge_count, Rtmp);
+
+  blt(CCR0, did_not_overflow);
+
+  // When ProfileInterpreter is on, the backedge_count comes from the
+  // methodDataOop, which value does not get reset on the call to
+  // frequency_counter_overflow(). To avoid excessive calls to the overflow
+  // routine while the method is being compiled, add a second test to make sure
+  // the overflow function is called only once every overflow_frequency.
+  if (ProfileInterpreter) {
+    const int overflow_frequency = 1024;
+    li(Rtmp, overflow_frequency-1);
+    andr(Rtmp, Rtmp, backedge_count);
+    cmpwi(CCR0, Rtmp, 0);
+    bne(CCR0, did_not_overflow);
+  }
+
+  // Overflow in loop, pass branch bytecode.
+  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::frequency_counter_overflow), branch_bcp, true);
+
+  // Was an OSR adapter generated?
+  // O0 = osr nmethod
+  cmpdi(CCR0, R3_RET, 0);
+  beq(CCR0, overflow_with_error);
+
+  // Has the nmethod been invalidated already?
+  lwz(Rtmp, nmethod::entry_bci_offset(), R3_RET);
+  cmpwi(CCR0, Rtmp, InvalidOSREntryBci);
+  beq(CCR0, overflow_with_error);
+
+  // Migrate the interpreter frame off of the stack.
+  // We can use all registers because we will not return to interpreter from this point.
+
+  // Save nmethod.
+  const Register osr_nmethod = R31;
+  mr(osr_nmethod, R3_RET);
+  set_top_ijava_frame_at_SP_as_last_Java_frame(R1_SP, R11_scratch1);
+  call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::OSR_migration_begin), R16_thread);
+  reset_last_Java_frame();
+  // OSR buffer is in ARG1
+
+  // Remove the interpreter frame.
+  merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ R0, R11_scratch1, R12_scratch2);
+
+  // Jump to the osr code.
+  ld(R11_scratch1, nmethod::osr_entry_point_offset(), osr_nmethod);
+  mtlr(R0);
+  mtctr(R11_scratch1);
+  bctr();
+
+  align(32, 12);
+  bind(overflow_with_error);
+  bind(did_not_overflow);
+}
+
+// Store a value at some constant offset from the method data pointer.
+void InterpreterMacroAssembler::set_mdp_data_at(int constant, Register value) {
+  assert(ProfileInterpreter, "must be profiling interpreter");
+
+  std(value, constant, R28_mdx);
+}
+
+// Increment the value at some constant offset from the method data pointer.
+void InterpreterMacroAssembler::increment_mdp_data_at(int constant,
+                                                      Register counter_addr,
+                                                      Register Rbumped_count,
+                                                      bool decrement) {
+  // Locate the counter at a fixed offset from the mdp:
+  addi(counter_addr, R28_mdx, constant);
+  increment_mdp_data_at(counter_addr, Rbumped_count, decrement);
+}
+
+// Increment the value at some non-fixed (reg + constant) offset from
+// the method data pointer.
+void InterpreterMacroAssembler::increment_mdp_data_at(Register reg,
+                                                      int constant,
+                                                      Register scratch,
+                                                      Register Rbumped_count,
+                                                      bool decrement) {
+  // Add the constant to reg to get the offset.
+  add(scratch, R28_mdx, reg);
+  // Then calculate the counter address.
+  addi(scratch, scratch, constant);
+  increment_mdp_data_at(scratch, Rbumped_count, decrement);
+}
+
+void InterpreterMacroAssembler::increment_mdp_data_at(Register counter_addr,
+                                                      Register Rbumped_count,
+                                                      bool decrement) {
+  assert(ProfileInterpreter, "must be profiling interpreter");
+
+  // Load the counter.
+  ld(Rbumped_count, 0, counter_addr);
+
+  if (decrement) {
+    // Decrement the register. Set condition codes.
+    addi(Rbumped_count, Rbumped_count, - DataLayout::counter_increment);
+    // Store the decremented counter, if it is still negative.
+    std(Rbumped_count, 0, counter_addr);
+    // Note: add/sub overflow check are not ported, since 64 bit
+    // calculation should never overflow.
+  } else {
+    // Increment the register. Set carry flag.
+    addi(Rbumped_count, Rbumped_count, DataLayout::counter_increment);
+    // Store the incremented counter.
+    std(Rbumped_count, 0, counter_addr);
+  }
+}
+
+// Set a flag value at the current method data pointer position.
+void InterpreterMacroAssembler::set_mdp_flag_at(int flag_constant,
+                                                Register scratch) {
+  assert(ProfileInterpreter, "must be profiling interpreter");
+  // Load the data header.
+  lbz(scratch, in_bytes(DataLayout::flags_offset()), R28_mdx);
+  // Set the flag.
+  ori(scratch, scratch, flag_constant);
+  // Store the modified header.
+  stb(scratch, in_bytes(DataLayout::flags_offset()), R28_mdx);
+}
+
+// Test the location at some offset from the method data pointer.
+// If it is not equal to value, branch to the not_equal_continue Label.
+void InterpreterMacroAssembler::test_mdp_data_at(int offset,
+                                                 Register value,
+                                                 Label& not_equal_continue,
+                                                 Register test_out) {
+  assert(ProfileInterpreter, "must be profiling interpreter");
+
+  ld(test_out, offset, R28_mdx);
+  cmpd(CCR0,  value, test_out);
+  bne(CCR0, not_equal_continue);
+}
+
+// Update the method data pointer by the displacement located at some fixed
+// offset from the method data pointer.
+void InterpreterMacroAssembler::update_mdp_by_offset(int offset_of_disp,
+                                                     Register scratch) {
+  assert(ProfileInterpreter, "must be profiling interpreter");
+
+  ld(scratch, offset_of_disp, R28_mdx);
+  add(R28_mdx, scratch, R28_mdx);
+}
+
+// Update the method data pointer by the displacement located at the
+// offset (reg + offset_of_disp).
+void InterpreterMacroAssembler::update_mdp_by_offset(Register reg,
+                                                     int offset_of_disp,
+                                                     Register scratch) {
+  assert(ProfileInterpreter, "must be profiling interpreter");
+
+  add(scratch, reg, R28_mdx);
+  ld(scratch, offset_of_disp, scratch);
+  add(R28_mdx, scratch, R28_mdx);
+}
+
+// Update the method data pointer by a simple constant displacement.
+void InterpreterMacroAssembler::update_mdp_by_constant(int constant) {
+  assert(ProfileInterpreter, "must be profiling interpreter");
+  addi(R28_mdx, R28_mdx, constant);
+}
+
+// Update the method data pointer for a _ret bytecode whose target
+// was not among our cached targets.
+void InterpreterMacroAssembler::update_mdp_for_ret(TosState state,
+                                                   Register return_bci) {
+  assert(ProfileInterpreter, "must be profiling interpreter");
+
+  push(state);
+  assert(return_bci->is_nonvolatile(), "need to protect return_bci");
+  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::update_mdp_for_ret), return_bci);
+  pop(state);
+}
+
+// Increments the backedge counter.
+// Returns backedge counter + invocation counter in Rdst.
+void InterpreterMacroAssembler::increment_backedge_counter(const Register Rcounters, const Register Rdst,
+                                                           const Register Rtmp1, Register Rscratch) {
+  assert(UseCompiler, "incrementing must be useful");
+  assert_different_registers(Rdst, Rtmp1);
+  const Register invocation_counter = Rtmp1;
+  const Register counter = Rdst;
+  // TODO ppc port assert(4 == InvocationCounter::sz_counter(), "unexpected field size.");
+
+  // Load backedge counter.
+  lwz(counter, in_bytes(MethodCounters::backedge_counter_offset()) +
+               in_bytes(InvocationCounter::counter_offset()), Rcounters);
+  // Load invocation counter.
+  lwz(invocation_counter, in_bytes(MethodCounters::invocation_counter_offset()) +
+                          in_bytes(InvocationCounter::counter_offset()), Rcounters);
+
+  // Add the delta to the backedge counter.
+  addi(counter, counter, InvocationCounter::count_increment);
+
+  // Mask the invocation counter.
+  li(Rscratch, InvocationCounter::count_mask_value);
+  andr(invocation_counter, invocation_counter, Rscratch);
+
+  // Store new counter value.
+  stw(counter, in_bytes(MethodCounters::backedge_counter_offset()) +
+               in_bytes(InvocationCounter::counter_offset()), Rcounters);
+  // Return invocation counter + backedge counter.
+  add(counter, counter, invocation_counter);
+}
+
+// Count a taken branch in the bytecodes.
+void InterpreterMacroAssembler::profile_taken_branch(Register scratch, Register bumped_count) {
+  if (ProfileInterpreter) {
+    Label profile_continue;
+
+    // If no method data exists, go to profile_continue.
+    test_method_data_pointer(profile_continue);
+
+    // We are taking a branch. Increment the taken count.
+    increment_mdp_data_at(in_bytes(JumpData::taken_offset()), scratch, bumped_count);
+
+    // The method data pointer needs to be updated to reflect the new target.
+    update_mdp_by_offset(in_bytes(JumpData::displacement_offset()), scratch);
+    bind (profile_continue);
+  }
+}
+
+// Count a not-taken branch in the bytecodes.
+void InterpreterMacroAssembler::profile_not_taken_branch(Register scratch1, Register scratch2) {
+  if (ProfileInterpreter) {
+    Label profile_continue;
+
+    // If no method data exists, go to profile_continue.
+    test_method_data_pointer(profile_continue);
+
+    // We are taking a branch. Increment the not taken count.
+    increment_mdp_data_at(in_bytes(BranchData::not_taken_offset()), scratch1, scratch2);
+
+    // The method data pointer needs to be updated to correspond to the
+    // next bytecode.
+    update_mdp_by_constant(in_bytes(BranchData::branch_data_size()));
+    bind (profile_continue);
+  }
+}
+
+// Count a non-virtual call in the bytecodes.
+void InterpreterMacroAssembler::profile_call(Register scratch1, Register scratch2) {
+  if (ProfileInterpreter) {
+    Label profile_continue;
+
+    // If no method data exists, go to profile_continue.
+    test_method_data_pointer(profile_continue);
+
+    // We are making a call. Increment the count.
+    increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2);
+
+    // The method data pointer needs to be updated to reflect the new target.
+    update_mdp_by_constant(in_bytes(CounterData::counter_data_size()));
+    bind (profile_continue);
+  }
+}
+
+// Count a final call in the bytecodes.
+void InterpreterMacroAssembler::profile_final_call(Register scratch1, Register scratch2) {
+  if (ProfileInterpreter) {
+    Label profile_continue;
+
+    // If no method data exists, go to profile_continue.
+    test_method_data_pointer(profile_continue);
+
+    // We are making a call. Increment the count.
+    increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2);
+
+    // The method data pointer needs to be updated to reflect the new target.
+    update_mdp_by_constant(in_bytes(VirtualCallData::virtual_call_data_size()));
+    bind (profile_continue);
+  }
+}
+
+// Count a virtual call in the bytecodes.
+void InterpreterMacroAssembler::profile_virtual_call(Register Rreceiver,
+                                                     Register Rscratch1,
+                                                     Register Rscratch2,
+                                                     bool receiver_can_be_null) {
+  if (!ProfileInterpreter) { return; }
+  Label profile_continue;
+
+  // If no method data exists, go to profile_continue.
+  test_method_data_pointer(profile_continue);
+
+  Label skip_receiver_profile;
+  if (receiver_can_be_null) {
+    Label not_null;
+    cmpdi(CCR0, Rreceiver, 0);
+    bne(CCR0, not_null);
+    // We are making a call. Increment the count for null receiver.
+    increment_mdp_data_at(in_bytes(CounterData::count_offset()), Rscratch1, Rscratch2);
+    b(skip_receiver_profile);
+    bind(not_null);
+  }
+
+  // Record the receiver type.
+  record_klass_in_profile(Rreceiver, Rscratch1, Rscratch2, true);
+  bind(skip_receiver_profile);
+
+  // The method data pointer needs to be updated to reflect the new target.
+  update_mdp_by_constant(in_bytes(VirtualCallData::virtual_call_data_size()));
+  bind (profile_continue);
+}
+
+void InterpreterMacroAssembler::profile_typecheck(Register Rklass, Register Rscratch1, Register Rscratch2) {
+  if (ProfileInterpreter) {
+    Label profile_continue;
+
+    // If no method data exists, go to profile_continue.
+    test_method_data_pointer(profile_continue);
+
+    int mdp_delta = in_bytes(BitData::bit_data_size());
+    if (TypeProfileCasts) {
+      mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
+
+      // Record the object type.
+      record_klass_in_profile(Rklass, Rscratch1, Rscratch2, false);
+    }
+
+    // The method data pointer needs to be updated.
+    update_mdp_by_constant(mdp_delta);
+
+    bind (profile_continue);
+  }
+}
+
+void InterpreterMacroAssembler::profile_typecheck_failed(Register Rscratch1, Register Rscratch2) {
+  if (ProfileInterpreter && TypeProfileCasts) {
+    Label profile_continue;
+
+    // If no method data exists, go to profile_continue.
+    test_method_data_pointer(profile_continue);
+
+    int count_offset = in_bytes(CounterData::count_offset());
+    // Back up the address, since we have already bumped the mdp.
+    count_offset -= in_bytes(VirtualCallData::virtual_call_data_size());
+
+    // *Decrement* the counter. We expect to see zero or small negatives.
+    increment_mdp_data_at(count_offset, Rscratch1, Rscratch2, true);
+
+    bind (profile_continue);
+  }
+}
+
+// Count a ret in the bytecodes.
+void InterpreterMacroAssembler::profile_ret(TosState state, Register return_bci, Register scratch1, Register scratch2) {
+  if (ProfileInterpreter) {
+    Label profile_continue;
+    uint row;
+
+    // If no method data exists, go to profile_continue.
+    test_method_data_pointer(profile_continue);
+
+    // Update the total ret count.
+    increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2 );
+
+    for (row = 0; row < RetData::row_limit(); row++) {
+      Label next_test;
+
+      // See if return_bci is equal to bci[n]:
+      test_mdp_data_at(in_bytes(RetData::bci_offset(row)), return_bci, next_test, scratch1);
+
+      // return_bci is equal to bci[n]. Increment the count.
+      increment_mdp_data_at(in_bytes(RetData::bci_count_offset(row)), scratch1, scratch2);
+
+      // The method data pointer needs to be updated to reflect the new target.
+      update_mdp_by_offset(in_bytes(RetData::bci_displacement_offset(row)), scratch1);
+      b(profile_continue);
+      bind(next_test);
+    }
+
+    update_mdp_for_ret(state, return_bci);
+
+    bind (profile_continue);
+  }
+}
+
+// Count the default case of a switch construct.
+void InterpreterMacroAssembler::profile_switch_default(Register scratch1,  Register scratch2) {
+  if (ProfileInterpreter) {
+    Label profile_continue;
+
+    // If no method data exists, go to profile_continue.
+    test_method_data_pointer(profile_continue);
+
+    // Update the default case count
+    increment_mdp_data_at(in_bytes(MultiBranchData::default_count_offset()),
+                          scratch1, scratch2);
+
+    // The method data pointer needs to be updated.
+    update_mdp_by_offset(in_bytes(MultiBranchData::default_displacement_offset()),
+                         scratch1);
+
+    bind (profile_continue);
+  }
+}
+
+// Count the index'th case of a switch construct.
+void InterpreterMacroAssembler::profile_switch_case(Register index,
+                                                    Register scratch1,
+                                                    Register scratch2,
+                                                    Register scratch3) {
+  if (ProfileInterpreter) {
+    assert_different_registers(index, scratch1, scratch2, scratch3);
+    Label profile_continue;
+
+    // If no method data exists, go to profile_continue.
+    test_method_data_pointer(profile_continue);
+
+    // Build the base (index * per_case_size_in_bytes()) + case_array_offset_in_bytes().
+    li(scratch3, in_bytes(MultiBranchData::case_array_offset()));
+
+    assert (in_bytes(MultiBranchData::per_case_size()) == 16, "so that shladd works");
+    sldi(scratch1, index, exact_log2(in_bytes(MultiBranchData::per_case_size())));
+    add(scratch1, scratch1, scratch3);
+
+    // Update the case count.
+    increment_mdp_data_at(scratch1, in_bytes(MultiBranchData::relative_count_offset()), scratch2, scratch3);
+
+    // The method data pointer needs to be updated.
+    update_mdp_by_offset(scratch1, in_bytes(MultiBranchData::relative_displacement_offset()), scratch2);
+
+    bind (profile_continue);
+  }
+}
+
+void InterpreterMacroAssembler::profile_null_seen(Register Rscratch1, Register Rscratch2) {
+  if (ProfileInterpreter) {
+    assert_different_registers(Rscratch1, Rscratch2);
+    Label profile_continue;
+
+    // If no method data exists, go to profile_continue.
+    test_method_data_pointer(profile_continue);
+
+    set_mdp_flag_at(BitData::null_seen_byte_constant(), Rscratch1);
+
+    // The method data pointer needs to be updated.
+    int mdp_delta = in_bytes(BitData::bit_data_size());
+    if (TypeProfileCasts) {
+      mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
+    }
+    update_mdp_by_constant(mdp_delta);
+
+    bind (profile_continue);
+  }
+}
+
+void InterpreterMacroAssembler::record_klass_in_profile(Register Rreceiver,
+                                                        Register Rscratch1, Register Rscratch2,
+                                                        bool is_virtual_call) {
+  assert(ProfileInterpreter, "must be profiling");
+  assert_different_registers(Rreceiver, Rscratch1, Rscratch2);
+
+  Label done;
+  record_klass_in_profile_helper(Rreceiver, Rscratch1, Rscratch2, 0, done, is_virtual_call);
+  bind (done);
+}
+
+void InterpreterMacroAssembler::record_klass_in_profile_helper(
+                                        Register receiver, Register scratch1, Register scratch2,
+                                        int start_row, Label& done, bool is_virtual_call) {
+  if (TypeProfileWidth == 0) {
+    if (is_virtual_call) {
+      increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2);
+    }
+    return;
+  }
+
+  int last_row = VirtualCallData::row_limit() - 1;
+  assert(start_row <= last_row, "must be work left to do");
+  // Test this row for both the receiver and for null.
+  // Take any of three different outcomes:
+  //   1. found receiver => increment count and goto done
+  //   2. found null => keep looking for case 1, maybe allocate this cell
+  //   3. found something else => keep looking for cases 1 and 2
+  // Case 3 is handled by a recursive call.
+  for (int row = start_row; row <= last_row; row++) {
+    Label next_test;
+    bool test_for_null_also = (row == start_row);
+
+    // See if the receiver is receiver[n].
+    int recvr_offset = in_bytes(VirtualCallData::receiver_offset(row));
+    test_mdp_data_at(recvr_offset, receiver, next_test, scratch1);
+    // delayed()->tst(scratch);
+
+    // The receiver is receiver[n]. Increment count[n].
+    int count_offset = in_bytes(VirtualCallData::receiver_count_offset(row));
+    increment_mdp_data_at(count_offset, scratch1, scratch2);
+    b(done);
+    bind(next_test);
+
+    if (test_for_null_also) {
+      Label found_null;
+      // Failed the equality check on receiver[n]... Test for null.
+      if (start_row == last_row) {
+        // The only thing left to do is handle the null case.
+        if (is_virtual_call) {
+          // Scratch1 contains test_out from test_mdp_data_at.
+          cmpdi(CCR0, scratch1, 0);
+          beq(CCR0, found_null);
+          // Receiver did not match any saved receiver and there is no empty row for it.
+          // Increment total counter to indicate polymorphic case.
+          increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2);
+          b(done);
+          bind(found_null);
+        } else {
+          cmpdi(CCR0, scratch1, 0);
+          bne(CCR0, done);
+        }
+        break;
+      }
+      // Since null is rare, make it be the branch-taken case.
+      cmpdi(CCR0, scratch1, 0);
+      beq(CCR0, found_null);
+
+      // Put all the "Case 3" tests here.
+      record_klass_in_profile_helper(receiver, scratch1, scratch2, start_row + 1, done, is_virtual_call);
+
+      // Found a null. Keep searching for a matching receiver,
+      // but remember that this is an empty (unused) slot.
+      bind(found_null);
+    }
+  }
+
+  // In the fall-through case, we found no matching receiver, but we
+  // observed the receiver[start_row] is NULL.
+
+  // Fill in the receiver field and increment the count.
+  int recvr_offset = in_bytes(VirtualCallData::receiver_offset(start_row));
+  set_mdp_data_at(recvr_offset, receiver);
+  int count_offset = in_bytes(VirtualCallData::receiver_count_offset(start_row));
+  li(scratch1, DataLayout::counter_increment);
+  set_mdp_data_at(count_offset, scratch1);
+  if (start_row > 0) {
+    b(done);
+  }
+}
+
+// Add a InterpMonitorElem to stack (see frame_sparc.hpp).
+void InterpreterMacroAssembler::add_monitor_to_stack(bool stack_is_empty, Register Rtemp1, Register Rtemp2) {
+
+  // Very-local scratch registers.
+  const Register esp  = Rtemp1;
+  const Register slot = Rtemp2;
+
+  // Extracted monitor_size.
+  int monitor_size = frame::interpreter_frame_monitor_size_in_bytes();
+  assert(Assembler::is_aligned((unsigned int)monitor_size,
+                               (unsigned int)frame::alignment_in_bytes),
+         "size of a monitor must respect alignment of SP");
+
+  resize_frame(-monitor_size, /*temp*/esp); // Allocate space for new monitor
+  std(R1_SP, _ijava_state_neg(top_frame_sp), esp); // esp contains fp
+
+  // Shuffle expression stack down. Recall that stack_base points
+  // just above the new expression stack bottom. Old_tos and new_tos
+  // are used to scan thru the old and new expression stacks.
+  if (!stack_is_empty) {
+    Label copy_slot, copy_slot_finished;
+    const Register n_slots = slot;
+
+    addi(esp, R15_esp, Interpreter::stackElementSize); // Point to first element (pre-pushed stack).
+    subf(n_slots, esp, R26_monitor);
+    srdi_(n_slots, n_slots, LogBytesPerWord);          // Compute number of slots to copy.
+    assert(LogBytesPerWord == 3, "conflicts assembler instructions");
+    beq(CCR0, copy_slot_finished);                     // Nothing to copy.
+
+    mtctr(n_slots);
+
+    // loop
+    bind(copy_slot);
+    ld(slot, 0, esp);              // Move expression stack down.
+    std(slot, -monitor_size, esp); // distance = monitor_size
+    addi(esp, esp, BytesPerWord);
+    bdnz(copy_slot);
+
+    bind(copy_slot_finished);
+  }
+
+  addi(R15_esp, R15_esp, -monitor_size);
+  addi(R26_monitor, R26_monitor, -monitor_size);
+
+  // Restart interpreter
+}
+
+// ============================================================================
+// Java locals access
+
+// Load a local variable at index in Rindex into register Rdst_value.
+// Also puts address of local into Rdst_address as a service.
+// Kills:
+//   - Rdst_value
+//   - Rdst_address
+void InterpreterMacroAssembler::load_local_int(Register Rdst_value, Register Rdst_address, Register Rindex) {
+  sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
+  subf(Rdst_address, Rdst_address, R18_locals);
+  lwz(Rdst_value, 0, Rdst_address);
+}
+
+// Load a local variable at index in Rindex into register Rdst_value.
+// Also puts address of local into Rdst_address as a service.
+// Kills:
+//   - Rdst_value
+//   - Rdst_address
+void InterpreterMacroAssembler::load_local_long(Register Rdst_value, Register Rdst_address, Register Rindex) {
+  sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
+  subf(Rdst_address, Rdst_address, R18_locals);
+  ld(Rdst_value, -8, Rdst_address);
+}
+
+// Load a local variable at index in Rindex into register Rdst_value.
+// Also puts address of local into Rdst_address as a service.
+// Input:
+//   - Rindex:      slot nr of local variable
+// Kills:
+//   - Rdst_value
+//   - Rdst_address
+void InterpreterMacroAssembler::load_local_ptr(Register Rdst_value, Register Rdst_address, Register Rindex) {
+  sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
+  subf(Rdst_address, Rdst_address, R18_locals);
+  ld(Rdst_value, 0, Rdst_address);
+}
+
+// Load a local variable at index in Rindex into register Rdst_value.
+// Also puts address of local into Rdst_address as a service.
+// Kills:
+//   - Rdst_value
+//   - Rdst_address
+void InterpreterMacroAssembler::load_local_float(FloatRegister Rdst_value, Register Rdst_address, Register Rindex) {
+  sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
+  subf(Rdst_address, Rdst_address, R18_locals);
+  lfs(Rdst_value, 0, Rdst_address);
+}
+
+// Load a local variable at index in Rindex into register Rdst_value.
+// Also puts address of local into Rdst_address as a service.
+// Kills:
+//   - Rdst_value
+//   - Rdst_address
+void InterpreterMacroAssembler::load_local_double(FloatRegister Rdst_value, Register Rdst_address, Register Rindex) {
+  sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
+  subf(Rdst_address, Rdst_address, R18_locals);
+  lfd(Rdst_value, -8, Rdst_address);
+}
+
+// Store an int value at local variable slot Rindex.
+// Kills:
+//   - Rindex
+void InterpreterMacroAssembler::store_local_int(Register Rvalue, Register Rindex) {
+  sldi(Rindex, Rindex, Interpreter::logStackElementSize);
+  subf(Rindex, Rindex, R18_locals);
+  stw(Rvalue, 0, Rindex);
+}
+
+// Store a long value at local variable slot Rindex.
+// Kills:
+//   - Rindex
+void InterpreterMacroAssembler::store_local_long(Register Rvalue, Register Rindex) {
+  sldi(Rindex, Rindex, Interpreter::logStackElementSize);
+  subf(Rindex, Rindex, R18_locals);
+  std(Rvalue, -8, Rindex);
+}
+
+// Store an oop value at local variable slot Rindex.
+// Kills:
+//   - Rindex
+void InterpreterMacroAssembler::store_local_ptr(Register Rvalue, Register Rindex) {
+  sldi(Rindex, Rindex, Interpreter::logStackElementSize);
+  subf(Rindex, Rindex, R18_locals);
+  std(Rvalue, 0, Rindex);
+}
+
+// Store an int value at local variable slot Rindex.
+// Kills:
+//   - Rindex
+void InterpreterMacroAssembler::store_local_float(FloatRegister Rvalue, Register Rindex) {
+  sldi(Rindex, Rindex, Interpreter::logStackElementSize);
+  subf(Rindex, Rindex, R18_locals);
+  stfs(Rvalue, 0, Rindex);
+}
+
+// Store an int value at local variable slot Rindex.
+// Kills:
+//   - Rindex
+void InterpreterMacroAssembler::store_local_double(FloatRegister Rvalue, Register Rindex) {
+  sldi(Rindex, Rindex, Interpreter::logStackElementSize);
+  subf(Rindex, Rindex, R18_locals);
+  stfd(Rvalue, -8, Rindex);
+}
+
+// Read pending exception from thread and jump to interpreter.
+// Throw exception entry if one if pending. Fall through otherwise.
+void InterpreterMacroAssembler::check_and_forward_exception(Register Rscratch1, Register Rscratch2) {
+  assert_different_registers(Rscratch1, Rscratch2, R3);
+  Register Rexception = Rscratch1;
+  Register Rtmp       = Rscratch2;
+  Label Ldone;
+  // Get pending exception oop.
+  ld(Rexception, thread_(pending_exception));
+  cmpdi(CCR0, Rexception, 0);
+  beq(CCR0, Ldone);
+  li(Rtmp, 0);
+  mr_if_needed(R3, Rexception);
+  std(Rtmp, thread_(pending_exception)); // Clear exception in thread
+  if (Interpreter::rethrow_exception_entry() != NULL) {
+    // Already got entry address.
+    load_dispatch_table(Rtmp, (address*)Interpreter::rethrow_exception_entry());
+  } else {
+    // Dynamically load entry address.
+    int simm16_rest = load_const_optimized(Rtmp, &Interpreter::_rethrow_exception_entry, R0, true);
+    ld(Rtmp, simm16_rest, Rtmp);
+  }
+  mtctr(Rtmp);
+  save_interpreter_state(Rtmp);
+  bctr();
+
+  align(32, 12);
+  bind(Ldone);
+}
+
+void InterpreterMacroAssembler::call_VM(Register oop_result, address entry_point, bool check_exceptions) {
+  save_interpreter_state(R11_scratch1);
+
+  MacroAssembler::call_VM(oop_result, entry_point, false);
+
+  restore_interpreter_state(R11_scratch1, /*bcp_and_mdx_only*/ true);
+
+  check_and_handle_popframe(R11_scratch1);
+  check_and_handle_earlyret(R11_scratch1);
+  // Now check exceptions manually.
+  if (check_exceptions) {
+    check_and_forward_exception(R11_scratch1, R12_scratch2);
+  }
+}
+
+void InterpreterMacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, bool check_exceptions) {
+  // ARG1 is reserved for the thread.
+  mr_if_needed(R4_ARG2, arg_1);
+  call_VM(oop_result, entry_point, check_exceptions);
+}
+
+void InterpreterMacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2, bool check_exceptions) {
+  // ARG1 is reserved for the thread.
+  mr_if_needed(R4_ARG2, arg_1);
+  assert(arg_2 != R4_ARG2, "smashed argument");
+  mr_if_needed(R5_ARG3, arg_2);
+  call_VM(oop_result, entry_point, check_exceptions);
+}
+
+void InterpreterMacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2, Register arg_3, bool check_exceptions) {
+  // ARG1 is reserved for the thread.
+  mr_if_needed(R4_ARG2, arg_1);
+  assert(arg_2 != R4_ARG2, "smashed argument");
+  mr_if_needed(R5_ARG3, arg_2);
+  assert(arg_3 != R4_ARG2 && arg_3 != R5_ARG3, "smashed argument");
+  mr_if_needed(R6_ARG4, arg_3);
+  call_VM(oop_result, entry_point, check_exceptions);
+}
+
+void InterpreterMacroAssembler::save_interpreter_state(Register scratch) {
+  ld(scratch, 0, R1_SP);
+  std(R15_esp, _ijava_state_neg(esp), scratch);
+  std(R14_bcp, _ijava_state_neg(bcp), scratch);
+  std(R26_monitor, _ijava_state_neg(monitors), scratch);
+  if (ProfileInterpreter) { std(R28_mdx, _ijava_state_neg(mdx), scratch); }
+  // Other entries should be unchanged.
+}
+
+void InterpreterMacroAssembler::restore_interpreter_state(Register scratch, bool bcp_and_mdx_only) {
+  ld(scratch, 0, R1_SP);
+  ld(R14_bcp, _ijava_state_neg(bcp), scratch); // Changed by VM code (exception).
+  if (ProfileInterpreter) { ld(R28_mdx, _ijava_state_neg(mdx), scratch); } // Changed by VM code.
+  if (!bcp_and_mdx_only) {
+    // Following ones are Metadata.
+    ld(R19_method, _ijava_state_neg(method), scratch);
+    ld(R27_constPoolCache, _ijava_state_neg(cpoolCache), scratch);
+    // Following ones are stack addresses and don't require reload.
+    ld(R15_esp, _ijava_state_neg(esp), scratch);
+    ld(R18_locals, _ijava_state_neg(locals), scratch);
+    ld(R26_monitor, _ijava_state_neg(monitors), scratch);
+  }
+#ifdef ASSERT
+  {
+    Label Lok;
+    subf(R0, R1_SP, scratch);
+    cmpdi(CCR0, R0, frame::abi_reg_args_size + frame::ijava_state_size);
+    bge(CCR0, Lok);
+    stop("frame too small (restore istate)", 0x5432);
+    bind(Lok);
+  }
+  {
+    Label Lok;
+    ld(R0, _ijava_state_neg(ijava_reserved), scratch);
+    cmpdi(CCR0, R0, 0x5afe);
+    beq(CCR0, Lok);
+    stop("frame corrupted (restore istate)", 0x5afe);
+    bind(Lok);
+  }
+#endif
+}
+
+#endif // !CC_INTERP
+
 void InterpreterMacroAssembler::get_method_counters(Register method,
                                                     Register Rcounters,
                                                     Label& skip) {
@@ -321,6 +1957,66 @@
   if (state == atos) { MacroAssembler::verify_oop(reg); }
 }
 
+#ifndef CC_INTERP
+// Local helper function for the verify_oop_or_return_address macro.
+static bool verify_return_address(Method* m, int bci) {
+#ifndef PRODUCT
+  address pc = (address)(m->constMethod()) + in_bytes(ConstMethod::codes_offset()) + bci;
+  // Assume it is a valid return address if it is inside m and is preceded by a jsr.
+  if (!m->contains(pc))                                            return false;
+  address jsr_pc;
+  jsr_pc = pc - Bytecodes::length_for(Bytecodes::_jsr);
+  if (*jsr_pc == Bytecodes::_jsr   && jsr_pc >= m->code_base())    return true;
+  jsr_pc = pc - Bytecodes::length_for(Bytecodes::_jsr_w);
+  if (*jsr_pc == Bytecodes::_jsr_w && jsr_pc >= m->code_base())    return true;
+#endif // PRODUCT
+  return false;
+}
+
+void InterpreterMacroAssembler::verify_FPU(int stack_depth, TosState state) {
+  if (VerifyFPU) {
+    unimplemented("verfiyFPU");
+  }
+}
+
+void InterpreterMacroAssembler::verify_oop_or_return_address(Register reg, Register Rtmp) {
+  if (!VerifyOops) return;
+
+  // The VM documentation for the astore[_wide] bytecode allows
+  // the TOS to be not only an oop but also a return address.
+  Label test;
+  Label skip;
+  // See if it is an address (in the current method):
+
+  const int log2_bytecode_size_limit = 16;
+  srdi_(Rtmp, reg, log2_bytecode_size_limit);
+  bne(CCR0, test);
+
+  address fd = CAST_FROM_FN_PTR(address, verify_return_address);
+  unsigned int nbytes_save = 10*8; // 10 volatile gprs
+
+  save_LR_CR(Rtmp);
+  push_frame_reg_args(nbytes_save, Rtmp);
+  save_volatile_gprs(R1_SP, 112); // except R0
+
+  load_const_optimized(Rtmp, fd, R0);
+  mr_if_needed(R4_ARG2, reg);
+  mr(R3_ARG1, R19_method);
+  call_c(Rtmp); // call C
+
+  restore_volatile_gprs(R1_SP, 112); // except R0
+  pop_frame();
+  restore_LR_CR(Rtmp);
+  b(skip);
+
+  // Perform a more elaborate out-of-line call.
+  // Not an address; verify it:
+  bind(test);
+  verify_oop(reg);
+  bind(skip);
+}
+#endif // !CC_INTERP
+
 // Inline assembly for:
 //
 // if (thread is in interp_only_mode) {
@@ -343,13 +2039,12 @@
     cmpwi(CCR0, R0, 0);
     beq(CCR0, jvmti_post_done);
     call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_entry),
-            /*check_exceptions=*/false);
+            /*check_exceptions=*/true CC_INTERP_ONLY(&& false));
 
     bind(jvmti_post_done);
   }
 }
 
-
 // Inline assembly for:
 //
 // if (thread is in interp_only_mode) {
@@ -365,26 +2060,33 @@
 //
 // Native methods have their result stored in d_tmp and l_tmp.
 // Java methods have their result stored in the expression stack.
-void InterpreterMacroAssembler::notify_method_exit(bool is_native_method, TosState state) {
+void InterpreterMacroAssembler::notify_method_exit(bool is_native_method, TosState state,
+                                                   NotifyMethodExitMode mode, bool check_exceptions) {
   // JVMTI
   // Whenever JVMTI puts a thread in interp_only_mode, method
   // entry/exit events are sent for that thread to track stack
   // depth. If it is possible to enter interp_only_mode we add
   // the code to check if the event should be sent.
-  if (JvmtiExport::can_post_interpreter_events()) {
+  if (mode == NotifyJVMTI && JvmtiExport::can_post_interpreter_events()) {
     Label jvmti_post_done;
 
     lwz(R0, in_bytes(JavaThread::interp_only_mode_offset()), R16_thread);
     cmpwi(CCR0, R0, 0);
     beq(CCR0, jvmti_post_done);
+    CC_INTERP_ONLY(assert(is_native_method && !check_exceptions, "must not push state"));
+    if (!is_native_method) push(state); // Expose tos to GC.
     call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_exit),
-            /*check_exceptions=*/false);
+            /*check_exceptions=*/check_exceptions);
+    if (!is_native_method) pop(state);
 
     align(32, 12);
     bind(jvmti_post_done);
   }
+
+  // Dtrace support not implemented.
 }
 
+#ifdef CC_INTERP
 // Convert the current TOP_IJAVA_FRAME into a PARENT_IJAVA_FRAME
 // (using parent_frame_resize) and push a new interpreter
 // TOP_IJAVA_FRAME (using frame_size).
@@ -442,7 +2144,6 @@
   std(R1_SP, _top_ijava_frame_abi(top_frame_sp), R1_SP);
 }
 
-#ifdef CC_INTERP
 // Turn state's interpreter frame into the current TOP_IJAVA_FRAME.
 void InterpreterMacroAssembler::pop_interpreter_frame_to_state(Register state, Register tmp1, Register tmp2, Register tmp3) {
   assert_different_registers(R14_state, R15_prev_state, tmp1, tmp2, tmp3);
@@ -471,7 +2172,6 @@
   // Used for non-initial callers by unextended_sp().
   std(R1_SP, _top_ijava_frame_abi(initial_caller_sp), R1_SP);
 }
-#endif // CC_INTERP
 
 // Set SP to initial caller's sp, but before fix the back chain.
 void InterpreterMacroAssembler::resize_frame_to_initial_caller(Register tmp1, Register tmp2) {
@@ -481,7 +2181,6 @@
   mr(R1_SP, tmp1); // ... and resize to initial caller.
 }
 
-#ifdef CC_INTERP
 // Pop the current interpreter state (without popping the correspoding
 // frame) and restore R14_state and R15_prev_state accordingly.
 // Use prev_state_may_be_0 to indicate whether prev_state may be 0
--- a/hotspot/src/cpu/ppc/vm/interp_masm_ppc_64.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/interp_masm_ppc_64.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright 2012, 2014 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
@@ -29,7 +29,7 @@
 #include "assembler_ppc.inline.hpp"
 #include "interpreter/invocationCounter.hpp"
 
-// This file specializes the assembler with interpreter-specific macros
+// This file specializes the assembler with interpreter-specific macros.
 
 
 class InterpreterMacroAssembler: public MacroAssembler {
@@ -39,15 +39,176 @@
 
   void null_check_throw(Register a, int offset, Register temp_reg);
 
-  // Handy address generation macros
+  void branch_to_entry(address entry, Register Rscratch);
+
+  // Handy address generation macros.
 #define thread_(field_name) in_bytes(JavaThread::field_name ## _offset()), R16_thread
 #define method_(field_name) in_bytes(Method::field_name ## _offset()), R19_method
 
 #ifdef CC_INTERP
 #define state_(field_name)  in_bytes(byte_offset_of(BytecodeInterpreter, field_name)), R14_state
 #define prev_state_(field_name)  in_bytes(byte_offset_of(BytecodeInterpreter, field_name)), R15_prev_state
+  void pop (TosState state) {};           // Not needed.
+  void push(TosState state) {};           // Not needed.
 #endif
 
+#ifndef CC_INTERP
+  virtual void check_and_handle_popframe(Register java_thread);
+  virtual void check_and_handle_earlyret(Register java_thread);
+
+  // Base routine for all dispatches.
+  void dispatch_base(TosState state, address* table);
+
+  void load_earlyret_value(TosState state, Register Rscratch1);
+
+  static const Address l_tmp;
+  static const Address d_tmp;
+
+  // dispatch routines
+  void dispatch_next(TosState state, int step = 0);
+  void dispatch_via (TosState state, address* table);
+  void load_dispatch_table(Register dst, address* table);
+  void dispatch_Lbyte_code(TosState state, Register bytecode, address* table, bool verify = false);
+
+  // Called by shared interpreter generator.
+  void dispatch_prolog(TosState state, int step = 0);
+  void dispatch_epilog(TosState state, int step = 0);
+
+  // Super call_VM calls - correspond to MacroAssembler::call_VM(_leaf) calls.
+  void super_call_VM_leaf(Register thread_cache, address entry_point, Register arg_1);
+  void super_call_VM(Register thread_cache, Register oop_result, Register last_java_sp,
+                     address entry_point, Register arg_1, Register arg_2, bool check_exception = true);
+
+  // Generate a subtype check: branch to ok_is_subtype if sub_klass is
+  // a subtype of super_klass.  Blows registers tmp1, tmp2 and tmp3.
+  void gen_subtype_check(Register sub_klass, Register super_klass,
+                         Register tmp1, Register tmp2, Register tmp3, Label &ok_is_subtype);
+
+  // Load object from cpool->resolved_references(index).
+  void load_resolved_reference_at_index(Register result, Register index);
+
+  void generate_stack_overflow_check_with_compare_and_throw(Register Rmem_frame_size, Register Rscratch1);
+  void load_receiver(Register Rparam_count, Register Rrecv_dst);
+
+  // helpers for expression stack
+  void pop_i(     Register r = R17_tos);
+  void pop_ptr(   Register r = R17_tos);
+  void pop_l(     Register r = R17_tos);
+  void pop_f(FloatRegister f = F15_ftos);
+  void pop_d(FloatRegister f = F15_ftos );
+
+  void push_i(     Register r = R17_tos);
+  void push_ptr(   Register r = R17_tos);
+  void push_l(     Register r = R17_tos);
+  void push_f(FloatRegister f = F15_ftos );
+  void push_d(FloatRegister f = F15_ftos);
+
+  void push_2ptrs(Register first, Register second);
+
+  void push_l_pop_d(Register l = R17_tos, FloatRegister d = F15_ftos);
+  void push_d_pop_l(FloatRegister d = F15_ftos, Register l = R17_tos);
+
+  void pop (TosState state);           // transition vtos -> state
+  void push(TosState state);           // transition state -> vtos
+  void empty_expression_stack();       // Resets both Lesp and SP.
+
+ public:
+  // Load values from bytecode stream:
+
+  enum signedOrNot { Signed, Unsigned };
+  enum setCCOrNot  { set_CC, dont_set_CC };
+
+  void get_2_byte_integer_at_bcp(int         bcp_offset,
+                                 Register    Rdst,
+                                 signedOrNot is_signed);
+
+  void get_4_byte_integer_at_bcp(int         bcp_offset,
+                                 Register    Rdst,
+                                 signedOrNot is_signed = Unsigned);
+
+  void get_cache_index_at_bcp(Register Rdst, int bcp_offset, size_t index_size);
+
+  void get_cache_and_index_at_bcp(Register cache, int bcp_offset, size_t index_size = sizeof(u2));
+
+
+  // common code
+
+  void field_offset_at(int n, Register tmp, Register dest, Register base);
+  int  field_offset_at(Register object, address bcp, int offset);
+  void fast_iaaccess(int n, address bcp);
+  void fast_iagetfield(address bcp);
+  void fast_iaputfield(address bcp, bool do_store_check);
+
+  void index_check(Register array, Register index, int index_shift, Register tmp, Register res);
+  void index_check_without_pop(Register array, Register index, int index_shift, Register tmp, Register res);
+
+  void get_const(Register Rdst);
+  void get_constant_pool(Register Rdst);
+  void get_constant_pool_cache(Register Rdst);
+  void get_cpool_and_tags(Register Rcpool, Register Rtags);
+  void is_a(Label& L);
+
+  // Java Call Helpers
+  void call_from_interpreter(Register Rtarget_method, Register Rret_addr, Register Rscratch1, Register Rscratch2);
+
+  // --------------------------------------------------
+
+  void unlock_if_synchronized_method(TosState state, bool throw_monitor_exception = true,
+                                     bool install_monitor_exception = true);
+
+  // Removes the current activation (incl. unlocking of monitors).
+  // Additionally this code is used for earlyReturn in which case we
+  // want to skip throwing an exception and installing an exception.
+  void remove_activation(TosState state,
+                         bool throw_monitor_exception = true,
+                         bool install_monitor_exception = true);
+  void merge_frames(Register Rtop_frame_sp, Register return_pc, Register Rscratch1, Register Rscratch2); // merge top frames
+
+  void add_monitor_to_stack(bool stack_is_empty, Register Rtemp1, Register Rtemp2);
+
+  // Local variable access helpers
+  void load_local_int(Register Rdst_value, Register Rdst_address, Register Rindex);
+  void load_local_long(Register Rdst_value, Register Rdst_address, Register Rindex);
+  void load_local_ptr(Register Rdst_value, Register Rdst_address, Register Rindex);
+  void load_local_float(FloatRegister Rdst_value, Register Rdst_address, Register Rindex);
+  void load_local_double(FloatRegister Rdst_value, Register Rdst_address, Register Rindex);
+  void store_local_int(Register Rvalue, Register Rindex);
+  void store_local_long(Register Rvalue, Register Rindex);
+  void store_local_ptr(Register Rvalue, Register Rindex);
+  void store_local_float(FloatRegister Rvalue, Register Rindex);
+  void store_local_double(FloatRegister Rvalue, Register Rindex);
+
+  // Call VM for std frames
+  // Special call VM versions that check for exceptions and forward exception
+  // via short cut (not via expensive forward exception stub).
+  void check_and_forward_exception(Register Rscratch1, Register Rscratch2);
+  void call_VM(Register oop_result, address entry_point, bool check_exceptions = true);
+  void call_VM(Register oop_result, address entry_point, Register arg_1, bool check_exceptions = true);
+  void call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2, bool check_exceptions = true);
+  void call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2, Register arg_3, bool check_exceptions = true);
+  // Should not be used:
+  void call_VM(Register oop_result, Register last_java_sp, address entry_point, bool check_exceptions = true) {ShouldNotReachHere();}
+  void call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, bool check_exceptions = true) {ShouldNotReachHere();}
+  void call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, Register arg_2, bool check_exceptions = true) {ShouldNotReachHere();}
+  void call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, Register arg_2, Register arg_3, bool check_exceptions = true) {ShouldNotReachHere();}
+
+  Address first_local_in_stack();
+
+  enum LoadOrStore { load, store };
+  void static_iload_or_store(int which_local, LoadOrStore direction, Register Rtmp);
+  void static_aload_or_store(int which_local, LoadOrStore direction, Register Rtmp);
+  void static_dload_or_store(int which_local, LoadOrStore direction);
+
+  void save_interpreter_state(Register scratch);
+  void restore_interpreter_state(Register scratch, bool bcp_and_mdx_only = false);
+
+  void increment_backedge_counter(const Register Rcounters, Register Rtmp, Register Rtmp2, Register Rscratch);
+  void test_backedge_count_for_osr(Register backedge_count, Register branch_bcp, Register Rtmp);
+
+  void record_static_call_in_profile(Register Rentry, Register Rtmp);
+  void record_receiver_call_in_profile(Register Rklass, Register Rentry, Register Rtmp);
+#endif // !CC_INTERP
+
   void get_method_counters(Register method, Register Rcounters, Label& skip);
   void increment_invocation_counter(Register iv_be_count, Register Rtmp1, Register Rtmp2_r0);
 
@@ -55,12 +216,59 @@
   void lock_object  (Register lock_reg, Register obj_reg);
   void unlock_object(Register lock_reg, bool check_for_exceptions = true);
 
+#ifndef CC_INTERP
+
+  // Interpreter profiling operations
+  void set_method_data_pointer_for_bcp();
+  void test_method_data_pointer(Label& zero_continue);
+  void verify_method_data_pointer();
+  void test_invocation_counter_for_mdp(Register invocation_count, Register Rscratch, Label &profile_continue);
+
+  void set_mdp_data_at(int constant, Register value);
+
+  void increment_mdp_data_at(int constant, Register counter_addr, Register Rbumped_count, bool decrement = false);
+
+  void increment_mdp_data_at(Register counter_addr, Register Rbumped_count, bool decrement = false);
+  void increment_mdp_data_at(Register reg, int constant, Register scratch, Register Rbumped_count, bool decrement = false);
+
+  void set_mdp_flag_at(int flag_constant, Register scratch);
+  void test_mdp_data_at(int offset, Register value, Label& not_equal_continue, Register test_out);
+
+  void update_mdp_by_offset(int offset_of_disp, Register scratch);
+  void update_mdp_by_offset(Register reg, int offset_of_disp,
+                            Register scratch);
+  void update_mdp_by_constant(int constant);
+  void update_mdp_for_ret(TosState state, Register return_bci);
+
+  void profile_taken_branch(Register scratch, Register bumped_count);
+  void profile_not_taken_branch(Register scratch1, Register scratch2);
+  void profile_call(Register scratch1, Register scratch2);
+  void profile_final_call(Register scratch1, Register scratch2);
+  void profile_virtual_call(Register Rreceiver, Register Rscratch1, Register Rscratch2,  bool receiver_can_be_null);
+  void profile_typecheck(Register Rklass, Register Rscratch1, Register Rscratch2);
+  void profile_typecheck_failed(Register Rscratch1, Register Rscratch2);
+  void profile_ret(TosState state, Register return_bci, Register scratch1, Register scratch2);
+  void profile_switch_default(Register scratch1, Register scratch2);
+  void profile_switch_case(Register index, Register scratch1,Register scratch2, Register scratch3);
+  void profile_null_seen(Register Rscratch1, Register Rscratch2);
+  void record_klass_in_profile(Register receiver, Register scratch1, Register scratch2, bool is_virtual_call);
+  void record_klass_in_profile_helper(Register receiver, Register scratch1, Register scratch2, int start_row, Label& done, bool is_virtual_call);
+
+#endif // !CC_INTERP
+
   // Debugging
   void verify_oop(Register reg, TosState state = atos);    // only if +VerifyOops && state == atos
+#ifndef CC_INTERP
+  void verify_oop_or_return_address(Register reg, Register rtmp); // for astore
+  void verify_FPU(int stack_depth, TosState state = ftos);
+#endif // !CC_INTERP
 
-  // support for jvmdi/jvmpi
+  typedef enum { NotifyJVMTI, SkipNotifyJVMTI } NotifyMethodExitMode;
+
+  // Support for jvmdi/jvmpi.
   void notify_method_entry();
-  void notify_method_exit(bool is_native_method, TosState state);
+  void notify_method_exit(bool is_native_method, TosState state,
+                          NotifyMethodExitMode mode, bool check_exceptions);
 
 #ifdef CC_INTERP
   // Convert the current TOP_IJAVA_FRAME into a PARENT_IJAVA_FRAME
--- a/hotspot/src/cpu/ppc/vm/interpreterRT_ppc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/interpreterRT_ppc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -109,8 +109,10 @@
 }
 
 void InterpreterRuntime::SignatureHandlerGenerator::generate(uint64_t fingerprint) {
+#if !defined(ABI_ELFv2)
   // Emit fd for current codebuffer. Needs patching!
   __ emit_fd();
+#endif
 
   // Generate code to handle arguments.
   iterate(fingerprint);
@@ -127,11 +129,13 @@
 // Implementation of SignatureHandlerLibrary
 
 void SignatureHandlerLibrary::pd_set_handler(address handler) {
+#if !defined(ABI_ELFv2)
   // patch fd here.
   FunctionDescriptor* fd = (FunctionDescriptor*) handler;
 
   fd->set_entry(handler + (int)sizeof(FunctionDescriptor));
   assert(fd->toc() == (address)0xcafe, "need to adjust TOC here");
+#endif
 }
 
 
--- a/hotspot/src/cpu/ppc/vm/interpreter_ppc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/interpreter_ppc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2012, 2014 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
@@ -51,10 +51,6 @@
 #include "c1/c1_Runtime1.hpp"
 #endif
 
-#ifndef CC_INTERP
-#error "CC_INTERP must be defined on PPC"
-#endif
-
 #define __ _masm->
 
 #ifdef PRODUCT
@@ -128,13 +124,13 @@
   const Register target_sp      = R28_tmp8;
   const FloatRegister floatSlot = F0;
 
-  address entry = __ emit_fd();
+  address entry = __ function_entry();
 
   __ save_LR_CR(R0);
   __ save_nonvolatile_gprs(R1_SP, _spill_nonvolatiles_neg(r14));
   // We use target_sp for storing arguments in the C frame.
   __ mr(target_sp, R1_SP);
-  __ push_frame_abi112_nonvolatiles(0, R11_scratch1);
+  __ push_frame_reg_args_nonvolatiles(0, R11_scratch1);
 
   __ mr(arg_java, R3_ARG1);
 
@@ -147,7 +143,8 @@
 #ifdef CC_INTERP
   __ ld(R19_method, state_(_method));
 #else
-  __ unimplemented("slow signature handler 1");
+  __ ld(R19_method, 0, target_sp);
+  __ ld(R19_method, _ijava_state_neg(method), R19_method);
 #endif
 
   // Get the result handler.
@@ -157,7 +154,8 @@
 #ifdef CC_INTERP
   __ ld(R19_method, state_(_method));
 #else
-  __ unimplemented("slow signature handler 2");
+  __ ld(R19_method, 0, target_sp);
+  __ ld(R19_method, _ijava_state_neg(method), R19_method);
 #endif
 
   {
@@ -453,7 +451,7 @@
   //
   // Registers alive
   //   R16_thread     - JavaThread*
-  //   R19_method     - callee's methodOop (method to be invoked)
+  //   R19_method     - callee's method (method to be invoked)
   //   R1_SP          - SP prepared such that caller's outgoing args are near top
   //   LR             - return address to caller
   //
@@ -474,7 +472,7 @@
 
   // Push a new C frame and save LR.
   __ save_LR_CR(R0);
-  __ push_frame_abi112(0, R11_scratch1);
+  __ push_frame_reg_args(0, R11_scratch1);
 
   // This is not a leaf but we have a JavaFrameAnchor now and we will
   // check (create) exceptions afterward so this is ok.
@@ -491,7 +489,12 @@
   // Return to frame manager, it will handle the pending exception.
   __ blr();
 #else
-  Unimplemented();
+  // We don't know our caller, so jump to the general forward exception stub,
+  // which will also pop our full frame off. Satisfy the interface of
+  // SharedRuntime::generate_forward_exception()
+  __ load_const_optimized(R11_scratch1, StubRoutines::forward_exception_entry(), R0);
+  __ mtctr(R11_scratch1);
+  __ bctr();
 #endif
 
   return entry;
@@ -500,8 +503,9 @@
 // Call an accessor method (assuming it is resolved, otherwise drop into
 // vanilla (slow path) entry.
 address InterpreterGenerator::generate_accessor_entry(void) {
-  if(!UseFastAccessorMethods && (!FLAG_IS_ERGO(UseFastAccessorMethods)))
+  if (!UseFastAccessorMethods && (!FLAG_IS_ERGO(UseFastAccessorMethods))) {
     return NULL;
+  }
 
   Label Lslow_path, Lacquire;
 
@@ -586,10 +590,14 @@
   // Load from branch table and dispatch (volatile case: one instruction ahead)
   __ sldi(Rflags, Rflags, LogBytesPerWord);
   __ cmpwi(CCR6, Rscratch, 1); // volatile?
-  __ sldi(Rscratch, Rscratch, exact_log2(BytesPerInstWord)); // volatile ? size of 1 instruction : 0
+  if (support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    __ sldi(Rscratch, Rscratch, exact_log2(BytesPerInstWord)); // volatile ? size of 1 instruction : 0
+  }
   __ ldx(Rbtable, Rbtable, Rflags);
 
-  __ subf(Rbtable, Rscratch, Rbtable); // point to volatile/non-volatile entry point
+  if (support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    __ subf(Rbtable, Rscratch, Rbtable); // point to volatile/non-volatile entry point
+  }
   __ mtctr(Rbtable);
   __ bctr();
 
@@ -605,7 +613,7 @@
   }
   assert(all_uninitialized != all_initialized, "consistency"); // either or
 
-  __ sync(); // volatile entry point (one instruction before non-volatile_entry point)
+  __ fence(); // volatile entry point (one instruction before non-volatile_entry point)
   if (branch_table[vtos] == 0) branch_table[vtos] = __ pc(); // non-volatile_entry point
   if (branch_table[dtos] == 0) branch_table[dtos] = __ pc(); // non-volatile_entry point
   if (branch_table[ftos] == 0) branch_table[ftos] = __ pc(); // non-volatile_entry point
@@ -614,7 +622,7 @@
 
   if (branch_table[itos] == 0) { // generate only once
     __ align(32, 28, 28); // align load
-    __ sync(); // volatile entry point (one instruction before non-volatile_entry point)
+    __ fence(); // volatile entry point (one instruction before non-volatile_entry point)
     branch_table[itos] = __ pc(); // non-volatile_entry point
     __ lwax(R3_RET, Rclass_or_obj, Roffset);
     __ beq(CCR6, Lacquire);
@@ -623,7 +631,7 @@
 
   if (branch_table[ltos] == 0) { // generate only once
     __ align(32, 28, 28); // align load
-    __ sync(); // volatile entry point (one instruction before non-volatile_entry point)
+    __ fence(); // volatile entry point (one instruction before non-volatile_entry point)
     branch_table[ltos] = __ pc(); // non-volatile_entry point
     __ ldx(R3_RET, Rclass_or_obj, Roffset);
     __ beq(CCR6, Lacquire);
@@ -632,7 +640,7 @@
 
   if (branch_table[btos] == 0) { // generate only once
     __ align(32, 28, 28); // align load
-    __ sync(); // volatile entry point (one instruction before non-volatile_entry point)
+    __ fence(); // volatile entry point (one instruction before non-volatile_entry point)
     branch_table[btos] = __ pc(); // non-volatile_entry point
     __ lbzx(R3_RET, Rclass_or_obj, Roffset);
     __ extsb(R3_RET, R3_RET);
@@ -642,7 +650,7 @@
 
   if (branch_table[ctos] == 0) { // generate only once
     __ align(32, 28, 28); // align load
-    __ sync(); // volatile entry point (one instruction before non-volatile_entry point)
+    __ fence(); // volatile entry point (one instruction before non-volatile_entry point)
     branch_table[ctos] = __ pc(); // non-volatile_entry point
     __ lhzx(R3_RET, Rclass_or_obj, Roffset);
     __ beq(CCR6, Lacquire);
@@ -651,7 +659,7 @@
 
   if (branch_table[stos] == 0) { // generate only once
     __ align(32, 28, 28); // align load
-    __ sync(); // volatile entry point (one instruction before non-volatile_entry point)
+    __ fence(); // volatile entry point (one instruction before non-volatile_entry point)
     branch_table[stos] = __ pc(); // non-volatile_entry point
     __ lhax(R3_RET, Rclass_or_obj, Roffset);
     __ beq(CCR6, Lacquire);
@@ -660,7 +668,7 @@
 
   if (branch_table[atos] == 0) { // generate only once
     __ align(32, 28, 28); // align load
-    __ sync(); // volatile entry point (one instruction before non-volatile_entry point)
+    __ fence(); // volatile entry point (one instruction before non-volatile_entry point)
     branch_table[atos] = __ pc(); // non-volatile_entry point
     __ load_heap_oop(R3_RET, (RegisterOrConstant)Roffset, Rclass_or_obj);
     __ verify_oop(R3_RET);
@@ -683,10 +691,7 @@
 #endif
 
   __ bind(Lslow_path);
-  assert(Interpreter::entry_for_kind(Interpreter::zerolocals), "Normal entry must have been generated by now");
-  __ load_const_optimized(Rscratch, Interpreter::entry_for_kind(Interpreter::zerolocals), R0);
-  __ mtctr(Rscratch);
-  __ bctr();
+  __ branch_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals), Rscratch);
   __ flush();
 
   return entry;
@@ -773,10 +778,7 @@
 
     // Generate regular method entry.
     __ bind(slow_path);
-    assert(Interpreter::entry_for_kind(Interpreter::zerolocals), "Normal entry must have been generated by now");
-    __ load_const_optimized(R11_scratch1, Interpreter::entry_for_kind(Interpreter::zerolocals), R0);
-    __ mtctr(R11_scratch1);
-    __ bctr();
+    __ branch_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals), R11_scratch1);
     __ flush();
 
     return entry;
--- a/hotspot/src/cpu/ppc/vm/interpreter_ppc.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/interpreter_ppc.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright 2012, 2014 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
@@ -28,15 +28,23 @@
 
  public:
 
-  // Stack index relative to tos (which points at value)
+  // Stack index relative to tos (which points at value).
   static int expr_index_at(int i) {
     return stackElementWords * i;
   }
 
-  // Already negated by c++ interpreter
+  // Already negated by c++ interpreter.
   static int local_index_at(int i) {
     assert(i <= 0, "local direction already negated");
     return stackElementWords * i;
   }
 
+#ifndef CC_INTERP
+  // The offset in bytes to access a expression stack slot
+  // relative to the esp pointer.
+  static int expr_offset_in_bytes(int slot) {
+    return stackElementSize * slot + wordSize;
+  }
+#endif
+
 #endif // CPU_PPC_VM_INTERPRETER_PPC_PP
--- a/hotspot/src/cpu/ppc/vm/javaFrameAnchor_ppc.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/javaFrameAnchor_ppc.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright 2012, 2014 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
@@ -26,10 +26,6 @@
 #ifndef CPU_PPC_VM_JAVAFRAMEANCHOR_PPC_HPP
 #define CPU_PPC_VM_JAVAFRAMEANCHOR_PPC_HPP
 
-#ifndef CC_INTERP
-#error "CC_INTERP must be defined on PPC64"
-#endif
-
 public:
   // Each arch must define reset, save, restore
   // These are used by objects that only care about:
--- a/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -594,7 +594,13 @@
            "can't identify emitted call");
   } else {
     // variant 1:
-
+#if defined(ABI_ELFv2)
+    nop();
+    calculate_address_from_global_toc(R12, dest, true, true, false);
+    mtctr(R12);
+    nop();
+    nop();
+#else
     mr(R0, R11);  // spill R11 -> R0.
 
     // Load the destination address into CTR,
@@ -604,6 +610,7 @@
     mtctr(R11);
     mr(R11, R0);  // spill R11 <- R0.
     nop();
+#endif
 
     // do the call/jump
     if (link) {
@@ -912,16 +919,16 @@
   }
 }
 
-// Push a frame of size `bytes' plus abi112 on top.
-void MacroAssembler::push_frame_abi112(unsigned int bytes, Register tmp) {
-  push_frame(bytes + frame::abi_112_size, tmp);
+// Push a frame of size `bytes' plus abi_reg_args on top.
+void MacroAssembler::push_frame_reg_args(unsigned int bytes, Register tmp) {
+  push_frame(bytes + frame::abi_reg_args_size, tmp);
 }
 
 // Setup up a new C frame with a spill area for non-volatile GPRs and
 // additional space for local variables.
-void MacroAssembler::push_frame_abi112_nonvolatiles(unsigned int bytes,
-                                                    Register tmp) {
-  push_frame(bytes + frame::abi_112_size + frame::spill_nonvolatiles_size, tmp);
+void MacroAssembler::push_frame_reg_args_nonvolatiles(unsigned int bytes,
+                                                      Register tmp) {
+  push_frame(bytes + frame::abi_reg_args_size + frame::spill_nonvolatiles_size, tmp);
 }
 
 // Pop current C frame.
@@ -929,6 +936,42 @@
   ld(R1_SP, _abi(callers_sp), R1_SP);
 }
 
+#if defined(ABI_ELFv2)
+address MacroAssembler::branch_to(Register r_function_entry, bool and_link) {
+  // TODO(asmundak): make sure the caller uses R12 as function descriptor
+  // most of the times.
+  if (R12 != r_function_entry) {
+    mr(R12, r_function_entry);
+  }
+  mtctr(R12);
+  // Do a call or a branch.
+  if (and_link) {
+    bctrl();
+  } else {
+    bctr();
+  }
+  _last_calls_return_pc = pc();
+
+  return _last_calls_return_pc;
+}
+
+// Call a C function via a function descriptor and use full C
+// calling conventions. Updates and returns _last_calls_return_pc.
+address MacroAssembler::call_c(Register r_function_entry) {
+  return branch_to(r_function_entry, /*and_link=*/true);
+}
+
+// For tail calls: only branch, don't link, so callee returns to caller of this function.
+address MacroAssembler::call_c_and_return_to_caller(Register r_function_entry) {
+  return branch_to(r_function_entry, /*and_link=*/false);
+}
+
+address MacroAssembler::call_c(address function_entry, relocInfo::relocType rt) {
+  load_const(R12, function_entry, R0);
+  return branch_to(R12,  /*and_link=*/true);
+}
+
+#else
 // Generic version of a call to C function via a function descriptor
 // with variable support for C calling conventions (TOC, ENV, etc.).
 // Updates and returns _last_calls_return_pc.
@@ -1077,6 +1120,7 @@
   }
   return _last_calls_return_pc;
 }
+#endif
 
 void MacroAssembler::call_VM_base(Register oop_result,
                                   Register last_java_sp,
@@ -1091,8 +1135,11 @@
 
   // ARG1 must hold thread address.
   mr(R3_ARG1, R16_thread);
-
+#if defined(ABI_ELFv2)
+  address return_pc = call_c(entry_point, relocInfo::none);
+#else
   address return_pc = call_c((FunctionDescriptor*)entry_point, relocInfo::none);
+#endif
 
   reset_last_Java_frame();
 
@@ -1113,7 +1160,11 @@
 
 void MacroAssembler::call_VM_leaf_base(address entry_point) {
   BLOCK_COMMENT("call_VM_leaf {");
+#if defined(ABI_ELFv2)
+  call_c(entry_point, relocInfo::none);
+#else
   call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, entry_point), relocInfo::none);
+#endif
   BLOCK_COMMENT("} call_VM_leaf");
 }
 
@@ -2227,7 +2278,7 @@
   // VM call need frame to access(write) O register.
   if (needs_frame) {
     save_LR_CR(Rtmp1);
-    push_frame_abi112(0, Rtmp2);
+    push_frame_reg_args(0, Rtmp2);
   }
 
   if (Rpre_val->is_volatile() && Robj == noreg) mr(R31, Rpre_val); // Save pre_val across C call if it was preloaded.
@@ -2361,7 +2412,8 @@
 #ifdef CC_INTERP
   ld(tmp1/*pc*/, _top_ijava_frame_abi(frame_manager_lr), sp);
 #else
-  Unimplemented();
+  address entry = pc();
+  load_const_optimized(tmp1, entry);
 #endif
 
   set_last_Java_frame(/*sp=*/sp, /*pc=*/tmp1);
@@ -2421,6 +2473,16 @@
   }
 }
 
+void MacroAssembler::store_klass_gap(Register dst_oop, Register val) {
+  if (UseCompressedClassPointers) {
+    if (val == noreg) {
+      val = R0;
+      li(val, 0);
+    }
+    stw(val, oopDesc::klass_gap_offset_in_bytes(), dst_oop); // klass gap if compressed
+  }
+}
+
 int MacroAssembler::instr_size_for_decode_klass_not_null() {
   if (!UseCompressedClassPointers) return 0;
   int num_instrs = 1;  // shift or move
@@ -3006,13 +3068,13 @@
   mr(R0, tmp);
   // kill tmp
   save_LR_CR(tmp);
-  push_frame_abi112(nbytes_save, tmp);
+  push_frame_reg_args(nbytes_save, tmp);
   // restore tmp
   mr(tmp, R0);
   save_volatile_gprs(R1_SP, 112); // except R0
-  // load FunctionDescriptor**
+  // load FunctionDescriptor** / entry_address *
   load_const(tmp, fd);
-  // load FunctionDescriptor*
+  // load FunctionDescriptor* / entry_address
   ld(tmp, 0, tmp);
   mr(R4_ARG2, oop);
   load_const(R3_ARG1, (address)msg);
@@ -3092,3 +3154,15 @@
 }
 
 #endif // !PRODUCT
+
+SkipIfEqualZero::SkipIfEqualZero(MacroAssembler* masm, Register temp, const bool* flag_addr) : _masm(masm), _label() {
+  int simm16_offset = masm->load_const_optimized(temp, (address)flag_addr, R0, true);
+  assert(sizeof(bool) == 1, "PowerPC ABI");
+  masm->lbz(temp, simm16_offset, temp);
+  masm->cmpwi(CCR0, temp, 0);
+  masm->beq(CCR0, _label);
+}
+
+SkipIfEqualZero::~SkipIfEqualZero() {
+  _masm->bind(_label);
+}
--- a/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright 2012, 2014 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
@@ -279,12 +279,12 @@
   // Push a frame of size `bytes'. No abi space provided.
   void push_frame(unsigned int bytes, Register tmp);
 
-  // Push a frame of size `bytes' plus abi112 on top.
-  void push_frame_abi112(unsigned int bytes, Register tmp);
+  // Push a frame of size `bytes' plus abi_reg_args on top.
+  void push_frame_reg_args(unsigned int bytes, Register tmp);
 
   // Setup up a new C frame with a spill area for non-volatile GPRs and additional
   // space for local variables
-  void push_frame_abi112_nonvolatiles(unsigned int bytes, Register tmp);
+  void push_frame_reg_args_nonvolatiles(unsigned int bytes, Register tmp);
 
   // pop current C frame
   void pop_frame();
@@ -296,17 +296,31 @@
  private:
   address _last_calls_return_pc;
 
+#if defined(ABI_ELFv2)
+  // Generic version of a call to C function.
+  // Updates and returns _last_calls_return_pc.
+  address branch_to(Register function_entry, bool and_link);
+#else
   // Generic version of a call to C function via a function descriptor
   // with variable support for C calling conventions (TOC, ENV, etc.).
   // updates and returns _last_calls_return_pc.
   address branch_to(Register function_descriptor, bool and_link, bool save_toc_before_call,
                     bool restore_toc_after_call, bool load_toc_of_callee, bool load_env_of_callee);
+#endif
 
  public:
 
   // Get the pc where the last call will return to. returns _last_calls_return_pc.
   inline address last_calls_return_pc();
 
+#if defined(ABI_ELFv2)
+  // Call a C function via a function descriptor and use full C
+  // calling conventions. Updates and returns _last_calls_return_pc.
+  address call_c(Register function_entry);
+  // For tail calls: only branch, don't link, so callee returns to caller of this function.
+  address call_c_and_return_to_caller(Register function_entry);
+  address call_c(address function_entry, relocInfo::relocType rt);
+#else
   // Call a C function via a function descriptor and use full C
   // calling conventions. Updates and returns _last_calls_return_pc.
   address call_c(Register function_descriptor);
@@ -315,6 +329,7 @@
   address call_c(const FunctionDescriptor* function_descriptor, relocInfo::relocType rt);
   address call_c_using_toc(const FunctionDescriptor* function_descriptor, relocInfo::relocType rt,
                            Register toc);
+#endif
 
  protected:
 
@@ -551,12 +566,14 @@
 
   // Load heap oop and decompress. Loaded oop may not be null.
   inline void load_heap_oop_not_null(Register d, RegisterOrConstant offs, Register s1 = noreg);
+  inline void store_heap_oop_not_null(Register d, RegisterOrConstant offs, Register s1,
+                                      /*specify if d must stay uncompressed*/ Register tmp = noreg);
 
   // Null allowed.
   inline void load_heap_oop(Register d, RegisterOrConstant offs, Register s1 = noreg);
 
   // Encode/decode heap oop. Oop may not be null, else en/decoding goes wrong.
-  inline void encode_heap_oop_not_null(Register d);
+  inline Register encode_heap_oop_not_null(Register d, Register src = noreg);
   inline void decode_heap_oop_not_null(Register d);
 
   // Null allowed.
@@ -566,6 +583,7 @@
   void load_klass(Register dst, Register src);
   void load_klass_with_trap_null_check(Register dst, Register src);
   void store_klass(Register dst_oop, Register klass, Register tmp = R0);
+  void store_klass_gap(Register dst_oop, Register val = noreg); // Will store 0 if val not specified.
   static int instr_size_for_decode_klass_not_null();
   void decode_klass_not_null(Register dst, Register src = noreg);
   void encode_klass_not_null(Register dst, Register src = noreg);
@@ -649,6 +667,11 @@
   void _verify_method_ptr(Register reg, const char * msg, const char * file, int line) {}
   void _verify_klass_ptr(Register reg, const char * msg, const char * file, int line) {}
 
+  // Convenience method returning function entry. For the ELFv1 case
+  // creates function descriptor at the current address and returs
+  // the pointer to it. For the ELFv2 case returns the current address.
+  inline address function_entry();
+
 #define verify_method_ptr(reg) _verify_method_ptr(reg, "broken method " #reg, __FILE__, __LINE__)
 #define verify_klass_ptr(reg) _verify_klass_ptr(reg, "broken klass " #reg, __FILE__, __LINE__)
 
@@ -673,4 +696,21 @@
   void zap_from_to(Register low, int before, Register high, int after, Register val, Register addr) PRODUCT_RETURN;
 };
 
+// class SkipIfEqualZero:
+//
+// Instantiating this class will result in assembly code being output that will
+// jump around any code emitted between the creation of the instance and it's
+// automatic destruction at the end of a scope block, depending on the value of
+// the flag passed to the constructor, which will be checked at run-time.
+class SkipIfEqualZero : public StackObj {
+ private:
+  MacroAssembler* _masm;
+  Label _label;
+
+ public:
+   // 'Temp' is a temp register that this object can use (and trash).
+   explicit SkipIfEqualZero(MacroAssembler*, Register temp, const bool* flag_addr);
+   ~SkipIfEqualZero();
+};
+
 #endif // CPU_PPC_VM_MACROASSEMBLER_PPC_HPP
--- a/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.inline.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/macroAssembler_ppc.inline.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright 2012, 2014 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
@@ -321,6 +321,15 @@
   }
 }
 
+inline void MacroAssembler::store_heap_oop_not_null(Register d, RegisterOrConstant offs, Register s1, Register tmp) {
+  if (UseCompressedOops) {
+    Register compressedOop = encode_heap_oop_not_null((tmp != noreg) ? tmp : d, d);
+    stw(compressedOop, offs, s1);
+  } else {
+    std(d, offs, s1);
+  }
+}
+
 inline void MacroAssembler::load_heap_oop(Register d, RegisterOrConstant offs, Register s1) {
   if (UseCompressedOops) {
     lwz(d, offs, s1);
@@ -330,13 +339,17 @@
   }
 }
 
-inline void MacroAssembler::encode_heap_oop_not_null(Register d) {
+inline Register MacroAssembler::encode_heap_oop_not_null(Register d, Register src) {
+  Register current = (src!=noreg) ? src : d; // Compressed oop is in d if no src provided.
   if (Universe::narrow_oop_base() != NULL) {
-    sub(d, d, R30);
+    sub(d, current, R30);
+    current = d;
   }
   if (Universe::narrow_oop_shift() != 0) {
-    srdi(d, d, LogMinObjAlignmentInBytes);
+    srdi(d, current, LogMinObjAlignmentInBytes);
+    current = d;
   }
+  return current; // Encoded oop is in this register.
 }
 
 inline void MacroAssembler::decode_heap_oop_not_null(Register d) {
@@ -385,4 +398,10 @@
   twi(traptoEqual | traptoGreaterThanUnsigned, a/*reg a*/, si16);
 }
 
+#if defined(ABI_ELFv2)
+inline address MacroAssembler::function_entry() { return pc(); }
+#else
+inline address MacroAssembler::function_entry() { return emit_fd(); }
+#endif
+
 #endif // CPU_PPC_VM_MACROASSEMBLER_PPC_INLINE_HPP
--- a/hotspot/src/cpu/ppc/vm/methodHandles_ppc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/methodHandles_ppc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -453,11 +453,11 @@
 
   if (Verbose) {
     tty->print_cr("Registers:");
-    const int abi_offset = frame::abi_112_size / 8;
+    const int abi_offset = frame::abi_reg_args_size / 8;
     for (int i = R3->encoding(); i <= R12->encoding(); i++) {
       Register r = as_Register(i);
       int count = i - R3->encoding();
-      // The registers are stored in reverse order on the stack (by save_volatile_gprs(R1_SP, abi_112_size)).
+      // The registers are stored in reverse order on the stack (by save_volatile_gprs(R1_SP, abi_reg_args_size)).
       tty->print("%3s=" PTR_FORMAT, r->name(), saved_regs[abi_offset + count]);
       if ((count + 1) % 4 == 0) {
         tty->cr();
@@ -524,9 +524,9 @@
   __ save_LR_CR(R0);
   __ mr(R0, R1_SP);                     // saved_sp
   assert(Assembler::is_simm(-nbytes_save, 16), "Overwriting R0");
-  // push_frame_abi112 only uses R0 if nbytes_save is wider than 16 bit
-  __ push_frame_abi112(nbytes_save, R0);
-  __ save_volatile_gprs(R1_SP, frame::abi_112_size); // Except R0.
+  // Push_frame_reg_args only uses R0 if nbytes_save is wider than 16 bit.
+  __ push_frame_reg_args(nbytes_save, R0);
+  __ save_volatile_gprs(R1_SP, frame::abi_reg_args_size); // Except R0.
 
   __ load_const(R3_ARG1, (address)adaptername);
   __ mr(R4_ARG2, R23_method_handle);
--- a/hotspot/src/cpu/ppc/vm/ppc.ad	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/ppc.ad	Wed Jul 05 19:33:51 2017 +0200
@@ -1008,7 +1008,11 @@
 }
 
 int MachCallRuntimeNode::ret_addr_offset() {
+#if defined(ABI_ELFv2)
+  return 28;
+#else
   return 40;
+#endif
 }
 
 //=============================================================================
@@ -3674,6 +3678,10 @@
     MacroAssembler _masm(&cbuf);
     const address start_pc = __ pc();
 
+#if defined(ABI_ELFv2)
+    address entry= !($meth$$method) ? NULL : (address)$meth$$method;
+    __ call_c(entry, relocInfo::runtime_call_type);
+#else
     // The function we're going to call.
     FunctionDescriptor fdtemp;
     const FunctionDescriptor* fd = !($meth$$method) ? &fdtemp : (FunctionDescriptor*)$meth$$method;
@@ -3684,6 +3692,7 @@
     // Put entry, env, toc into the constant pool, this needs up to 3 constant
     // pool entries; call_c_using_toc will optimize the call.
     __ call_c_using_toc(fd, relocInfo::runtime_call_type, Rtoc);
+#endif
 
     // Check the ret_addr_offset.
     assert(((MachCallRuntimeNode*)this)->ret_addr_offset() ==  __ last_calls_return_pc() - start_pc,
@@ -3699,20 +3708,25 @@
     __ mtctr($src$$Register);
   %}
 
-  // postalloc expand emitter for runtime leaf calls.
+  // Postalloc expand emitter for runtime leaf calls.
   enc_class postalloc_expand_java_to_runtime_call(method meth, iRegLdst toc) %{
+    loadConLNodesTuple loadConLNodes_Entry;
+#if defined(ABI_ELFv2)
+    jlong entry_address = (jlong) this->entry_point();
+    assert(entry_address, "need address here");
+    loadConLNodes_Entry = loadConLNodesTuple_create(C, ra_, n_toc, new (C) immLOper(entry_address),
+                                                    OptoReg::Name(R12_H_num), OptoReg::Name(R12_num));
+#else
     // Get the struct that describes the function we are about to call.
     FunctionDescriptor* fd = (FunctionDescriptor*) this->entry_point();
     assert(fd, "need fd here");
+    jlong entry_address = (jlong) fd->entry();
     // new nodes
-    loadConLNodesTuple loadConLNodes_Entry;
     loadConLNodesTuple loadConLNodes_Env;
     loadConLNodesTuple loadConLNodes_Toc;
-    MachNode         *mtctr = NULL;
-    MachCallLeafNode *call  = NULL;
 
     // Create nodes and operands for loading the entry point.
-    loadConLNodes_Entry = loadConLNodesTuple_create(C, ra_, n_toc, new (C) immLOper((jlong) fd->entry()),
+    loadConLNodes_Entry = loadConLNodesTuple_create(C, ra_, n_toc, new (C) immLOper(entry_address),
                                                     OptoReg::Name(R12_H_num), OptoReg::Name(R12_num));
 
 
@@ -3733,8 +3747,9 @@
     // Create nodes and operands for loading the Toc point.
     loadConLNodes_Toc = loadConLNodesTuple_create(C, ra_, n_toc, new (C) immLOper((jlong) fd->toc()),
                                                   OptoReg::Name(R2_H_num), OptoReg::Name(R2_num));
+#endif // ABI_ELFv2
     // mtctr node
-    mtctr = new (C) CallLeafDirect_mtctrNode();
+    MachNode *mtctr = new (C) CallLeafDirect_mtctrNode();
 
     assert(loadConLNodes_Entry._last != NULL, "entry must exist");
     mtctr->add_req(0, loadConLNodes_Entry._last);
@@ -3743,10 +3758,10 @@
     mtctr->_opnds[1] = new (C) iRegLdstOper();
 
     // call node
-    call = new (C) CallLeafDirectNode();
+    MachCallLeafNode *call = new (C) CallLeafDirectNode();
 
     call->_opnds[0] = _opnds[0];
-    call->_opnds[1] = new (C) methodOper((intptr_t) fd->entry()); // may get set later
+    call->_opnds[1] = new (C) methodOper((intptr_t) entry_address); // May get set later.
 
     // Make the new call node look like the old one.
     call->_name        = _name;
@@ -3773,8 +3788,10 @@
     // These must be reqired edges, as the registers are live up to
     // the call. Else the constants are handled as kills.
     call->add_req(mtctr);
+#if !defined(ABI_ELFv2)
     call->add_req(loadConLNodes_Env._last);
     call->add_req(loadConLNodes_Toc._last);
+#endif
 
     // ...as well as prec
     for (uint i = req(); i < len(); ++i) {
@@ -3787,10 +3804,12 @@
     // Insert the new nodes.
     if (loadConLNodes_Entry._large_hi) nodes->push(loadConLNodes_Entry._large_hi);
     if (loadConLNodes_Entry._last)     nodes->push(loadConLNodes_Entry._last);
+#if !defined(ABI_ELFv2)
     if (loadConLNodes_Env._large_hi)   nodes->push(loadConLNodes_Env._large_hi);
     if (loadConLNodes_Env._last)       nodes->push(loadConLNodes_Env._last);
     if (loadConLNodes_Toc._large_hi)   nodes->push(loadConLNodes_Toc._large_hi);
     if (loadConLNodes_Toc._last)       nodes->push(loadConLNodes_Toc._last);
+#endif
     nodes->push(mtctr);
     nodes->push(call);
   %}
@@ -3837,7 +3856,7 @@
   // out_preserve_stack_slots for calls to C. Supports the var-args
   // backing area for register parms.
   //
-  varargs_C_out_slots_killed(((frame::abi_112_size - frame::jit_out_preserve_size) / VMRegImpl::stack_slot_size));
+  varargs_C_out_slots_killed(((frame::abi_reg_args_size - frame::jit_out_preserve_size) / VMRegImpl::stack_slot_size));
 
   // The after-PROLOG location of the return address. Location of
   // return address specifies a type (REG or STACK) and a number
--- a/hotspot/src/cpu/ppc/vm/register_ppc.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/register_ppc.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright 2012, 2014 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
@@ -579,15 +579,27 @@
 
 // Register declarations to be used in frame manager assembly code.
 // Use only non-volatile registers in order to keep values across C-calls.
+#ifdef CC_INTERP
 REGISTER_DECLARATION(Register, R14_state,      R14);      // address of new cInterpreter.
 REGISTER_DECLARATION(Register, R15_prev_state, R15);      // address of old cInterpreter
+#else // CC_INTERP
+REGISTER_DECLARATION(Register, R14_bcp,        R14);
+REGISTER_DECLARATION(Register, R15_esp,        R15);
+REGISTER_DECLARATION(FloatRegister, F15_ftos,  F15);
+#endif // CC_INTERP
 REGISTER_DECLARATION(Register, R16_thread,     R16);      // address of current thread
 REGISTER_DECLARATION(Register, R17_tos,        R17);      // address of Java tos (prepushed).
 REGISTER_DECLARATION(Register, R18_locals,     R18);      // address of first param slot (receiver).
 REGISTER_DECLARATION(Register, R19_method,     R19);      // address of current method
 #ifndef DONT_USE_REGISTER_DEFINES
+#ifdef CC_INTERP
 #define R14_state         AS_REGISTER(Register, R14)
 #define R15_prev_state    AS_REGISTER(Register, R15)
+#else // CC_INTERP
+#define R14_bcp           AS_REGISTER(Register, R14)
+#define R15_esp           AS_REGISTER(Register, R15)
+#define F15_ftos          AS_REGISTER(FloatRegister, F15)
+#endif // CC_INTERP
 #define R16_thread        AS_REGISTER(Register, R16)
 #define R17_tos           AS_REGISTER(Register, R17)
 #define R18_locals        AS_REGISTER(Register, R18)
@@ -608,6 +620,14 @@
 REGISTER_DECLARATION(Register, R27_tmp7, R27);
 REGISTER_DECLARATION(Register, R28_tmp8, R28);
 REGISTER_DECLARATION(Register, R29_tmp9, R29);
+#ifndef CC_INTERP
+REGISTER_DECLARATION(Register, R24_dispatch_addr,     R24);
+REGISTER_DECLARATION(Register, R25_templateTableBase, R25);
+REGISTER_DECLARATION(Register, R26_monitor,           R26);
+REGISTER_DECLARATION(Register, R27_constPoolCache,    R27);
+REGISTER_DECLARATION(Register, R28_mdx,               R28);
+#endif // CC_INTERP
+
 #ifndef DONT_USE_REGISTER_DEFINES
 #define R21_tmp1         AS_REGISTER(Register, R21)
 #define R22_tmp2         AS_REGISTER(Register, R22)
@@ -618,6 +638,16 @@
 #define R27_tmp7         AS_REGISTER(Register, R27)
 #define R28_tmp8         AS_REGISTER(Register, R28)
 #define R29_tmp9         AS_REGISTER(Register, R29)
+#ifndef CC_INTERP
+//    Lmonitors  : monitor pointer
+//    LcpoolCache: constant pool cache
+//    mdx: method data index
+#define R24_dispatch_addr     AS_REGISTER(Register, R24)
+#define R25_templateTableBase AS_REGISTER(Register, R25)
+#define R26_monitor           AS_REGISTER(Register, R26)
+#define R27_constPoolCache    AS_REGISTER(Register, R27)
+#define R28_mdx               AS_REGISTER(Register, R28)
+#endif
 
 #define CCR4_is_synced AS_REGISTER(ConditionRegister, CCR4)
 #endif
--- a/hotspot/src/cpu/ppc/vm/runtime_ppc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/runtime_ppc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -87,7 +87,7 @@
 
   address start = __ pc();
 
-  int frame_size_in_bytes = frame::abi_112_size;
+  int frame_size_in_bytes = frame::abi_reg_args_size;
   OopMap* map = new OopMap(frame_size_in_bytes / sizeof(jint), 0);
 
   // Exception pc is 'return address' for stack walker.
@@ -99,7 +99,7 @@
 
   // Save callee-saved registers.
   // Push a C frame for the exception blob. It is needed for the C call later on.
-  __ push_frame_abi112(0, R11_scratch1);
+  __ push_frame_reg_args(0, R11_scratch1);
 
   // This call does all the hard work. It checks if an exception handler
   // exists in the method.
@@ -109,8 +109,12 @@
   __ set_last_Java_frame(/*sp=*/R1_SP, noreg);
 
   __ mr(R3_ARG1, R16_thread);
+#if defined(ABI_ELFv2)
+  __ call_c((address) OptoRuntime::handle_exception_C, relocInfo::none);
+#else
   __ call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, OptoRuntime::handle_exception_C),
             relocInfo::none);
+#endif
   address calls_return_pc = __ last_calls_return_pc();
 # ifdef ASSERT
   __ cmpdi(CCR0, R3_RET, 0);
@@ -162,7 +166,11 @@
   __ bind(mh_callsite);
   __ mr(R31, R3_RET); // Save branch address.
   __ mr(R3_ARG1, R16_thread);
+#if defined(ABI_ELFv2)
+  __ call_c((address) adjust_SP_for_methodhandle_callsite, relocInfo::none);
+#else
   __ call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, adjust_SP_for_methodhandle_callsite), relocInfo::none);
+#endif
   // Returns unextended_sp in R3_RET.
 
   __ mtctr(R31); // Move address of exception handler to SR_CTR.
--- a/hotspot/src/cpu/ppc/vm/sharedRuntime_ppc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/sharedRuntime_ppc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright 2012, 2014 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
@@ -67,7 +67,7 @@
     return_pc_is_thread_saved_exception_pc
   };
 
-  static OopMap* push_frame_abi112_and_save_live_registers(MacroAssembler* masm,
+  static OopMap* push_frame_reg_args_and_save_live_registers(MacroAssembler* masm,
                          int* out_frame_size_in_bytes,
                          bool generate_oop_map,
                          int return_pc_adjustment,
@@ -200,12 +200,12 @@
   RegisterSaver_LiveIntReg(   R30 ), // r30 must be the last register
 };
 
-OopMap* RegisterSaver::push_frame_abi112_and_save_live_registers(MacroAssembler* masm,
+OopMap* RegisterSaver::push_frame_reg_args_and_save_live_registers(MacroAssembler* masm,
                          int* out_frame_size_in_bytes,
                          bool generate_oop_map,
                          int return_pc_adjustment,
                          ReturnPCLocation return_pc_location) {
-  // Push an abi112-frame and store all registers which may be live.
+  // Push an abi_reg_args-frame and store all registers which may be live.
   // If requested, create an OopMap: Record volatile registers as
   // callee-save values in an OopMap so their save locations will be
   // propagated to the RegisterMap of the caller frame during
@@ -221,7 +221,7 @@
                                    sizeof(RegisterSaver::LiveRegType);
   const int register_save_size   = regstosave_num * reg_size;
   const int frame_size_in_bytes  = round_to(register_save_size, frame::alignment_in_bytes)
-                                   + frame::abi_112_size;
+                                   + frame::abi_reg_args_size;
   *out_frame_size_in_bytes       = frame_size_in_bytes;
   const int frame_size_in_slots  = frame_size_in_bytes / sizeof(jint);
   const int register_save_offset = frame_size_in_bytes - register_save_size;
@@ -229,7 +229,7 @@
   // OopMap frame size is in c2 stack slots (sizeof(jint)) not bytes or words.
   OopMap* map = generate_oop_map ? new OopMap(frame_size_in_slots, 0) : NULL;
 
-  BLOCK_COMMENT("push_frame_abi112_and_save_live_registers {");
+  BLOCK_COMMENT("push_frame_reg_args_and_save_live_registers {");
 
   // Save r30 in the last slot of the not yet pushed frame so that we
   // can use it as scratch reg.
@@ -294,7 +294,7 @@
     offset += reg_size;
   }
 
-  BLOCK_COMMENT("} push_frame_abi112_and_save_live_registers");
+  BLOCK_COMMENT("} push_frame_reg_args_and_save_live_registers");
 
   // And we're done.
   return map;
@@ -699,15 +699,19 @@
 
   int i;
   VMReg reg;
-  // Leave room for C-compatible ABI_112.
-  int stk = (frame::abi_112_size - frame::jit_out_preserve_size) / VMRegImpl::stack_slot_size;
+  // Leave room for C-compatible ABI_REG_ARGS.
+  int stk = (frame::abi_reg_args_size - frame::jit_out_preserve_size) / VMRegImpl::stack_slot_size;
   int arg = 0;
   int freg = 0;
 
   // Avoid passing C arguments in the wrong stack slots.
+#if defined(ABI_ELFv2)
+  assert((SharedRuntime::out_preserve_stack_slots() + stk) * VMRegImpl::stack_slot_size == 96,
+         "passing C arguments in wrong stack slots");
+#else
   assert((SharedRuntime::out_preserve_stack_slots() + stk) * VMRegImpl::stack_slot_size == 112,
          "passing C arguments in wrong stack slots");
-
+#endif
   // We fill-out regs AND regs2 if an argument must be passed in a
   // register AND in a stack slot. If regs2 is NULL in such a
   // situation, we bail-out with a fatal error.
@@ -953,6 +957,9 @@
 
 #ifdef CC_INTERP
   const Register tos = R17_tos;
+#else
+  const Register tos = R15_esp;
+  __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
 #endif
 
   // load TOS
@@ -971,7 +978,7 @@
                             const BasicType *sig_bt,
                             const VMRegPair *regs) {
 
-  // Load method's entry-point from methodOop.
+  // Load method's entry-point from method.
   __ ld(R12_scratch2, in_bytes(Method::from_compiled_offset()), R19_method);
   __ mtctr(R12_scratch2);
 
@@ -992,7 +999,10 @@
 
 #ifdef CC_INTERP
   const Register ld_ptr = R17_tos;
+#else
+  const Register ld_ptr = R15_esp;
 #endif
+
   const Register value_regs[] = { R22_tmp2, R23_tmp3, R24_tmp4, R25_tmp5, R26_tmp6 };
   const int num_value_regs = sizeof(value_regs) / sizeof(Register);
   int value_regs_index = 0;
@@ -1083,8 +1093,8 @@
     }
   }
 
-  BLOCK_COMMENT("Store method oop");
-  // Store method oop into thread->callee_target.
+  BLOCK_COMMENT("Store method");
+  // Store method into thread->callee_target.
   // We might end up in handle_wrong_method if the callee is
   // deoptimized as we race thru here. If that happens we don't want
   // to take a safepoint because the caller frame will look
@@ -1504,7 +1514,11 @@
 
   __ block_comment("block_for_jni_critical");
   address entry_point = CAST_FROM_FN_PTR(address, SharedRuntime::block_for_jni_critical);
+#if defined(ABI_ELFv2)
+  __ call_c(entry_point, relocInfo::runtime_call_type);
+#else
   __ call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, entry_point), relocInfo::runtime_call_type);
+#endif
   address start           = __ pc() - __ offset(),
           calls_return_pc = __ last_calls_return_pc();
   oop_maps->add_gc_map(calls_return_pc - start, map);
@@ -1877,7 +1891,7 @@
   // Layout of the native wrapper frame:
   // (stack grows upwards, memory grows downwards)
   //
-  // NW     [ABI_112]                  <-- 1) R1_SP
+  // NW     [ABI_REG_ARGS]             <-- 1) R1_SP
   //        [outgoing arguments]       <-- 2) R1_SP + out_arg_slot_offset
   //        [oopHandle area]           <-- 3) R1_SP + oop_handle_offset (save area for critical natives)
   //        klass                      <-- 4) R1_SP + klass_offset
@@ -2211,8 +2225,8 @@
     // slow case of monitor enter. Inline a special case of call_VM that
     // disallows any pending_exception.
 
-    // Save argument registers and leave room for C-compatible ABI_112.
-    int frame_size = frame::abi_112_size +
+    // Save argument registers and leave room for C-compatible ABI_REG_ARGS.
+    int frame_size = frame::abi_reg_args_size +
                      round_to(total_c_args * wordSize, frame::alignment_in_bytes);
     __ mr(R11_scratch1, R1_SP);
     RegisterSaver::push_frame_and_save_argument_registers(masm, R12_scratch2, frame_size, total_c_args, out_regs, out_regs2);
@@ -2250,9 +2264,12 @@
 
   // The JNI call
   // --------------------------------------------------------------------------
-
+#if defined(ABI_ELFv2)
+  __ call_c(native_func, relocInfo::runtime_call_type);
+#else
   FunctionDescriptor* fd_native_method = (FunctionDescriptor*) native_func;
   __ call_c(fd_native_method, relocInfo::runtime_call_type);
+#endif
 
 
   // Now, we are back from the native code.
@@ -2606,8 +2623,12 @@
 #ifdef CC_INTERP
   __ std(R1_SP, _parent_ijava_frame_abi(initial_caller_sp), R1_SP);
 #else
-  Unimplemented();
+#ifdef ASSERT
+  __ load_const_optimized(pc_reg, 0x5afe);
+  __ std(pc_reg, _ijava_state_neg(ijava_reserved), R1_SP);
 #endif
+  __ std(R1_SP, _ijava_state_neg(sender_sp), R1_SP);
+#endif // CC_INTERP
   __ addi(number_of_frames_reg, number_of_frames_reg, -1);
   __ addi(frame_sizes_reg, frame_sizes_reg, wordSize);
   __ addi(pcs_reg, pcs_reg, wordSize);
@@ -2679,7 +2700,15 @@
   __ std(R12_scratch2, _abi(lr), R1_SP);
 
   // Initialize initial_caller_sp.
+#ifdef CC_INTERP
   __ std(frame_size_reg/*old_sp*/, _parent_ijava_frame_abi(initial_caller_sp), R1_SP);
+#else
+#ifdef ASSERT
+ __ load_const_optimized(pc_reg, 0x5afe);
+ __ std(pc_reg, _ijava_state_neg(ijava_reserved), R1_SP);
+#endif
+ __ std(frame_size_reg, _ijava_state_neg(sender_sp), R1_SP);
+#endif // CC_INTERP
 
 #ifdef ASSERT
   // Make sure that there is at least one entry in the array.
@@ -2724,7 +2753,7 @@
   OopMapSet *oop_maps = new OopMapSet();
 
   // size of ABI112 plus spill slots for R3_RET and F1_RET.
-  const int frame_size_in_bytes = frame::abi_112_spill_size;
+  const int frame_size_in_bytes = frame::abi_reg_args_spill_size;
   const int frame_size_in_slots = frame_size_in_bytes / sizeof(jint);
   int first_frame_size_in_bytes = 0; // frame size of "unpack frame" for call to fetch_unroll_info.
 
@@ -2757,11 +2786,11 @@
 
   // Push the "unpack frame"
   // Save everything in sight.
-  map = RegisterSaver::push_frame_abi112_and_save_live_registers(masm,
-                                                                 &first_frame_size_in_bytes,
-                                                                 /*generate_oop_map=*/ true,
-                                                                 return_pc_adjustment_no_exception,
-                                                                 RegisterSaver::return_pc_is_lr);
+  map = RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
+                                                                   &first_frame_size_in_bytes,
+                                                                   /*generate_oop_map=*/ true,
+                                                                   return_pc_adjustment_no_exception,
+                                                                   RegisterSaver::return_pc_is_lr);
   assert(map != NULL, "OopMap must have been created");
 
   __ li(exec_mode_reg, Deoptimization::Unpack_deopt);
@@ -2787,11 +2816,11 @@
   // Push the "unpack frame".
   // Save everything in sight.
   assert(R4 == R4_ARG2, "exception pc must be in r4");
-  RegisterSaver::push_frame_abi112_and_save_live_registers(masm,
-                                                           &first_frame_size_in_bytes,
-                                                           /*generate_oop_map=*/ false,
-                                                           return_pc_adjustment_exception,
-                                                           RegisterSaver::return_pc_is_r4);
+  RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
+                                                             &first_frame_size_in_bytes,
+                                                             /*generate_oop_map=*/ false,
+                                                             return_pc_adjustment_exception,
+                                                             RegisterSaver::return_pc_is_r4);
 
   // Deopt during an exception. Save exec mode for unpack_frames.
   __ li(exec_mode_reg, Deoptimization::Unpack_exception);
@@ -2876,8 +2905,8 @@
   // ...).
 
   // Spill live volatile registers since we'll do a call.
-  __ std( R3_RET,  _abi_112_spill(spill_ret),  R1_SP);
-  __ stfd(F1_RET, _abi_112_spill(spill_fret), R1_SP);
+  __ std( R3_RET, _abi_reg_args_spill(spill_ret),  R1_SP);
+  __ stfd(F1_RET, _abi_reg_args_spill(spill_fret), R1_SP);
 
   // Let the unpacker layout information in the skeletal frames just
   // allocated.
@@ -2889,8 +2918,8 @@
   __ reset_last_Java_frame();
 
   // Restore the volatiles saved above.
-  __ ld( R3_RET, _abi_112_spill(spill_ret),  R1_SP);
-  __ lfd(F1_RET, _abi_112_spill(spill_fret), R1_SP);
+  __ ld( R3_RET, _abi_reg_args_spill(spill_ret),  R1_SP);
+  __ lfd(F1_RET, _abi_reg_args_spill(spill_fret), R1_SP);
 
   // Pop the unpack frame.
   __ pop_frame();
@@ -2900,10 +2929,16 @@
   // optional c2i, caller of deoptee, ...).
 
   // Initialize R14_state.
+#ifdef CC_INTERP
   __ ld(R14_state, 0, R1_SP);
   __ addi(R14_state, R14_state, -frame::interpreter_frame_cinterpreterstate_size_in_bytes());
   // Also inititialize R15_prev_state.
   __ restore_prev_state();
+#else
+  __ restore_interpreter_state(R11_scratch1);
+  __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
+#endif // CC_INTERP
+
 
   // Return to the interpreter entry point.
   __ blr();
@@ -2930,7 +2965,7 @@
   Register unc_trap_reg     = R23_tmp3;
 
   OopMapSet* oop_maps = new OopMapSet();
-  int frame_size_in_bytes = frame::abi_112_size;
+  int frame_size_in_bytes = frame::abi_reg_args_size;
   OopMap* map = new OopMap(frame_size_in_bytes / sizeof(jint), 0);
 
   // stack: (deoptee, optional i2c, caller_of_deoptee, ...).
@@ -2943,7 +2978,7 @@
   __ save_LR_CR(R11_scratch1);
 
   // Push an "uncommon_trap" frame.
-  __ push_frame_abi112(0, R11_scratch1);
+  __ push_frame_reg_args(0, R11_scratch1);
 
   // stack: (unpack frame, deoptee, optional i2c, caller_of_deoptee, ...).
 
@@ -2996,7 +3031,7 @@
   // interpreter frames just created.
 
   // Push a simple "unpack frame" here.
-  __ push_frame_abi112(0, R11_scratch1);
+  __ push_frame_reg_args(0, R11_scratch1);
 
   // stack: (unpack frame, skeletal interpreter frame, ..., optional
   // skeletal interpreter frame, optional c2i, caller of deoptee,
@@ -3022,11 +3057,17 @@
   // stack: (top interpreter frame, ..., optional interpreter frame,
   // optional c2i, caller of deoptee, ...).
 
+#ifdef CC_INTERP
   // Initialize R14_state, ...
   __ ld(R11_scratch1, 0, R1_SP);
   __ addi(R14_state, R11_scratch1, -frame::interpreter_frame_cinterpreterstate_size_in_bytes());
   // also initialize R15_prev_state.
   __ restore_prev_state();
+#else
+  __ restore_interpreter_state(R11_scratch1);
+  __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
+#endif // CC_INTERP
+
   // Return to the interpreter entry point.
   __ blr();
 
@@ -3064,11 +3105,11 @@
   }
 
   // Save registers, fpu state, and flags.
-  map = RegisterSaver::push_frame_abi112_and_save_live_registers(masm,
-                                                                 &frame_size_in_bytes,
-                                                                 /*generate_oop_map=*/ true,
-                                                                 /*return_pc_adjustment=*/0,
-                                                                 return_pc_location);
+  map = RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
+                                                                   &frame_size_in_bytes,
+                                                                   /*generate_oop_map=*/ true,
+                                                                   /*return_pc_adjustment=*/0,
+                                                                   return_pc_location);
 
   // The following is basically a call_VM. However, we need the precise
   // address of the call in order to generate an oopmap. Hence, we do all the
@@ -3104,7 +3145,6 @@
                                                       frame_size_in_bytes,
                                                       /*restore_ctr=*/true);
 
-
   BLOCK_COMMENT("  Jump to forward_exception_entry.");
   // Jump to forward_exception_entry, with the issuing PC in LR
   // so it looks like the original nmethod called forward_exception_entry.
@@ -3151,11 +3191,11 @@
 
   address start = __ pc();
 
-  map = RegisterSaver::push_frame_abi112_and_save_live_registers(masm,
-                                                                 &frame_size_in_bytes,
-                                                                 /*generate_oop_map*/ true,
-                                                                 /*return_pc_adjustment*/ 0,
-                                                                 RegisterSaver::return_pc_is_lr);
+  map = RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
+                                                                   &frame_size_in_bytes,
+                                                                   /*generate_oop_map*/ true,
+                                                                   /*return_pc_adjustment*/ 0,
+                                                                   RegisterSaver::return_pc_is_lr);
 
   // Use noreg as last_Java_pc, the return pc will be reconstructed
   // from the physical frame.
@@ -3189,7 +3229,7 @@
 
   RegisterSaver::restore_live_registers_and_pop_frame(masm, frame_size_in_bytes, /*restore_ctr*/ false);
 
-  // Get the returned methodOop.
+  // Get the returned method.
   __ get_vm_result_2(R19_method);
 
   __ bctr();
--- a/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,6 +1,6 @@
 /*
  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2012, 2013 SAP AG. All rights reserved.
+ * Copyright 2012, 2014 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
@@ -39,15 +39,10 @@
 #include "runtime/stubCodeGenerator.hpp"
 #include "runtime/stubRoutines.hpp"
 #include "utilities/top.hpp"
-#ifdef TARGET_OS_FAMILY_aix
-# include "thread_aix.inline.hpp"
-#endif
-#ifdef TARGET_OS_FAMILY_linux
-# include "thread_linux.inline.hpp"
-#endif
 #ifdef COMPILER2
 #include "opto/runtime.hpp"
 #endif
+#include "runtime/thread.inline.hpp"
 
 #define __ _masm->
 
@@ -79,11 +74,11 @@
 
     StubCodeMark mark(this, "StubRoutines", "call_stub");
 
-    address start = __ emit_fd();
+    address start = __ function_entry();
 
     // some sanity checks
-    assert((sizeof(frame::abi_48) % 16) == 0,                 "unaligned");
-    assert((sizeof(frame::abi_112) % 16) == 0,                "unaligned");
+    assert((sizeof(frame::abi_minframe) % 16) == 0,           "unaligned");
+    assert((sizeof(frame::abi_reg_args) % 16) == 0,           "unaligned");
     assert((sizeof(frame::spill_nonvolatiles) % 16) == 0,     "unaligned");
     assert((sizeof(frame::parent_ijava_frame_abi) % 16) == 0, "unaligned");
     assert((sizeof(frame::entry_frame_locals) % 16) == 0,     "unaligned");
@@ -221,7 +216,7 @@
     {
       BLOCK_COMMENT("Call frame manager or native entry.");
       // Call frame manager or native entry.
-      Register r_new_arg_entry = R14_state;
+      Register r_new_arg_entry = R14; // PPC_state;
       assert_different_registers(r_new_arg_entry, r_top_of_arguments_addr,
                                  r_arg_method, r_arg_thread);
 
@@ -234,7 +229,11 @@
       //   R16_thread  -  JavaThread*
 
       // Tos must point to last argument - element_size.
+#ifdef CC_INTERP
       const Register tos = R17_tos;
+#else
+      const Register tos = R15_esp;
+#endif
       __ addi(tos, r_top_of_arguments_addr, -Interpreter::stackElementSize);
 
       // initialize call_stub locals (step 2)
@@ -248,8 +247,11 @@
       assert(tos != r_arg_thread && R19_method != r_arg_thread, "trashed r_arg_thread");
 
       // Set R15_prev_state to 0 for simplifying checks in callee.
+#ifdef CC_INTERP
       __ li(R15_prev_state, 0);
-
+#else
+      __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
+#endif
       // Stack on entry to frame manager / native entry:
       //
       //      F0      [TOP_IJAVA_FRAME_ABI]
@@ -444,7 +446,7 @@
 
     // Save LR/CR and copy exception pc (LR) into R4_ARG2.
     __ save_LR_CR(R4_ARG2);
-    __ push_frame_abi112(0, R0);
+    __ push_frame_reg_args(0, R0);
     // Find exception handler.
     __ call_VM_leaf(CAST_FROM_FN_PTR(address,
                      SharedRuntime::exception_handler_for_return_address),
@@ -519,7 +521,7 @@
     MacroAssembler* masm = new MacroAssembler(&code);
 
     OopMapSet* oop_maps  = new OopMapSet();
-    int frame_size_in_bytes = frame::abi_112_size;
+    int frame_size_in_bytes = frame::abi_reg_args_size;
     OopMap* map = new OopMap(frame_size_in_bytes / sizeof(jint), 0);
 
     StubCodeMark mark(this, "StubRoutines", "throw_exception");
@@ -529,7 +531,7 @@
     __ save_LR_CR(R11_scratch1);
 
     // Push a frame.
-    __ push_frame_abi112(0, R11_scratch1);
+    __ push_frame_reg_args(0, R11_scratch1);
 
     address frame_complete_pc = __ pc();
 
@@ -551,8 +553,11 @@
     if (arg2 != noreg) {
       __ mr(R5_ARG3, arg2);
     }
-    __ call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, runtime_entry),
-              relocInfo::none);
+#if defined(ABI_ELFv2)
+    __ call_c(runtime_entry, relocInfo::none);
+#else
+    __ call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, runtime_entry), relocInfo::none);
+#endif
 
     // Set an oopmap for the call site.
     oop_maps->add_gc_map((int)(gc_map_pc - start), map);
@@ -614,7 +619,7 @@
         // With G1, don't generate the call if we statically know that the target in uninitialized
         if (!dest_uninitialized) {
           const int spill_slots = 4 * wordSize;
-          const int frame_size  = frame::abi_112_size + spill_slots;
+          const int frame_size  = frame::abi_reg_args_size + spill_slots;
           Label filtered;
 
           // Is marking active?
@@ -628,7 +633,7 @@
           __ beq(CCR0, filtered);
 
           __ save_LR_CR(R0);
-          __ push_frame_abi112(spill_slots, R0);
+          __ push_frame_reg_args(spill_slots, R0);
           __ std(from,  frame_size - 1 * wordSize, R1_SP);
           __ std(to,    frame_size - 2 * wordSize, R1_SP);
           __ std(count, frame_size - 3 * wordSize, R1_SP);
@@ -672,7 +677,7 @@
           if (branchToEnd) {
             __ save_LR_CR(R0);
             // We need this frame only to spill LR.
-            __ push_frame_abi112(0, R0);
+            __ push_frame_reg_args(0, R0);
             __ call_VM_leaf(CAST_FROM_FN_PTR(address, BarrierSet::static_write_ref_array_post), addr, count);
             __ pop_frame();
             __ restore_LR_CR(R0);
@@ -742,7 +747,7 @@
     StubCodeMark mark(this, "StubRoutines", "zero_words_aligned8");
 
     // Implemented as in ClearArray.
-    address start = __ emit_fd();
+    address start = __ function_entry();
 
     Register base_ptr_reg   = R3_ARG1; // tohw (needs to be 8b aligned)
     Register cnt_dwords_reg = R4_ARG2; // count (in dwords)
@@ -820,7 +825,7 @@
   //
   address generate_handler_for_unsafe_access() {
     StubCodeMark mark(this, "StubRoutines", "handler_for_unsafe_access");
-    address start = __ emit_fd();
+    address start = __ function_entry();
     __ unimplemented("StubRoutines::handler_for_unsafe_access", 93);
     return start;
   }
@@ -861,7 +866,7 @@
   // to read from the safepoint polling page.
   address generate_load_from_poll() {
     StubCodeMark mark(this, "StubRoutines", "generate_load_from_poll");
-    address start = __ emit_fd();
+    address start = __ function_entry();
     __ unimplemented("StubRoutines::verify_oop", 95);  // TODO PPC port
     return start;
   }
@@ -885,7 +890,7 @@
   //
   address generate_fill(BasicType t, bool aligned, const char* name) {
     StubCodeMark mark(this, "StubRoutines", name);
-    address start = __ emit_fd();
+    address start = __ function_entry();
 
     const Register to    = R3_ARG1;   // source array address
     const Register value = R4_ARG2;   // fill value
@@ -1123,7 +1128,7 @@
   //
   address generate_disjoint_byte_copy(bool aligned, const char * name) {
     StubCodeMark mark(this, "StubRoutines", name);
-    address start = __ emit_fd();
+    address start = __ function_entry();
 
     Register tmp1 = R6_ARG4;
     Register tmp2 = R7_ARG5;
@@ -1254,15 +1259,21 @@
   //
   address generate_conjoint_byte_copy(bool aligned, const char * name) {
     StubCodeMark mark(this, "StubRoutines", name);
-    address start = __ emit_fd();
+    address start = __ function_entry();
 
     Register tmp1 = R6_ARG4;
     Register tmp2 = R7_ARG5;
     Register tmp3 = R8_ARG6;
 
+#if defined(ABI_ELFv2)
+     address nooverlap_target = aligned ?
+       StubRoutines::arrayof_jbyte_disjoint_arraycopy() :
+       StubRoutines::jbyte_disjoint_arraycopy();
+#else
     address nooverlap_target = aligned ?
       ((FunctionDescriptor*)StubRoutines::arrayof_jbyte_disjoint_arraycopy())->entry() :
       ((FunctionDescriptor*)StubRoutines::jbyte_disjoint_arraycopy())->entry();
+#endif
 
     array_overlap_test(nooverlap_target, 0);
     // Do reverse copy. We assume the case of actual overlap is rare enough
@@ -1345,7 +1356,7 @@
     Register tmp3 = R8_ARG6;
     Register tmp4 = R9_ARG7;
 
-    address start = __ emit_fd();
+    address start = __ function_entry();
 
       Label l_1, l_2, l_3, l_4, l_5, l_6, l_7, l_8;
     // don't try anything fancy if arrays don't have many elements
@@ -1474,15 +1485,21 @@
   //
   address generate_conjoint_short_copy(bool aligned, const char * name) {
     StubCodeMark mark(this, "StubRoutines", name);
-    address start = __ emit_fd();
+    address start = __ function_entry();
 
     Register tmp1 = R6_ARG4;
     Register tmp2 = R7_ARG5;
     Register tmp3 = R8_ARG6;
 
+#if defined(ABI_ELFv2)
+    address nooverlap_target = aligned ?
+        StubRoutines::arrayof_jshort_disjoint_arraycopy() :
+        StubRoutines::jshort_disjoint_arraycopy();
+#else
     address nooverlap_target = aligned ?
         ((FunctionDescriptor*)StubRoutines::arrayof_jshort_disjoint_arraycopy())->entry() :
         ((FunctionDescriptor*)StubRoutines::jshort_disjoint_arraycopy())->entry();
+#endif
 
     array_overlap_test(nooverlap_target, 1);
 
@@ -1597,7 +1614,7 @@
   //
   address generate_disjoint_int_copy(bool aligned, const char * name) {
     StubCodeMark mark(this, "StubRoutines", name);
-    address start = __ emit_fd();
+    address start = __ function_entry();
     generate_disjoint_int_copy_core(aligned);
     __ blr();
     return start;
@@ -1681,11 +1698,17 @@
   //
   address generate_conjoint_int_copy(bool aligned, const char * name) {
     StubCodeMark mark(this, "StubRoutines", name);
-    address start = __ emit_fd();
+    address start = __ function_entry();
 
+#if defined(ABI_ELFv2)
+    address nooverlap_target = aligned ?
+      StubRoutines::arrayof_jint_disjoint_arraycopy() :
+      StubRoutines::jint_disjoint_arraycopy();
+#else
     address nooverlap_target = aligned ?
       ((FunctionDescriptor*)StubRoutines::arrayof_jint_disjoint_arraycopy())->entry() :
       ((FunctionDescriptor*)StubRoutines::jint_disjoint_arraycopy())->entry();
+#endif
 
     array_overlap_test(nooverlap_target, 2);
 
@@ -1767,7 +1790,7 @@
   //
   address generate_disjoint_long_copy(bool aligned, const char * name) {
     StubCodeMark mark(this, "StubRoutines", name);
-    address start = __ emit_fd();
+    address start = __ function_entry();
     generate_disjoint_long_copy_core(aligned);
     __ blr();
 
@@ -1849,11 +1872,17 @@
   //
   address generate_conjoint_long_copy(bool aligned, const char * name) {
     StubCodeMark mark(this, "StubRoutines", name);
-    address start = __ emit_fd();
+    address start = __ function_entry();
 
+#if defined(ABI_ELFv2)
+    address nooverlap_target = aligned ?
+      StubRoutines::arrayof_jlong_disjoint_arraycopy() :
+      StubRoutines::jlong_disjoint_arraycopy();
+#else
     address nooverlap_target = aligned ?
       ((FunctionDescriptor*)StubRoutines::arrayof_jlong_disjoint_arraycopy())->entry() :
       ((FunctionDescriptor*)StubRoutines::jlong_disjoint_arraycopy())->entry();
+#endif
 
     array_overlap_test(nooverlap_target, 3);
     generate_conjoint_long_copy_core(aligned);
@@ -1875,11 +1904,17 @@
   address generate_conjoint_oop_copy(bool aligned, const char * name, bool dest_uninitialized) {
     StubCodeMark mark(this, "StubRoutines", name);
 
-    address start = __ emit_fd();
+    address start = __ function_entry();
 
+#if defined(ABI_ELFv2)
+    address nooverlap_target = aligned ?
+      StubRoutines::arrayof_oop_disjoint_arraycopy() :
+      StubRoutines::oop_disjoint_arraycopy();
+#else
     address nooverlap_target = aligned ?
       ((FunctionDescriptor*)StubRoutines::arrayof_oop_disjoint_arraycopy())->entry() :
       ((FunctionDescriptor*)StubRoutines::oop_disjoint_arraycopy())->entry();
+#endif
 
     gen_write_ref_array_pre_barrier(R3_ARG1, R4_ARG2, R5_ARG3, dest_uninitialized, R9_ARG7);
 
@@ -1910,7 +1945,7 @@
   //
   address generate_disjoint_oop_copy(bool aligned, const char * name, bool dest_uninitialized) {
     StubCodeMark mark(this, "StubRoutines", name);
-    address start = __ emit_fd();
+    address start = __ function_entry();
 
     gen_write_ref_array_pre_barrier(R3_ARG1, R4_ARG2, R5_ARG3, dest_uninitialized, R9_ARG7);
 
@@ -1991,7 +2026,7 @@
     StubCodeMark mark(this, "StubRoutines", name);
 
     // Entry point, pc or function descriptor.
-    *entry = __ emit_fd();
+    *entry = __ function_entry();
 
     // Load *adr into R4_ARG2, may fault.
     *fault_pc = __ pc();
@@ -2056,7 +2091,7 @@
       guarantee(!UseAESIntrinsics, "not yet implemented.");
     }
 
-    // PPC uses stubs for safefetch.
+    // Safefetch stubs.
     generate_safefetch("SafeFetch32", sizeof(int),     &StubRoutines::_safefetch32_entry,
                                                        &StubRoutines::_safefetch32_fault_pc,
                                                        &StubRoutines::_safefetch32_continuation_pc);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/cpu/ppc/vm/templateInterpreterGenerator_ppc.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2013, 2014 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.
+ *
+ */
+
+#ifndef CPU_PPC_VM_TEMPLATEINTERPRETERGENERATOR_PPC_HPP
+#define CPU_PPC_VM_TEMPLATEINTERPRETERGENERATOR_PPC_HPP
+
+ protected:
+  address generate_normal_entry(bool synchronized);
+  address generate_native_entry(bool synchronized);
+  address generate_math_entry(AbstractInterpreter::MethodKind kind);
+  address generate_empty_entry(void);
+
+  void lock_method(Register Rflags, Register Rscratch1, Register Rscratch2, bool flags_preloaded=false);
+  void unlock_method(bool check_exceptions = true);
+
+  void generate_counter_incr(Label* overflow, Label* profile_method, Label* profile_method_continue);
+  void generate_counter_overflow(Label& continue_entry);
+
+  void generate_fixed_frame(bool native_call, Register Rsize_of_parameters, Register Rsize_of_locals);
+  void generate_stack_overflow_check(Register Rframe_size, Register Rscratch1);
+
+#endif // CPU_PPC_VM_TEMPLATEINTERPRETERGENERATOR_PPC_HPP
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/cpu/ppc/vm/templateInterpreter_ppc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,1813 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2013, 2014 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 "precompiled.hpp"
+#ifndef CC_INTERP
+#include "asm/macroAssembler.inline.hpp"
+#include "interpreter/bytecodeHistogram.hpp"
+#include "interpreter/interpreter.hpp"
+#include "interpreter/interpreterGenerator.hpp"
+#include "interpreter/interpreterRuntime.hpp"
+#include "interpreter/templateTable.hpp"
+#include "oops/arrayOop.hpp"
+#include "oops/methodData.hpp"
+#include "oops/method.hpp"
+#include "oops/oop.inline.hpp"
+#include "prims/jvmtiExport.hpp"
+#include "prims/jvmtiThreadState.hpp"
+#include "runtime/arguments.hpp"
+#include "runtime/deoptimization.hpp"
+#include "runtime/frame.inline.hpp"
+#include "runtime/sharedRuntime.hpp"
+#include "runtime/stubRoutines.hpp"
+#include "runtime/synchronizer.hpp"
+#include "runtime/timer.hpp"
+#include "runtime/vframeArray.hpp"
+#include "utilities/debug.hpp"
+#include "utilities/macros.hpp"
+
+#undef __
+#define __ _masm->
+
+#ifdef PRODUCT
+#define BLOCK_COMMENT(str) /* nothing */
+#else
+#define BLOCK_COMMENT(str) __ block_comment(str)
+#endif
+
+#define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
+
+//-----------------------------------------------------------------------------
+
+// Actually we should never reach here since we do stack overflow checks before pushing any frame.
+address TemplateInterpreterGenerator::generate_StackOverflowError_handler() {
+  address entry = __ pc();
+  __ unimplemented("generate_StackOverflowError_handler");
+  return entry;
+}
+
+address TemplateInterpreterGenerator::generate_ArrayIndexOutOfBounds_handler(const char* name) {
+  address entry = __ pc();
+  __ empty_expression_stack();
+  __ load_const_optimized(R4_ARG2, (address) name);
+  // Index is in R17_tos.
+  __ mr(R5_ARG3, R17_tos);
+  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException));
+  return entry;
+}
+
+#if 0
+// Call special ClassCastException constructor taking object to cast
+// and target class as arguments.
+address TemplateInterpreterGenerator::generate_ClassCastException_verbose_handler(const char* name) {
+  address entry = __ pc();
+
+  // Target class oop is in register R6_ARG4 by convention!
+
+  // Expression stack must be empty before entering the VM if an
+  // exception happened.
+  __ empty_expression_stack();
+  // Setup parameters.
+  // Thread will be loaded to R3_ARG1.
+  __ load_const_optimized(R4_ARG2, (address) name);
+  __ mr(R5_ARG3, R17_tos);
+  // R6_ARG4 contains specified class.
+  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ClassCastException_verbose));
+#ifdef ASSERT
+  // Above call must not return here since exception pending.
+  __ should_not_reach_here();
+#endif
+  return entry;
+}
+#endif
+
+address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
+  address entry = __ pc();
+  // Expression stack must be empty before entering the VM if an
+  // exception happened.
+  __ empty_expression_stack();
+
+  // Load exception object.
+  // Thread will be loaded to R3_ARG1.
+  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ClassCastException), R17_tos);
+#ifdef ASSERT
+  // Above call must not return here since exception pending.
+  __ should_not_reach_here();
+#endif
+  return entry;
+}
+
+address TemplateInterpreterGenerator::generate_exception_handler_common(const char* name, const char* message, bool pass_oop) {
+  address entry = __ pc();
+  //__ untested("generate_exception_handler_common");
+  Register Rexception = R17_tos;
+
+  // Expression stack must be empty before entering the VM if an exception happened.
+  __ empty_expression_stack();
+
+  __ load_const_optimized(R4_ARG2, (address) name, R11_scratch1);
+  if (pass_oop) {
+    __ mr(R5_ARG3, Rexception);
+    __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_klass_exception), false);
+  } else {
+    __ load_const_optimized(R5_ARG3, (address) message, R11_scratch1);
+    __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_exception), false);
+  }
+
+  // Throw exception.
+  __ mr(R3_ARG1, Rexception);
+  __ load_const_optimized(R11_scratch1, Interpreter::throw_exception_entry(), R12_scratch2);
+  __ mtctr(R11_scratch1);
+  __ bctr();
+
+  return entry;
+}
+
+address TemplateInterpreterGenerator::generate_continuation_for(TosState state) {
+  address entry = __ pc();
+  __ unimplemented("generate_continuation_for");
+  return entry;
+}
+
+// This entry is returned to when a call returns to the interpreter.
+// When we arrive here, we expect that the callee stack frame is already popped.
+address TemplateInterpreterGenerator::generate_return_entry_for(TosState state, int step, size_t index_size) {
+  address entry = __ pc();
+
+  // Move the value out of the return register back to the TOS cache of current frame.
+  switch (state) {
+    case ltos:
+    case btos:
+    case ctos:
+    case stos:
+    case atos:
+    case itos: __ mr(R17_tos, R3_RET); break;   // RET -> TOS cache
+    case ftos:
+    case dtos: __ fmr(F15_ftos, F1_RET); break; // TOS cache -> GR_FRET
+    case vtos: break;                           // Nothing to do, this was a void return.
+    default  : ShouldNotReachHere();
+  }
+
+  __ restore_interpreter_state(R11_scratch1); // Sets R11_scratch1 = fp.
+  __ ld(R12_scratch2, _ijava_state_neg(top_frame_sp), R11_scratch1);
+  __ resize_frame_absolute(R12_scratch2, R11_scratch1, R0);
+
+  // Compiled code destroys templateTableBase, reload.
+  __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R12_scratch2);
+
+  const Register cache = R11_scratch1;
+  const Register size  = R12_scratch2;
+  __ get_cache_and_index_at_bcp(cache, 1, index_size);
+
+  // Big Endian (get least significant byte of 64 bit value):
+  __ lbz(size, in_bytes(ConstantPoolCache::base_offset() + ConstantPoolCacheEntry::flags_offset()) + 7, cache);
+  __ sldi(size, size, Interpreter::logStackElementSize);
+  __ add(R15_esp, R15_esp, size);
+  __ dispatch_next(state, step);
+  return entry;
+}
+
+address TemplateInterpreterGenerator::generate_deopt_entry_for(TosState state, int step) {
+  address entry = __ pc();
+  // If state != vtos, we're returning from a native method, which put it's result
+  // into the result register. So move the value out of the return register back
+  // to the TOS cache of current frame.
+
+  switch (state) {
+    case ltos:
+    case btos:
+    case ctos:
+    case stos:
+    case atos:
+    case itos: __ mr(R17_tos, R3_RET); break;   // GR_RET -> TOS cache
+    case ftos:
+    case dtos: __ fmr(F15_ftos, F1_RET); break; // TOS cache -> GR_FRET
+    case vtos: break;                           // Nothing to do, this was a void return.
+    default  : ShouldNotReachHere();
+  }
+
+  // Load LcpoolCache @@@ should be already set!
+  __ get_constant_pool_cache(R27_constPoolCache);
+
+  // Handle a pending exception, fall through if none.
+  __ check_and_forward_exception(R11_scratch1, R12_scratch2);
+
+  // Start executing bytecodes.
+  __ dispatch_next(state, step);
+
+  return entry;
+}
+
+// A result handler converts the native result into java format.
+// Use the shared code between c++ and template interpreter.
+address TemplateInterpreterGenerator::generate_result_handler_for(BasicType type) {
+  return AbstractInterpreterGenerator::generate_result_handler_for(type);
+}
+
+address TemplateInterpreterGenerator::generate_safept_entry_for(TosState state, address runtime_entry) {
+  address entry = __ pc();
+
+  __ push(state);
+  __ call_VM(noreg, runtime_entry);
+  __ dispatch_via(vtos, Interpreter::_normal_table.table_for(vtos));
+
+  return entry;
+}
+
+// Helpers for commoning out cases in the various type of method entries.
+
+// Increment invocation count & check for overflow.
+//
+// Note: checking for negative value instead of overflow
+//       so we have a 'sticky' overflow test.
+//
+void TemplateInterpreterGenerator::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.
+  Register Rscratch1   = R11_scratch1;
+  Register Rscratch2   = R12_scratch2;
+  Register R3_counters = R3_ARG1;
+  Label done;
+
+  if (TieredCompilation) {
+    const int increment = InvocationCounter::count_increment;
+    const int mask = ((1 << Tier0InvokeNotifyFreqLog) - 1) << InvocationCounter::count_shift;
+    Label no_mdo;
+    if (ProfileInterpreter) {
+      const Register Rmdo = Rscratch1;
+      // If no method data exists, go to profile_continue.
+      __ ld(Rmdo, in_bytes(Method::method_data_offset()), R19_method);
+      __ cmpdi(CCR0, Rmdo, 0);
+      __ beq(CCR0, no_mdo);
+
+      // Increment backedge counter in the MDO.
+      const int mdo_bc_offs = in_bytes(MethodData::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
+      __ lwz(Rscratch2, mdo_bc_offs, Rmdo);
+      __ addi(Rscratch2, Rscratch2, increment);
+      __ stw(Rscratch2, mdo_bc_offs, Rmdo);
+      __ load_const_optimized(Rscratch1, mask, R0);
+      __ and_(Rscratch1, Rscratch2, Rscratch1);
+      __ bne(CCR0, done);
+      __ b(*overflow);
+    }
+
+    // Increment counter in MethodCounters*.
+    const int mo_bc_offs = in_bytes(MethodCounters::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
+    __ bind(no_mdo);
+    __ get_method_counters(R19_method, R3_counters, done);
+    __ lwz(Rscratch2, mo_bc_offs, R3_counters);
+    __ addi(Rscratch2, Rscratch2, increment);
+    __ stw(Rscratch2, mo_bc_offs, R3_counters);
+    __ load_const_optimized(Rscratch1, mask, R0);
+    __ and_(Rscratch1, Rscratch2, Rscratch1);
+    __ beq(CCR0, *overflow);
+
+    __ bind(done);
+
+  } else {
+
+    // Update standard invocation counters.
+    Register Rsum_ivc_bec = R4_ARG2;
+    __ get_method_counters(R19_method, R3_counters, done);
+    __ increment_invocation_counter(R3_counters, Rsum_ivc_bec, R12_scratch2);
+    // Increment interpreter invocation counter.
+    if (ProfileInterpreter) {  // %%% Merge this into methodDataOop.
+      __ lwz(R12_scratch2, in_bytes(MethodCounters::interpreter_invocation_counter_offset()), R3_counters);
+      __ addi(R12_scratch2, R12_scratch2, 1);
+      __ stw(R12_scratch2, in_bytes(MethodCounters::interpreter_invocation_counter_offset()), R3_counters);
+    }
+    // Check if we must create a method data obj.
+    if (ProfileInterpreter && profile_method != NULL) {
+      const Register profile_limit = Rscratch1;
+      int pl_offs = __ load_const_optimized(profile_limit, &InvocationCounter::InterpreterProfileLimit, R0, true);
+      __ lwz(profile_limit, pl_offs, profile_limit);
+      // Test to see if we should create a method data oop.
+      __ cmpw(CCR0, Rsum_ivc_bec, profile_limit);
+      __ blt(CCR0, *profile_method_continue);
+      // If no method data exists, go to profile_method.
+      __ test_method_data_pointer(*profile_method);
+    }
+    // Finally check for counter overflow.
+    if (overflow) {
+      const Register invocation_limit = Rscratch1;
+      int il_offs = __ load_const_optimized(invocation_limit, &InvocationCounter::InterpreterInvocationLimit, R0, true);
+      __ lwz(invocation_limit, il_offs, invocation_limit);
+      assert(4 == sizeof(InvocationCounter::InterpreterInvocationLimit), "unexpected field size");
+      __ cmpw(CCR0, Rsum_ivc_bec, invocation_limit);
+      __ bge(CCR0, *overflow);
+    }
+
+    __ bind(done);
+  }
+}
+
+// Generate code to initiate compilation on invocation counter overflow.
+void TemplateInterpreterGenerator::generate_counter_overflow(Label& continue_entry) {
+  // Generate code to initiate compilation on the counter overflow.
+
+  // InterpreterRuntime::frequency_counter_overflow takes one arguments,
+  // which indicates if the counter overflow occurs at a backwards branch (NULL bcp)
+  // We pass zero in.
+  // The call returns the address of the verified entry point for the method or NULL
+  // if the compilation did not complete (either went background or bailed out).
+  //
+  // Unlike the C++ interpreter above: Check exceptions!
+  // Assumption: Caller must set the flag "do_not_unlock_if_sychronized" if the monitor of a sync'ed
+  // method has not yet been created. Thus, no unlocking of a non-existing monitor can occur.
+
+  __ li(R4_ARG2, 0);
+  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::frequency_counter_overflow), R4_ARG2, true);
+
+  // Returns verified_entry_point or NULL.
+  // We ignore it in any case.
+  __ b(continue_entry);
+}
+
+void TemplateInterpreterGenerator::generate_stack_overflow_check(Register Rmem_frame_size, Register Rscratch1) {
+  assert_different_registers(Rmem_frame_size, Rscratch1);
+  __ generate_stack_overflow_check_with_compare_and_throw(Rmem_frame_size, Rscratch1);
+}
+
+void TemplateInterpreterGenerator::unlock_method(bool check_exceptions) {
+  __ unlock_object(R26_monitor, check_exceptions);
+}
+
+// Lock the current method, interpreter register window must be set up!
+void TemplateInterpreterGenerator::lock_method(Register Rflags, Register Rscratch1, Register Rscratch2, bool flags_preloaded) {
+  const Register Robj_to_lock = Rscratch2;
+
+  {
+    if (!flags_preloaded) {
+      __ lwz(Rflags, method_(access_flags));
+    }
+
+#ifdef ASSERT
+    // Check if methods needs synchronization.
+    {
+      Label Lok;
+      __ testbitdi(CCR0, R0, Rflags, JVM_ACC_SYNCHRONIZED_BIT);
+      __ btrue(CCR0,Lok);
+      __ stop("method doesn't need synchronization");
+      __ bind(Lok);
+    }
+#endif // ASSERT
+  }
+
+  // Get synchronization object to Rscratch2.
+  {
+    const int mirror_offset = in_bytes(Klass::java_mirror_offset());
+    Label Lstatic;
+    Label Ldone;
+
+    __ testbitdi(CCR0, R0, Rflags, JVM_ACC_STATIC_BIT);
+    __ btrue(CCR0, Lstatic);
+
+    // Non-static case: load receiver obj from stack and we're done.
+    __ ld(Robj_to_lock, R18_locals);
+    __ b(Ldone);
+
+    __ bind(Lstatic); // Static case: Lock the java mirror
+    __ ld(Robj_to_lock, in_bytes(Method::const_offset()), R19_method);
+    __ ld(Robj_to_lock, in_bytes(ConstMethod::constants_offset()), Robj_to_lock);
+    __ ld(Robj_to_lock, ConstantPool::pool_holder_offset_in_bytes(), Robj_to_lock);
+    __ ld(Robj_to_lock, mirror_offset, Robj_to_lock);
+
+    __ bind(Ldone);
+    __ verify_oop(Robj_to_lock);
+  }
+
+  // Got the oop to lock => execute!
+  __ add_monitor_to_stack(true, Rscratch1, R0);
+
+  __ std(Robj_to_lock, BasicObjectLock::obj_offset_in_bytes(), R26_monitor);
+  __ lock_object(R26_monitor, Robj_to_lock);
+}
+
+// Generate a fixed interpreter frame for pure interpreter
+// and I2N native transition frames.
+//
+// Before (stack grows downwards):
+//
+//         |  ...         |
+//         |------------- |
+//         |  java arg0   |
+//         |  ...         |
+//         |  java argn   |
+//         |              |   <-   R15_esp
+//         |              |
+//         |--------------|
+//         | abi_112      |
+//         |              |   <-   R1_SP
+//         |==============|
+//
+//
+// After:
+//
+//         |  ...         |
+//         |  java arg0   |<-   R18_locals
+//         |  ...         |
+//         |  java argn   |
+//         |--------------|
+//         |              |
+//         |  java locals |
+//         |              |
+//         |--------------|
+//         |  abi_48      |
+//         |==============|
+//         |              |
+//         |   istate     |
+//         |              |
+//         |--------------|
+//         |   monitor    |<-   R26_monitor
+//         |--------------|
+//         |              |<-   R15_esp
+//         | expression   |
+//         | stack        |
+//         |              |
+//         |--------------|
+//         |              |
+//         | abi_112      |<-   R1_SP
+//         |==============|
+//
+// The top most frame needs an abi space of 112 bytes. This space is needed,
+// since we call to c. The c function may spill their arguments to the caller
+// frame. When we call to java, we don't need these spill slots. In order to save
+// space on the stack, we resize the caller. However, java local reside in
+// the caller frame and the frame has to be increased. The frame_size for the
+// current frame was calculated based on max_stack as size for the expression
+// stack. At the call, just a part of the expression stack might be used.
+// We don't want to waste this space and cut the frame back accordingly.
+// The resulting amount for resizing is calculated as follows:
+// resize =   (number_of_locals - number_of_arguments) * slot_size
+//          + (R1_SP - R15_esp) + 48
+//
+// The size for the callee frame is calculated:
+// framesize = 112 + max_stack + monitor + state_size
+//
+// maxstack:   Max number of slots on the expression stack, loaded from the method.
+// monitor:    We statically reserve room for one monitor object.
+// state_size: We save the current state of the interpreter to this area.
+//
+void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call, Register Rsize_of_parameters, Register Rsize_of_locals) {
+  Register parent_frame_resize = R6_ARG4, // Frame will grow by this number of bytes.
+           top_frame_size      = R7_ARG5,
+           Rconst_method       = R8_ARG6;
+
+  assert_different_registers(Rsize_of_parameters, Rsize_of_locals, parent_frame_resize, top_frame_size);
+
+  __ ld(Rconst_method, method_(const));
+  __ lhz(Rsize_of_parameters /* number of params */,
+         in_bytes(ConstMethod::size_of_parameters_offset()), Rconst_method);
+  if (native_call) {
+    // If we're calling a native method, we reserve space for the worst-case signature
+    // handler varargs vector, which is max(Argument::n_register_parameters, parameter_count+2).
+    // We add two slots to the parameter_count, one for the jni
+    // environment and one for a possible native mirror.
+    Label skip_native_calculate_max_stack;
+    __ addi(top_frame_size, Rsize_of_parameters, 2);
+    __ cmpwi(CCR0, top_frame_size, Argument::n_register_parameters);
+    __ bge(CCR0, skip_native_calculate_max_stack);
+    __ li(top_frame_size, Argument::n_register_parameters);
+    __ bind(skip_native_calculate_max_stack);
+    __ sldi(Rsize_of_parameters, Rsize_of_parameters, Interpreter::logStackElementSize);
+    __ sldi(top_frame_size, top_frame_size, Interpreter::logStackElementSize);
+    __ sub(parent_frame_resize, R1_SP, R15_esp); // <0, off by Interpreter::stackElementSize!
+    assert(Rsize_of_locals == noreg, "Rsize_of_locals not initialized"); // Only relevant value is Rsize_of_parameters.
+  } else {
+    __ lhz(Rsize_of_locals /* number of params */, in_bytes(ConstMethod::size_of_locals_offset()), Rconst_method);
+    __ sldi(Rsize_of_parameters, Rsize_of_parameters, Interpreter::logStackElementSize);
+    __ sldi(Rsize_of_locals, Rsize_of_locals, Interpreter::logStackElementSize);
+    __ lhz(top_frame_size, in_bytes(ConstMethod::max_stack_offset()), Rconst_method);
+    __ sub(R11_scratch1, Rsize_of_locals, Rsize_of_parameters); // >=0
+    __ sub(parent_frame_resize, R1_SP, R15_esp); // <0, off by Interpreter::stackElementSize!
+    __ sldi(top_frame_size, top_frame_size, Interpreter::logStackElementSize);
+    __ add(parent_frame_resize, parent_frame_resize, R11_scratch1);
+  }
+
+  // Compute top frame size.
+  __ addi(top_frame_size, top_frame_size, frame::abi_reg_args_size + frame::ijava_state_size);
+
+  // Cut back area between esp and max_stack.
+  __ addi(parent_frame_resize, parent_frame_resize, frame::abi_minframe_size - Interpreter::stackElementSize);
+
+  __ round_to(top_frame_size, frame::alignment_in_bytes);
+  __ round_to(parent_frame_resize, frame::alignment_in_bytes);
+  // parent_frame_resize = (locals-parameters) - (ESP-SP-ABI48) Rounded to frame alignment size.
+  // Enlarge by locals-parameters (not in case of native_call), shrink by ESP-SP-ABI48.
+
+  {
+    // --------------------------------------------------------------------------
+    // Stack overflow check
+
+    Label cont;
+    __ add(R11_scratch1, parent_frame_resize, top_frame_size);
+    generate_stack_overflow_check(R11_scratch1, R12_scratch2);
+  }
+
+  // Set up interpreter state registers.
+
+  __ add(R18_locals, R15_esp, Rsize_of_parameters);
+  __ ld(R27_constPoolCache, in_bytes(ConstMethod::constants_offset()), Rconst_method);
+  __ ld(R27_constPoolCache, ConstantPool::cache_offset_in_bytes(), R27_constPoolCache);
+
+  // Set method data pointer.
+  if (ProfileInterpreter) {
+    Label zero_continue;
+    __ ld(R28_mdx, method_(method_data));
+    __ cmpdi(CCR0, R28_mdx, 0);
+    __ beq(CCR0, zero_continue);
+    __ addi(R28_mdx, R28_mdx, in_bytes(MethodData::data_offset()));
+    __ bind(zero_continue);
+  }
+
+  if (native_call) {
+    __ li(R14_bcp, 0); // Must initialize.
+  } else {
+    __ add(R14_bcp, in_bytes(ConstMethod::codes_offset()), Rconst_method);
+  }
+
+  // Resize parent frame.
+  __ mflr(R12_scratch2);
+  __ neg(parent_frame_resize, parent_frame_resize);
+  __ resize_frame(parent_frame_resize, R11_scratch1);
+  __ std(R12_scratch2, _abi(lr), R1_SP);
+
+  __ addi(R26_monitor, R1_SP, - frame::ijava_state_size);
+  __ addi(R15_esp, R26_monitor, - Interpreter::stackElementSize);
+
+  // Store values.
+  // R15_esp, R14_bcp, R26_monitor, R28_mdx are saved at java calls
+  // in InterpreterMacroAssembler::call_from_interpreter.
+  __ std(R19_method, _ijava_state_neg(method), R1_SP);
+  __ std(R21_sender_SP, _ijava_state_neg(sender_sp), R1_SP);
+  __ std(R27_constPoolCache, _ijava_state_neg(cpoolCache), R1_SP);
+  __ std(R18_locals, _ijava_state_neg(locals), R1_SP);
+
+  // Note: esp, bcp, monitor, mdx live in registers. Hence, the correct version can only
+  // be found in the frame after save_interpreter_state is done. This is always true
+  // for non-top frames. But when a signal occurs, dumping the top frame can go wrong,
+  // because e.g. frame::interpreter_frame_bcp() will not access the correct value
+  // (Enhanced Stack Trace).
+  // The signal handler does not save the interpreter state into the frame.
+  __ li(R0, 0);
+#ifdef ASSERT
+  // Fill remaining slots with constants.
+  __ load_const_optimized(R11_scratch1, 0x5afe);
+  __ load_const_optimized(R12_scratch2, 0xdead);
+#endif
+  // We have to initialize some frame slots for native calls (accessed by GC).
+  if (native_call) {
+    __ std(R26_monitor, _ijava_state_neg(monitors), R1_SP);
+    __ std(R14_bcp, _ijava_state_neg(bcp), R1_SP);
+    if (ProfileInterpreter) { __ std(R28_mdx, _ijava_state_neg(mdx), R1_SP); }
+  }
+#ifdef ASSERT
+  else {
+    __ std(R12_scratch2, _ijava_state_neg(monitors), R1_SP);
+    __ std(R12_scratch2, _ijava_state_neg(bcp), R1_SP);
+    __ std(R12_scratch2, _ijava_state_neg(mdx), R1_SP);
+  }
+  __ std(R11_scratch1, _ijava_state_neg(ijava_reserved), R1_SP);
+  __ std(R12_scratch2, _ijava_state_neg(esp), R1_SP);
+  __ std(R12_scratch2, _ijava_state_neg(lresult), R1_SP);
+  __ std(R12_scratch2, _ijava_state_neg(fresult), R1_SP);
+#endif
+  __ subf(R12_scratch2, top_frame_size, R1_SP);
+  __ std(R0, _ijava_state_neg(oop_tmp), R1_SP);
+  __ std(R12_scratch2, _ijava_state_neg(top_frame_sp), R1_SP);
+
+  // Push top frame.
+  __ push_frame(top_frame_size, R11_scratch1);
+}
+
+// End of helpers
+
+// ============================================================================
+// Various method entries
+//
+
+// Empty method, generate a very fast return. We must skip this entry if
+// someone's debugging, indicated by the flag
+// "interp_mode" in the Thread obj.
+// Note: empty methods are generated mostly methods that do assertions, which are
+// disabled in the "java opt build".
+address TemplateInterpreterGenerator::generate_empty_entry(void) {
+  if (!UseFastEmptyMethods) {
+    NOT_PRODUCT(__ should_not_reach_here();)
+    return Interpreter::entry_for_kind(Interpreter::zerolocals);
+  }
+
+  Label Lslow_path;
+  const Register Rjvmti_mode = R11_scratch1;
+  address entry = __ pc();
+
+  __ lwz(Rjvmti_mode, thread_(interp_only_mode));
+  __ cmpwi(CCR0, Rjvmti_mode, 0);
+  __ bne(CCR0, Lslow_path); // jvmti_mode!=0
+
+  // Noone's debuggin: Simply return.
+  // Pop c2i arguments (if any) off when we return.
+#ifdef ASSERT
+    __ ld(R9_ARG7, 0, R1_SP);
+    __ ld(R10_ARG8, 0, R21_sender_SP);
+    __ cmpd(CCR0, R9_ARG7, R10_ARG8);
+    __ asm_assert_eq("backlink", 0x545);
+#endif // ASSERT
+  __ mr(R1_SP, R21_sender_SP); // Cut the stack back to where the caller started.
+
+  // And we're done.
+  __ blr();
+
+  __ bind(Lslow_path);
+  __ branch_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals), R11_scratch1);
+  __ flush();
+
+  return entry;
+}
+
+// Support abs and sqrt like in compiler.
+// For others we can use a normal (native) entry.
+
+inline bool math_entry_available(AbstractInterpreter::MethodKind kind) {
+  // Provide math entry with debugging on demand.
+  // Note: Debugging changes which code will get executed:
+  // Debugging or disabled InlineIntrinsics: java method will get interpreted and performs a native call.
+  // Not debugging and enabled InlineIntrinics: processor instruction will get used.
+  // Result might differ slightly due to rounding etc.
+  if (!InlineIntrinsics && (!FLAG_IS_ERGO(InlineIntrinsics))) return false; // Generate a vanilla entry.
+
+  return ((kind==Interpreter::java_lang_math_sqrt && VM_Version::has_fsqrt()) ||
+          (kind==Interpreter::java_lang_math_abs));
+}
+
+address TemplateInterpreterGenerator::generate_math_entry(AbstractInterpreter::MethodKind kind) {
+  if (!math_entry_available(kind)) {
+    NOT_PRODUCT(__ should_not_reach_here();)
+    return Interpreter::entry_for_kind(Interpreter::zerolocals);
+  }
+
+  Label Lslow_path;
+  const Register Rjvmti_mode = R11_scratch1;
+  address entry = __ pc();
+
+  // Provide math entry with debugging on demand.
+  __ lwz(Rjvmti_mode, thread_(interp_only_mode));
+  __ cmpwi(CCR0, Rjvmti_mode, 0);
+  __ bne(CCR0, Lslow_path); // jvmti_mode!=0
+
+  __ lfd(F1_RET, Interpreter::stackElementSize, R15_esp);
+
+  // Pop c2i arguments (if any) off when we return.
+#ifdef ASSERT
+  __ ld(R9_ARG7, 0, R1_SP);
+  __ ld(R10_ARG8, 0, R21_sender_SP);
+  __ cmpd(CCR0, R9_ARG7, R10_ARG8);
+  __ asm_assert_eq("backlink", 0x545);
+#endif // ASSERT
+  __ mr(R1_SP, R21_sender_SP); // Cut the stack back to where the caller started.
+
+  if (kind == Interpreter::java_lang_math_sqrt) {
+    __ fsqrt(F1_RET, F1_RET);
+  } else if (kind == Interpreter::java_lang_math_abs) {
+    __ fabs(F1_RET, F1_RET);
+  } else {
+    ShouldNotReachHere();
+  }
+
+  // And we're done.
+  __ blr();
+
+  // Provide slow path for JVMTI case.
+  __ bind(Lslow_path);
+  __ branch_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals), R12_scratch2);
+  __ flush();
+
+  return entry;
+}
+
+// Interpreter stub for calling a native method. (asm interpreter)
+// This sets up a somewhat different looking stack for calling the
+// native method than the typical interpreter frame setup.
+//
+// On entry:
+//   R19_method    - method
+//   R16_thread    - JavaThread*
+//   R15_esp       - intptr_t* sender tos
+//
+//   abstract stack (grows up)
+//     [  IJava (caller of JNI callee)  ]  <-- ASP
+//        ...
+address TemplateInterpreterGenerator::generate_native_entry(bool synchronized) {
+
+  address entry = __ pc();
+
+  const bool inc_counter = UseCompiler || CountCompiledCalls;
+
+  // -----------------------------------------------------------------------------
+  // Allocate a new frame that represents the native callee (i2n frame).
+  // This is not a full-blown interpreter frame, but in particular, the
+  // following registers are valid after this:
+  // - R19_method
+  // - R18_local (points to start of argumuments to native function)
+  //
+  //   abstract stack (grows up)
+  //     [  IJava (caller of JNI callee)  ]  <-- ASP
+  //        ...
+
+  const Register signature_handler_fd = R11_scratch1;
+  const Register pending_exception    = R0;
+  const Register result_handler_addr  = R31;
+  const Register native_method_fd     = R11_scratch1;
+  const Register access_flags         = R22_tmp2;
+  const Register active_handles       = R11_scratch1; // R26_monitor saved to state.
+  const Register sync_state           = R12_scratch2;
+  const Register sync_state_addr      = sync_state;   // Address is dead after use.
+  const Register suspend_flags        = R11_scratch1;
+
+  //=============================================================================
+  // Allocate new frame and initialize interpreter state.
+
+  Label exception_return;
+  Label exception_return_sync_check;
+  Label stack_overflow_return;
+
+  // Generate new interpreter state and jump to stack_overflow_return in case of
+  // a stack overflow.
+  //generate_compute_interpreter_state(stack_overflow_return);
+
+  Register size_of_parameters = R22_tmp2;
+
+  generate_fixed_frame(true, size_of_parameters, noreg /* unused */);
+
+  //=============================================================================
+  // Increment invocation counter. On overflow, entry to JNI method
+  // will be compiled.
+  Label invocation_counter_overflow, continue_after_compile;
+  if (inc_counter) {
+    if (synchronized) {
+      // Since at this point in the method invocation the exception handler
+      // would try to exit the monitor of synchronized methods which hasn't
+      // been entered yet, we set the thread local variable
+      // _do_not_unlock_if_synchronized to true. If any exception was thrown by
+      // runtime, exception handling i.e. unlock_if_synchronized_method will
+      // check this thread local flag.
+      // This flag has two effects, one is to force an unwind in the topmost
+      // interpreter frame and not perform an unlock while doing so.
+      __ li(R0, 1);
+      __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
+    }
+    generate_counter_incr(&invocation_counter_overflow, NULL, NULL);
+
+    __ BIND(continue_after_compile);
+    // Reset the _do_not_unlock_if_synchronized flag.
+    if (synchronized) {
+      __ li(R0, 0);
+      __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
+    }
+  }
+
+  // access_flags = method->access_flags();
+  // Load access flags.
+  assert(access_flags->is_nonvolatile(),
+         "access_flags must be in a non-volatile register");
+  // Type check.
+  assert(4 == sizeof(AccessFlags), "unexpected field size");
+  __ lwz(access_flags, method_(access_flags));
+
+  // We don't want to reload R19_method and access_flags after calls
+  // to some helper functions.
+  assert(R19_method->is_nonvolatile(),
+         "R19_method must be a non-volatile register");
+
+  // Check for synchronized methods. Must happen AFTER invocation counter
+  // check, so method is not locked if counter overflows.
+
+  if (synchronized) {
+    lock_method(access_flags, R11_scratch1, R12_scratch2, true);
+
+    // Update monitor in state.
+    __ ld(R11_scratch1, 0, R1_SP);
+    __ std(R26_monitor, _ijava_state_neg(monitors), R11_scratch1);
+  }
+
+  // jvmti/jvmpi support
+  __ notify_method_entry();
+
+  //=============================================================================
+  // Get and call the signature handler.
+
+  __ ld(signature_handler_fd, method_(signature_handler));
+  Label call_signature_handler;
+
+  __ cmpdi(CCR0, signature_handler_fd, 0);
+  __ bne(CCR0, call_signature_handler);
+
+  // Method has never been called. Either generate a specialized
+  // handler or point to the slow one.
+  //
+  // Pass parameter 'false' to avoid exception check in call_VM.
+  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::prepare_native_call), R19_method, false);
+
+  // Check for an exception while looking up the target method. If we
+  // incurred one, bail.
+  __ ld(pending_exception, thread_(pending_exception));
+  __ cmpdi(CCR0, pending_exception, 0);
+  __ bne(CCR0, exception_return_sync_check); // Has pending exception.
+
+  // Reload signature handler, it may have been created/assigned in the meanwhile.
+  __ ld(signature_handler_fd, method_(signature_handler));
+  __ twi_0(signature_handler_fd); // Order wrt. load of klass mirror and entry point (isync is below).
+
+  __ BIND(call_signature_handler);
+
+  // Before we call the signature handler we push a new frame to
+  // protect the interpreter frame volatile registers when we return
+  // from jni but before we can get back to Java.
+
+  // First set the frame anchor while the SP/FP registers are
+  // convenient and the slow signature handler can use this same frame
+  // anchor.
+
+  // We have a TOP_IJAVA_FRAME here, which belongs to us.
+  __ set_top_ijava_frame_at_SP_as_last_Java_frame(R1_SP, R12_scratch2/*tmp*/);
+
+  // Now the interpreter frame (and its call chain) have been
+  // invalidated and flushed. We are now protected against eager
+  // being enabled in native code. Even if it goes eager the
+  // registers will be reloaded as clean and we will invalidate after
+  // the call so no spurious flush should be possible.
+
+  // Call signature handler and pass locals address.
+  //
+  // Our signature handlers copy required arguments to the C stack
+  // (outgoing C args), R3_ARG1 to R10_ARG8, and FARG1 to FARG13.
+  __ mr(R3_ARG1, R18_locals);
+  __ ld(signature_handler_fd, 0, signature_handler_fd);
+
+  __ call_stub(signature_handler_fd);
+
+  // Remove the register parameter varargs slots we allocated in
+  // compute_interpreter_state. SP+16 ends up pointing to the ABI
+  // outgoing argument area.
+  //
+  // Not needed on PPC64.
+  //__ add(SP, SP, Argument::n_register_parameters*BytesPerWord);
+
+  assert(result_handler_addr->is_nonvolatile(), "result_handler_addr must be in a non-volatile register");
+  // Save across call to native method.
+  __ mr(result_handler_addr, R3_RET);
+
+  __ isync(); // Acquire signature handler before trying to fetch the native entry point and klass mirror.
+
+  // Set up fixed parameters and call the native method.
+  // If the method is static, get mirror into R4_ARG2.
+  {
+    Label method_is_not_static;
+    // Access_flags is non-volatile and still, no need to restore it.
+
+    // Restore access flags.
+    __ testbitdi(CCR0, R0, access_flags, JVM_ACC_STATIC_BIT);
+    __ bfalse(CCR0, method_is_not_static);
+
+    // constants = method->constants();
+    __ ld(R11_scratch1, in_bytes(Method::const_offset()), R19_method);
+    __ ld(R11_scratch1, in_bytes(ConstMethod::constants_offset()), R11_scratch1);
+    // pool_holder = method->constants()->pool_holder();
+    __ ld(R11_scratch1/*pool_holder*/, ConstantPool::pool_holder_offset_in_bytes(),
+          R11_scratch1/*constants*/);
+
+    const int mirror_offset = in_bytes(Klass::java_mirror_offset());
+
+    // mirror = pool_holder->klass_part()->java_mirror();
+    __ ld(R0/*mirror*/, mirror_offset, R11_scratch1/*pool_holder*/);
+    // state->_native_mirror = mirror;
+
+    __ ld(R11_scratch1, 0, R1_SP);
+    __ std(R0/*mirror*/, _ijava_state_neg(oop_tmp), R11_scratch1);
+    // R4_ARG2 = &state->_oop_temp;
+    __ addi(R4_ARG2, R11_scratch1, _ijava_state_neg(oop_tmp));
+    __ BIND(method_is_not_static);
+  }
+
+  // At this point, arguments have been copied off the stack into
+  // their JNI positions. Oops are boxed in-place on the stack, with
+  // handles copied to arguments. The result handler address is in a
+  // register.
+
+  // Pass JNIEnv address as first parameter.
+  __ addir(R3_ARG1, thread_(jni_environment));
+
+  // Load the native_method entry before we change the thread state.
+  __ ld(native_method_fd, method_(native_function));
+
+  //=============================================================================
+  // Transition from _thread_in_Java to _thread_in_native. As soon as
+  // we make this change the safepoint code needs to be certain that
+  // the last Java frame we established is good. The pc in that frame
+  // just needs to be near here not an actual return address.
+
+  // We use release_store_fence to update values like the thread state, where
+  // we don't want the current thread to continue until all our prior memory
+  // accesses (including the new thread state) are visible to other threads.
+  __ li(R0, _thread_in_native);
+  __ release();
+
+  // TODO PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
+  __ stw(R0, thread_(thread_state));
+
+  if (UseMembar) {
+    __ fence();
+  }
+
+  //=============================================================================
+  // Call the native method. Argument registers must not have been
+  // overwritten since "__ call_stub(signature_handler);" (except for
+  // ARG1 and ARG2 for static methods).
+  __ call_c(native_method_fd);
+
+  __ li(R0, 0);
+  __ ld(R11_scratch1, 0, R1_SP);
+  __ std(R3_RET, _ijava_state_neg(lresult), R11_scratch1);
+  __ stfd(F1_RET, _ijava_state_neg(fresult), R11_scratch1);
+  __ std(R0/*mirror*/, _ijava_state_neg(oop_tmp), R11_scratch1); // reset
+
+  // Note: C++ interpreter needs the following here:
+  // The frame_manager_lr field, which we use for setting the last
+  // java frame, gets overwritten by the signature handler. Restore
+  // it now.
+  //__ get_PC_trash_LR(R11_scratch1);
+  //__ std(R11_scratch1, _top_ijava_frame_abi(frame_manager_lr), R1_SP);
+
+  // Because of GC R19_method may no longer be valid.
+
+  // Block, if necessary, before resuming in _thread_in_Java state.
+  // In order for GC to work, don't clear the last_Java_sp until after
+  // blocking.
+
+  //=============================================================================
+  // Switch thread to "native transition" state before reading the
+  // synchronization state. This additional state is necessary
+  // because reading and testing the synchronization state is not
+  // atomic w.r.t. GC, as this scenario demonstrates: Java thread A,
+  // in _thread_in_native state, loads _not_synchronized and is
+  // preempted. VM thread changes sync state to synchronizing and
+  // suspends threads for GC. Thread A is resumed to finish this
+  // native method, but doesn't block here since it didn't see any
+  // synchronization in progress, and escapes.
+
+  // We use release_store_fence to update values like the thread state, where
+  // we don't want the current thread to continue until all our prior memory
+  // accesses (including the new thread state) are visible to other threads.
+  __ li(R0/*thread_state*/, _thread_in_native_trans);
+  __ release();
+  __ stw(R0/*thread_state*/, thread_(thread_state));
+  if (UseMembar) {
+    __ fence();
+  }
+  // Write serialization page so that the VM thread can do a pseudo remote
+  // membar. We use the current thread pointer to calculate a thread
+  // specific offset to write to within the page. This minimizes bus
+  // traffic due to cache line collision.
+  else {
+    __ serialize_memory(R16_thread, R11_scratch1, R12_scratch2);
+  }
+
+  // Now before we return to java we must look for a current safepoint
+  // (a new safepoint can not start since we entered native_trans).
+  // We must check here because a current safepoint could be modifying
+  // the callers registers right this moment.
+
+  // Acquire isn't strictly necessary here because of the fence, but
+  // sync_state is declared to be volatile, so we do it anyway
+  // (cmp-br-isync on one path, release (same as acquire on PPC64) on the other path).
+  int sync_state_offs = __ load_const_optimized(sync_state_addr, SafepointSynchronize::address_of_state(), /*temp*/R0, true);
+
+  // TODO PPC port assert(4 == SafepointSynchronize::sz_state(), "unexpected field size");
+  __ lwz(sync_state, sync_state_offs, sync_state_addr);
+
+  // TODO PPC port assert(4 == Thread::sz_suspend_flags(), "unexpected field size");
+  __ lwz(suspend_flags, thread_(suspend_flags));
+
+  Label sync_check_done;
+  Label do_safepoint;
+  // No synchronization in progress nor yet synchronized.
+  __ cmpwi(CCR0, sync_state, SafepointSynchronize::_not_synchronized);
+  // Not suspended.
+  __ cmpwi(CCR1, suspend_flags, 0);
+
+  __ bne(CCR0, do_safepoint);
+  __ beq(CCR1, sync_check_done);
+  __ bind(do_safepoint);
+  __ isync();
+  // Block. We do the call directly and leave the current
+  // last_Java_frame setup undisturbed. We must save any possible
+  // native result across the call. No oop is present.
+
+  __ mr(R3_ARG1, R16_thread);
+  __ call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, JavaThread::check_special_condition_for_native_trans),
+            relocInfo::none);
+
+  __ bind(sync_check_done);
+
+  //=============================================================================
+  // <<<<<< Back in Interpreter Frame >>>>>
+
+  // We are in thread_in_native_trans here and back in the normal
+  // interpreter frame. We don't have to do anything special about
+  // safepoints and we can switch to Java mode anytime we are ready.
+
+  // Note: frame::interpreter_frame_result has a dependency on how the
+  // method result is saved across the call to post_method_exit. For
+  // native methods it assumes that the non-FPU/non-void result is
+  // saved in _native_lresult and a FPU result in _native_fresult. If
+  // this changes then the interpreter_frame_result implementation
+  // will need to be updated too.
+
+  // On PPC64, we have stored the result directly after the native call.
+
+  //=============================================================================
+  // Back in Java
+
+  // We use release_store_fence to update values like the thread state, where
+  // we don't want the current thread to continue until all our prior memory
+  // accesses (including the new thread state) are visible to other threads.
+  __ li(R0/*thread_state*/, _thread_in_Java);
+  __ release();
+  __ stw(R0/*thread_state*/, thread_(thread_state));
+  if (UseMembar) {
+    __ fence();
+  }
+
+  __ reset_last_Java_frame();
+
+  // Jvmdi/jvmpi support. Whether we've got an exception pending or
+  // not, and whether unlocking throws an exception or not, we notify
+  // on native method exit. If we do have an exception, we'll end up
+  // in the caller's context to handle it, so if we don't do the
+  // notify here, we'll drop it on the floor.
+  __ notify_method_exit(true/*native method*/,
+                        ilgl /*illegal state (not used for native methods)*/,
+                        InterpreterMacroAssembler::NotifyJVMTI,
+                        false /*check_exceptions*/);
+
+  //=============================================================================
+  // Handle exceptions
+
+  if (synchronized) {
+    // Don't check for exceptions since we're still in the i2n frame. Do that
+    // manually afterwards.
+    unlock_method(false);
+  }
+
+  // Reset active handles after returning from native.
+  // thread->active_handles()->clear();
+  __ ld(active_handles, thread_(active_handles));
+  // TODO PPC port assert(4 == JNIHandleBlock::top_size_in_bytes(), "unexpected field size");
+  __ li(R0, 0);
+  __ stw(R0, JNIHandleBlock::top_offset_in_bytes(), active_handles);
+
+  Label exception_return_sync_check_already_unlocked;
+  __ ld(R0/*pending_exception*/, thread_(pending_exception));
+  __ cmpdi(CCR0, R0/*pending_exception*/, 0);
+  __ bne(CCR0, exception_return_sync_check_already_unlocked);
+
+  //-----------------------------------------------------------------------------
+  // No exception pending.
+
+  // Move native method result back into proper registers and return.
+  // Invoke result handler (may unbox/promote).
+  __ ld(R11_scratch1, 0, R1_SP);
+  __ ld(R3_RET, _ijava_state_neg(lresult), R11_scratch1);
+  __ lfd(F1_RET, _ijava_state_neg(fresult), R11_scratch1);
+  __ call_stub(result_handler_addr);
+
+  __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ R0, R11_scratch1, R12_scratch2);
+
+  // Must use the return pc which was loaded from the caller's frame
+  // as the VM uses return-pc-patching for deoptimization.
+  __ mtlr(R0);
+  __ blr();
+
+  //-----------------------------------------------------------------------------
+  // An exception is pending. We call into the runtime only if the
+  // caller was not interpreted. If it was interpreted the
+  // interpreter will do the correct thing. If it isn't interpreted
+  // (call stub/compiled code) we will change our return and continue.
+
+  __ BIND(exception_return_sync_check);
+
+  if (synchronized) {
+    // Don't check for exceptions since we're still in the i2n frame. Do that
+    // manually afterwards.
+    unlock_method(false);
+  }
+  __ BIND(exception_return_sync_check_already_unlocked);
+
+  const Register return_pc = R31;
+
+  __ ld(return_pc, 0, R1_SP);
+  __ ld(return_pc, _abi(lr), return_pc);
+
+  // Get the address of the exception handler.
+  __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address),
+                  R16_thread,
+                  return_pc /* return pc */);
+  __ merge_frames(/*top_frame_sp*/ R21_sender_SP, noreg, R11_scratch1, R12_scratch2);
+
+  // Load the PC of the the exception handler into LR.
+  __ mtlr(R3_RET);
+
+  // Load exception into R3_ARG1 and clear pending exception in thread.
+  __ ld(R3_ARG1/*exception*/, thread_(pending_exception));
+  __ li(R4_ARG2, 0);
+  __ std(R4_ARG2, thread_(pending_exception));
+
+  // Load the original return pc into R4_ARG2.
+  __ mr(R4_ARG2/*issuing_pc*/, return_pc);
+
+  // Return to exception handler.
+  __ blr();
+
+  //=============================================================================
+  // Counter overflow.
+
+  if (inc_counter) {
+    // Handle invocation counter overflow.
+    __ bind(invocation_counter_overflow);
+
+    generate_counter_overflow(continue_after_compile);
+  }
+
+  return entry;
+}
+
+// Generic interpreted method entry to (asm) interpreter.
+//
+address TemplateInterpreterGenerator::generate_normal_entry(bool synchronized) {
+  bool inc_counter = UseCompiler || CountCompiledCalls;
+  address entry = __ pc();
+  // Generate the code to allocate the interpreter stack frame.
+  Register Rsize_of_parameters = R4_ARG2, // Written by generate_fixed_frame.
+           Rsize_of_locals     = R5_ARG3; // Written by generate_fixed_frame.
+
+  generate_fixed_frame(false, Rsize_of_parameters, Rsize_of_locals);
+
+#ifdef FAST_DISPATCH
+  __ unimplemented("Fast dispatch in generate_normal_entry");
+#if 0
+  __ set((intptr_t)Interpreter::dispatch_table(), IdispatchTables);
+  // Set bytecode dispatch table base.
+#endif
+#endif
+
+  // --------------------------------------------------------------------------
+  // Zero out non-parameter locals.
+  // Note: *Always* zero out non-parameter locals as Sparc does. It's not
+  // worth to ask the flag, just do it.
+  Register Rslot_addr = R6_ARG4,
+           Rnum       = R7_ARG5;
+  Label Lno_locals, Lzero_loop;
+
+  // Set up the zeroing loop.
+  __ subf(Rnum, Rsize_of_parameters, Rsize_of_locals);
+  __ subf(Rslot_addr, Rsize_of_parameters, R18_locals);
+  __ srdi_(Rnum, Rnum, Interpreter::logStackElementSize);
+  __ beq(CCR0, Lno_locals);
+  __ li(R0, 0);
+  __ mtctr(Rnum);
+
+  // The zero locals loop.
+  __ bind(Lzero_loop);
+  __ std(R0, 0, Rslot_addr);
+  __ addi(Rslot_addr, Rslot_addr, -Interpreter::stackElementSize);
+  __ bdnz(Lzero_loop);
+
+  __ bind(Lno_locals);
+
+  // --------------------------------------------------------------------------
+  // Counter increment and overflow check.
+  Label invocation_counter_overflow,
+        profile_method,
+        profile_method_continue;
+  if (inc_counter || ProfileInterpreter) {
+
+    Register Rdo_not_unlock_if_synchronized_addr = R11_scratch1;
+    if (synchronized) {
+      // Since at this point in the method invocation the exception handler
+      // would try to exit the monitor of synchronized methods which hasn't
+      // been entered yet, we set the thread local variable
+      // _do_not_unlock_if_synchronized to true. If any exception was thrown by
+      // runtime, exception handling i.e. unlock_if_synchronized_method will
+      // check this thread local flag.
+      // This flag has two effects, one is to force an unwind in the topmost
+      // interpreter frame and not perform an unlock while doing so.
+      __ li(R0, 1);
+      __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
+    }
+    // Increment invocation counter and check for overflow.
+    if (inc_counter) {
+      generate_counter_incr(&invocation_counter_overflow, &profile_method, &profile_method_continue);
+    }
+
+    __ bind(profile_method_continue);
+
+    // Reset the _do_not_unlock_if_synchronized flag.
+    if (synchronized) {
+      __ li(R0, 0);
+      __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
+    }
+  }
+
+  // --------------------------------------------------------------------------
+  // Locking of synchronized methods. Must happen AFTER invocation_counter
+  // check and stack overflow check, so method is not locked if overflows.
+  if (synchronized) {
+    lock_method(R3_ARG1, R4_ARG2, R5_ARG3);
+  }
+#ifdef ASSERT
+  else {
+    Label Lok;
+    __ lwz(R0, in_bytes(Method::access_flags_offset()), R19_method);
+    __ andi_(R0, R0, JVM_ACC_SYNCHRONIZED);
+    __ asm_assert_eq("method needs synchronization", 0x8521);
+    __ bind(Lok);
+  }
+#endif // ASSERT
+
+  __ verify_thread();
+
+  // --------------------------------------------------------------------------
+  // JVMTI support
+  __ notify_method_entry();
+
+  // --------------------------------------------------------------------------
+  // Start executing instructions.
+  __ dispatch_next(vtos);
+
+  // --------------------------------------------------------------------------
+  // Out of line counter overflow and MDO creation code.
+  if (ProfileInterpreter) {
+    // We have decided to profile this method in the interpreter.
+    __ bind(profile_method);
+    __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::profile_method));
+    __ set_method_data_pointer_for_bcp();
+    __ b(profile_method_continue);
+  }
+
+  if (inc_counter) {
+    // Handle invocation counter overflow.
+    __ bind(invocation_counter_overflow);
+    generate_counter_overflow(profile_method_continue);
+  }
+  return entry;
+}
+
+// =============================================================================
+// Entry points
+
+address AbstractInterpreterGenerator::generate_method_entry(
+                                        AbstractInterpreter::MethodKind kind) {
+  // Determine code generation flags.
+  bool synchronized = false;
+  address entry_point = NULL;
+
+  switch (kind) {
+  case Interpreter::zerolocals             :                                                                             break;
+  case Interpreter::zerolocals_synchronized: synchronized = true;                                                        break;
+  case Interpreter::native                 : entry_point = ((InterpreterGenerator*) this)->generate_native_entry(false); break;
+  case Interpreter::native_synchronized    : entry_point = ((InterpreterGenerator*) this)->generate_native_entry(true);  break;
+  case Interpreter::empty                  : entry_point = ((InterpreterGenerator*) this)->generate_empty_entry();       break;
+  case Interpreter::accessor               : entry_point = ((InterpreterGenerator*) this)->generate_accessor_entry();    break;
+  case Interpreter::abstract               : entry_point = ((InterpreterGenerator*) this)->generate_abstract_entry();    break;
+
+  case Interpreter::java_lang_math_sin     : // fall thru
+  case Interpreter::java_lang_math_cos     : // fall thru
+  case Interpreter::java_lang_math_tan     : // fall thru
+  case Interpreter::java_lang_math_abs     : // fall thru
+  case Interpreter::java_lang_math_log     : // fall thru
+  case Interpreter::java_lang_math_log10   : // fall thru
+  case Interpreter::java_lang_math_sqrt    : // fall thru
+  case Interpreter::java_lang_math_pow     : // fall thru
+  case Interpreter::java_lang_math_exp     : entry_point = ((InterpreterGenerator*) this)->generate_math_entry(kind);    break;
+  case Interpreter::java_lang_ref_reference_get
+                                           : entry_point = ((InterpreterGenerator*)this)->generate_Reference_get_entry(); break;
+  default                                  : ShouldNotReachHere();                                                       break;
+  }
+
+  if (entry_point) {
+    return entry_point;
+  }
+
+  return ((InterpreterGenerator*) this)->generate_normal_entry(synchronized);
+}
+
+// These should never be compiled since the interpreter will prefer
+// the compiled version to the intrinsic version.
+bool AbstractInterpreter::can_be_compiled(methodHandle m) {
+  return !math_entry_available(method_kind(m));
+}
+
+// How much stack a method activation needs in stack slots.
+// We must calc this exactly like in generate_fixed_frame.
+// Note: This returns the conservative size assuming maximum alignment.
+int AbstractInterpreter::size_top_interpreter_activation(Method* method) {
+  const int max_alignment_size = 2;
+  const int abi_scratch = frame::abi_reg_args_size;
+  return method->max_locals() + method->max_stack() + frame::interpreter_frame_monitor_size() + max_alignment_size + abi_scratch;
+}
+
+// Fills a sceletal interpreter frame generated during deoptimizations
+// and returns the frame size in slots.
+//
+// Parameters:
+//
+// interpreter_frame == NULL:
+//   Only calculate the size of an interpreter activation, no actual layout.
+//   Note: This calculation must exactly parallel the frame setup
+//   in TemplateInterpreter::generate_normal_entry. But it does not
+//   account for the SP alignment, that might further enhance the
+//   frame size, depending on FP.
+//
+// interpreter_frame != NULL:
+//   set up the method, locals, and monitors.
+//   The frame interpreter_frame, if not NULL, is guaranteed to be the
+//   right size, as determined by a previous call to this method.
+//   It is also guaranteed to be walkable even though it is in a skeletal state
+//
+// is_top_frame == true:
+//   We're processing the *oldest* interpreter frame!
+//
+// pop_frame_extra_args:
+//   If this is != 0 we are returning to a deoptimized frame by popping
+//   off the callee frame. We want to re-execute the call that called the
+//   callee interpreted, but since the return to the interpreter would pop
+//   the arguments off advance the esp by dummy popframe_extra_args slots.
+//   Popping off those will establish the stack layout as it was before the call.
+//
+int AbstractInterpreter::layout_activation(Method* method,
+                                           int tempcount,
+                                           int popframe_extra_args,
+                                           int moncount,
+                                           int caller_actual_parameters,
+                                           int callee_param_count,
+                                           int callee_locals,
+                                           frame* caller,
+                                           frame* interpreter_frame,
+                                           bool is_top_frame,
+                                           bool is_bottom_frame) {
+
+  const int max_alignment_space = 2;
+  const int abi_scratch = is_top_frame ? (frame::abi_reg_args_size / Interpreter::stackElementSize) :
+                                         (frame::abi_minframe_size / Interpreter::stackElementSize) ;
+  const int conservative_framesize_in_slots =
+    method->max_stack() + callee_locals - callee_param_count +
+    (moncount * frame::interpreter_frame_monitor_size()) + max_alignment_space +
+    abi_scratch + frame::ijava_state_size / Interpreter::stackElementSize;
+
+  assert(!is_top_frame || conservative_framesize_in_slots * 8 > frame::abi_reg_args_size + frame::ijava_state_size, "frame too small");
+
+  if (interpreter_frame == NULL) {
+    // Since we don't know the exact alignment, we return the conservative size.
+    return (conservative_framesize_in_slots & -2);
+  } else {
+    // Now we know our caller, calc the exact frame layout and size.
+    intptr_t* locals_base  = (caller->is_interpreted_frame()) ?
+      caller->interpreter_frame_esp() + caller_actual_parameters :
+      caller->sp() + method->max_locals() - 1 + (frame::abi_minframe_size / Interpreter::stackElementSize) ;
+
+    intptr_t* monitor_base = caller->sp() - frame::ijava_state_size / Interpreter::stackElementSize ;
+    intptr_t* monitor      = monitor_base - (moncount * frame::interpreter_frame_monitor_size());
+    intptr_t* esp_base     = monitor - 1;
+    intptr_t* esp          = esp_base - tempcount - popframe_extra_args;
+    intptr_t* sp           = (intptr_t *) (((intptr_t) (esp_base- callee_locals + callee_param_count - method->max_stack()- abi_scratch)) & -StackAlignmentInBytes);
+    intptr_t* sender_sp    = caller->sp() + (frame::abi_minframe_size - frame::abi_reg_args_size) / Interpreter::stackElementSize;
+    intptr_t* top_frame_sp = is_top_frame ? sp : sp + (frame::abi_minframe_size - frame::abi_reg_args_size) / Interpreter::stackElementSize;
+
+    interpreter_frame->interpreter_frame_set_method(method);
+    interpreter_frame->interpreter_frame_set_locals(locals_base);
+    interpreter_frame->interpreter_frame_set_cpcache(method->constants()->cache());
+    interpreter_frame->interpreter_frame_set_esp(esp);
+    interpreter_frame->interpreter_frame_set_monitor_end((BasicObjectLock *)monitor);
+    interpreter_frame->interpreter_frame_set_top_frame_sp(top_frame_sp);
+    if (!is_bottom_frame) {
+      interpreter_frame->interpreter_frame_set_sender_sp(sender_sp);
+    }
+
+    int framesize_in_slots = caller->sp() - sp;
+    assert(!is_top_frame ||framesize_in_slots >= (frame::abi_reg_args_size / Interpreter::stackElementSize) + frame::ijava_state_size / Interpreter::stackElementSize, "frame too small");
+    assert(framesize_in_slots <= conservative_framesize_in_slots, "exact frame size must be smaller than the convervative size!");
+    return framesize_in_slots;
+  }
+}
+
+// =============================================================================
+// Exceptions
+
+void TemplateInterpreterGenerator::generate_throw_exception() {
+  Register Rexception    = R17_tos,
+           Rcontinuation = R3_RET;
+
+  // --------------------------------------------------------------------------
+  // Entry point if an method returns with a pending exception (rethrow).
+  Interpreter::_rethrow_exception_entry = __ pc();
+  {
+    __ restore_interpreter_state(R11_scratch1); // Sets R11_scratch1 = fp.
+    __ ld(R12_scratch2, _ijava_state_neg(top_frame_sp), R11_scratch1);
+    __ resize_frame_absolute(R12_scratch2, R11_scratch1, R0);
+
+    // Compiled code destroys templateTableBase, reload.
+    __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
+  }
+
+  // Entry point if a interpreted method throws an exception (throw).
+  Interpreter::_throw_exception_entry = __ pc();
+  {
+    __ mr(Rexception, R3_RET);
+
+    __ verify_thread();
+    __ verify_oop(Rexception);
+
+    // Expression stack must be empty before entering the VM in case of an exception.
+    __ empty_expression_stack();
+    // Find exception handler address and preserve exception oop.
+    // Call C routine to find handler and jump to it.
+    __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::exception_handler_for_exception), Rexception);
+    __ mtctr(Rcontinuation);
+    // Push exception for exception handler bytecodes.
+    __ push_ptr(Rexception);
+
+    // Jump to exception handler (may be remove activation entry!).
+    __ bctr();
+  }
+
+  // If the exception is not handled in the current frame the frame is
+  // removed and the exception is rethrown (i.e. exception
+  // continuation is _rethrow_exception).
+  //
+  // Note: At this point the bci is still the bxi for the instruction
+  // which caused the exception and the expression stack is
+  // empty. Thus, for any VM calls at this point, GC will find a legal
+  // oop map (with empty expression stack).
+
+  // In current activation
+  // tos: exception
+  // bcp: exception bcp
+
+  // --------------------------------------------------------------------------
+  // JVMTI PopFrame support
+
+  Interpreter::_remove_activation_preserving_args_entry = __ pc();
+  {
+    // Set the popframe_processing bit in popframe_condition indicating that we are
+    // currently handling popframe, so that call_VMs that may happen later do not
+    // trigger new popframe handling cycles.
+    __ lwz(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
+    __ ori(R11_scratch1, R11_scratch1, JavaThread::popframe_processing_bit);
+    __ stw(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
+
+    // Empty the expression stack, as in normal exception handling.
+    __ empty_expression_stack();
+    __ unlock_if_synchronized_method(vtos, /* throw_monitor_exception */ false, /* install_monitor_exception */ false);
+
+    // Check to see whether we are returning to a deoptimized frame.
+    // (The PopFrame call ensures that the caller of the popped frame is
+    // either interpreted or compiled and deoptimizes it if compiled.)
+    // Note that we don't compare the return PC against the
+    // deoptimization blob's unpack entry because of the presence of
+    // adapter frames in C2.
+    Label Lcaller_not_deoptimized;
+    Register return_pc = R3_ARG1;
+    __ ld(return_pc, 0, R1_SP);
+    __ ld(return_pc, _abi(lr), return_pc);
+    __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::interpreter_contains), return_pc);
+    __ cmpdi(CCR0, R3_RET, 0);
+    __ bne(CCR0, Lcaller_not_deoptimized);
+
+    // The deoptimized case.
+    // In this case, we can't call dispatch_next() after the frame is
+    // popped, but instead must save the incoming arguments and restore
+    // them after deoptimization has occurred.
+    __ ld(R4_ARG2, in_bytes(Method::const_offset()), R19_method);
+    __ lhz(R4_ARG2 /* number of params */, in_bytes(ConstMethod::size_of_parameters_offset()), R4_ARG2);
+    __ slwi(R4_ARG2, R4_ARG2, Interpreter::logStackElementSize);
+    __ addi(R5_ARG3, R18_locals, Interpreter::stackElementSize);
+    __ subf(R5_ARG3, R4_ARG2, R5_ARG3);
+    // Save these arguments.
+    __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::popframe_preserve_args), R16_thread, R4_ARG2, R5_ARG3);
+
+    // Inform deoptimization that it is responsible for restoring these arguments.
+    __ load_const_optimized(R11_scratch1, JavaThread::popframe_force_deopt_reexecution_bit);
+    __ stw(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
+
+    // Return from the current method into the deoptimization blob. Will eventually
+    // end up in the deopt interpeter entry, deoptimization prepared everything that
+    // we will reexecute the call that called us.
+    __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*reload return_pc*/ return_pc, R11_scratch1, R12_scratch2);
+    __ mtlr(return_pc);
+    __ blr();
+
+    // The non-deoptimized case.
+    __ bind(Lcaller_not_deoptimized);
+
+    // Clear the popframe condition flag.
+    __ li(R0, 0);
+    __ stw(R0, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
+
+    // Get out of the current method and re-execute the call that called us.
+    __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ return_pc, R11_scratch1, R12_scratch2);
+    __ restore_interpreter_state(R11_scratch1);
+    __ ld(R12_scratch2, _ijava_state_neg(top_frame_sp), R11_scratch1);
+    __ resize_frame_absolute(R12_scratch2, R11_scratch1, R0);
+    __ mtlr(return_pc);
+    if (ProfileInterpreter) {
+      __ set_method_data_pointer_for_bcp();
+    }
+    __ dispatch_next(vtos);
+  }
+  // end of JVMTI PopFrame support
+
+  // --------------------------------------------------------------------------
+  // Remove activation exception entry.
+  // This is jumped to if an interpreted method can't handle an exception itself
+  // (we come from the throw/rethrow exception entry above). We're going to call
+  // into the VM to find the exception handler in the caller, pop the current
+  // frame and return the handler we calculated.
+  Interpreter::_remove_activation_entry = __ pc();
+  {
+    __ pop_ptr(Rexception);
+    __ verify_thread();
+    __ verify_oop(Rexception);
+    __ std(Rexception, in_bytes(JavaThread::vm_result_offset()), R16_thread);
+
+    __ unlock_if_synchronized_method(vtos, /* throw_monitor_exception */ false, true);
+    __ notify_method_exit(false, vtos, InterpreterMacroAssembler::SkipNotifyJVMTI, false);
+
+    __ get_vm_result(Rexception);
+
+    // We are done with this activation frame; find out where to go next.
+    // The continuation point will be an exception handler, which expects
+    // the following registers set up:
+    //
+    // RET:  exception oop
+    // ARG2: Issuing PC (see generate_exception_blob()), only used if the caller is compiled.
+
+    Register return_pc = R31; // Needs to survive the runtime call.
+    __ ld(return_pc, 0, R1_SP);
+    __ ld(return_pc, _abi(lr), return_pc);
+    __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), R16_thread, return_pc);
+
+    // Remove the current activation.
+    __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ noreg, R11_scratch1, R12_scratch2);
+
+    __ mr(R4_ARG2, return_pc);
+    __ mtlr(R3_RET);
+    __ mr(R3_RET, Rexception);
+    __ blr();
+  }
+}
+
+// JVMTI ForceEarlyReturn support.
+// Returns "in the middle" of a method with a "fake" return value.
+address TemplateInterpreterGenerator::generate_earlyret_entry_for(TosState state) {
+
+  Register Rscratch1 = R11_scratch1,
+           Rscratch2 = R12_scratch2;
+
+  address entry = __ pc();
+  __ empty_expression_stack();
+
+  __ load_earlyret_value(state, Rscratch1);
+
+  __ ld(Rscratch1, in_bytes(JavaThread::jvmti_thread_state_offset()), R16_thread);
+  // Clear the earlyret state.
+  __ li(R0, 0);
+  __ stw(R0, in_bytes(JvmtiThreadState::earlyret_state_offset()), Rscratch1);
+
+  __ remove_activation(state, false, false);
+  // Copied from TemplateTable::_return.
+  // Restoration of lr done by remove_activation.
+  switch (state) {
+    case ltos:
+    case btos:
+    case ctos:
+    case stos:
+    case atos:
+    case itos: __ mr(R3_RET, R17_tos); break;
+    case ftos:
+    case dtos: __ fmr(F1_RET, F15_ftos); break;
+    case vtos: // This might be a constructor. Final fields (and volatile fields on PPC64) need
+               // to get visible before the reference to the object gets stored anywhere.
+               __ membar(Assembler::StoreStore); break;
+    default  : ShouldNotReachHere();
+  }
+  __ blr();
+
+  return entry;
+} // end of ForceEarlyReturn support
+
+//-----------------------------------------------------------------------------
+// Helper for vtos entry point generation
+
+void TemplateInterpreterGenerator::set_vtos_entry_points(Template* t,
+                                                         address& bep,
+                                                         address& cep,
+                                                         address& sep,
+                                                         address& aep,
+                                                         address& iep,
+                                                         address& lep,
+                                                         address& fep,
+                                                         address& dep,
+                                                         address& vep) {
+  assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
+  Label L;
+
+  aep = __ pc();  __ push_ptr();  __ b(L);
+  fep = __ pc();  __ push_f();    __ b(L);
+  dep = __ pc();  __ push_d();    __ b(L);
+  lep = __ pc();  __ push_l();    __ b(L);
+  __ align(32, 12, 24); // align L
+  bep = cep = sep =
+  iep = __ pc();  __ push_i();
+  vep = __ pc();
+  __ bind(L);
+  generate_and_dispatch(t);
+}
+
+//-----------------------------------------------------------------------------
+// Generation of individual instructions
+
+// helpers for generate_and_dispatch
+
+InterpreterGenerator::InterpreterGenerator(StubQueue* code)
+  : TemplateInterpreterGenerator(code) {
+  generate_all(); // Down here so it can be "virtual".
+}
+
+//-----------------------------------------------------------------------------
+
+// Non-product code
+#ifndef PRODUCT
+address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
+  //__ flush_bundle();
+  address entry = __ pc();
+
+  char *bname = NULL;
+  uint tsize = 0;
+  switch(state) {
+  case ftos:
+    bname = "trace_code_ftos {";
+    tsize = 2;
+    break;
+  case btos:
+    bname = "trace_code_btos {";
+    tsize = 2;
+    break;
+  case ctos:
+    bname = "trace_code_ctos {";
+    tsize = 2;
+    break;
+  case stos:
+    bname = "trace_code_stos {";
+    tsize = 2;
+    break;
+  case itos:
+    bname = "trace_code_itos {";
+    tsize = 2;
+    break;
+  case ltos:
+    bname = "trace_code_ltos {";
+    tsize = 3;
+    break;
+  case atos:
+    bname = "trace_code_atos {";
+    tsize = 2;
+    break;
+  case vtos:
+    // Note: In case of vtos, the topmost of stack value could be a int or doubl
+    // In case of a double (2 slots) we won't see the 2nd stack value.
+    // Maybe we simply should print the topmost 3 stack slots to cope with the problem.
+    bname = "trace_code_vtos {";
+    tsize = 2;
+
+    break;
+  case dtos:
+    bname = "trace_code_dtos {";
+    tsize = 3;
+    break;
+  default:
+    ShouldNotReachHere();
+  }
+  BLOCK_COMMENT(bname);
+
+  // Support short-cut for TraceBytecodesAt.
+  // Don't call into the VM if we don't want to trace to speed up things.
+  Label Lskip_vm_call;
+  if (TraceBytecodesAt > 0 && TraceBytecodesAt < max_intx) {
+    int offs1 = __ load_const_optimized(R11_scratch1, (address) &TraceBytecodesAt, R0, true);
+    int offs2 = __ load_const_optimized(R12_scratch2, (address) &BytecodeCounter::_counter_value, R0, true);
+    __ ld(R11_scratch1, offs1, R11_scratch1);
+    __ lwa(R12_scratch2, offs2, R12_scratch2);
+    __ cmpd(CCR0, R12_scratch2, R11_scratch1);
+    __ blt(CCR0, Lskip_vm_call);
+  }
+
+  __ push(state);
+  // Load 2 topmost expression stack values.
+  __ ld(R6_ARG4, tsize*Interpreter::stackElementSize, R15_esp);
+  __ ld(R5_ARG3, Interpreter::stackElementSize, R15_esp);
+  __ mflr(R31);
+  __ call_VM(noreg, CAST_FROM_FN_PTR(address, SharedRuntime::trace_bytecode), /* unused */ R4_ARG2, R5_ARG3, R6_ARG4, false);
+  __ mtlr(R31);
+  __ pop(state);
+
+  if (TraceBytecodesAt > 0 && TraceBytecodesAt < max_intx) {
+    __ bind(Lskip_vm_call);
+  }
+  __ blr();
+  BLOCK_COMMENT("} trace_code");
+  return entry;
+}
+
+void TemplateInterpreterGenerator::count_bytecode() {
+  int offs = __ load_const_optimized(R11_scratch1, (address) &BytecodeCounter::_counter_value, R12_scratch2, true);
+  __ lwz(R12_scratch2, offs, R11_scratch1);
+  __ addi(R12_scratch2, R12_scratch2, 1);
+  __ stw(R12_scratch2, offs, R11_scratch1);
+}
+
+void TemplateInterpreterGenerator::histogram_bytecode(Template* t) {
+  int offs = __ load_const_optimized(R11_scratch1, (address) &BytecodeHistogram::_counters[t->bytecode()], R12_scratch2, true);
+  __ lwz(R12_scratch2, offs, R11_scratch1);
+  __ addi(R12_scratch2, R12_scratch2, 1);
+  __ stw(R12_scratch2, offs, R11_scratch1);
+}
+
+void TemplateInterpreterGenerator::histogram_bytecode_pair(Template* t) {
+  const Register addr = R11_scratch1,
+                 tmp  = R12_scratch2;
+  // Get index, shift out old bytecode, bring in new bytecode, and store it.
+  // _index = (_index >> log2_number_of_codes) |
+  //          (bytecode << log2_number_of_codes);
+  int offs1 = __ load_const_optimized(addr, (address)&BytecodePairHistogram::_index, tmp, true);
+  __ lwz(tmp, offs1, addr);
+  __ srwi(tmp, tmp, BytecodePairHistogram::log2_number_of_codes);
+  __ ori(tmp, tmp, ((int) t->bytecode()) << BytecodePairHistogram::log2_number_of_codes);
+  __ stw(tmp, offs1, addr);
+
+  // Bump bucket contents.
+  // _counters[_index] ++;
+  int offs2 = __ load_const_optimized(addr, (address)&BytecodePairHistogram::_counters, R0, true);
+  __ sldi(tmp, tmp, LogBytesPerInt);
+  __ add(addr, tmp, addr);
+  __ lwz(tmp, offs2, addr);
+  __ addi(tmp, tmp, 1);
+  __ stw(tmp, offs2, addr);
+}
+
+void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
+  // Call a little run-time stub to avoid blow-up for each bytecode.
+  // The run-time runtime saves the right registers, depending on
+  // the tosca in-state for the given template.
+
+  assert(Interpreter::trace_code(t->tos_in()) != NULL,
+         "entry must have been generated");
+
+  // Note: we destroy LR here.
+  __ bl(Interpreter::trace_code(t->tos_in()));
+}
+
+void TemplateInterpreterGenerator::stop_interpreter_at() {
+  Label L;
+  int offs1 = __ load_const_optimized(R11_scratch1, (address) &StopInterpreterAt, R0, true);
+  int offs2 = __ load_const_optimized(R12_scratch2, (address) &BytecodeCounter::_counter_value, R0, true);
+  __ ld(R11_scratch1, offs1, R11_scratch1);
+  __ lwa(R12_scratch2, offs2, R12_scratch2);
+  __ cmpd(CCR0, R12_scratch2, R11_scratch1);
+  __ bne(CCR0, L);
+  __ illtrap();
+  __ bind(L);
+}
+
+#endif // !PRODUCT
+#endif // !CC_INTERP
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/cpu/ppc/vm/templateInterpreter_ppc.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2013, 2014 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.
+ *
+ */
+
+#ifndef CPU_PPC_VM_TEMPLATEINTERPRETER_PPC_HPP
+#define CPU_PPC_VM_TEMPLATEINTERPRETER_PPC_HPP
+
+ protected:
+
+  // Size of interpreter code.  Increase if too small.  Interpreter will
+  // fail with a guarantee ("not enough space for interpreter generation");
+  // if too small.
+  // Run with +PrintInterpreter to get the VM to print out the size.
+  // Max size with JVMTI
+
+  const static int InterpreterCodeSize = 210*K;
+
+#endif // CPU_PPC_VM_TEMPLATEINTERPRETER_PPC_HPP
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/cpu/ppc/vm/templateTable_ppc_64.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,4082 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2013, 2014 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 "precompiled.hpp"
+#include "asm/macroAssembler.inline.hpp"
+#include "interpreter/interpreter.hpp"
+#include "interpreter/interpreterRuntime.hpp"
+#include "interpreter/templateInterpreter.hpp"
+#include "interpreter/templateTable.hpp"
+#include "memory/universe.inline.hpp"
+#include "oops/objArrayKlass.hpp"
+#include "oops/oop.inline.hpp"
+#include "prims/methodHandles.hpp"
+#include "runtime/sharedRuntime.hpp"
+#include "runtime/stubRoutines.hpp"
+#include "runtime/synchronizer.hpp"
+#include "utilities/macros.hpp"
+
+#ifndef CC_INTERP
+
+#undef __
+#define __ _masm->
+
+// ============================================================================
+// Misc helpers
+
+// Do an oop store like *(base + index) = val OR *(base + offset) = val
+// (only one of both variants is possible at the same time).
+// Index can be noreg.
+// Kills:
+//   Rbase, Rtmp
+static void do_oop_store(InterpreterMacroAssembler* _masm,
+                         Register           Rbase,
+                         RegisterOrConstant offset,
+                         Register           Rval,         // Noreg means always null.
+                         Register           Rtmp1,
+                         Register           Rtmp2,
+                         Register           Rtmp3,
+                         BarrierSet::Name   barrier,
+                         bool               precise,
+                         bool               check_null) {
+  assert_different_registers(Rtmp1, Rtmp2, Rtmp3, Rval, Rbase);
+
+  switch (barrier) {
+#ifndef SERIALGC
+    case BarrierSet::G1SATBCT:
+    case BarrierSet::G1SATBCTLogging:
+      {
+        // Load and record the previous value.
+        __ g1_write_barrier_pre(Rbase, offset,
+                                Rtmp3, /* holder of pre_val ? */
+                                Rtmp1, Rtmp2, false /* frame */);
+
+        Label Lnull, Ldone;
+        if (Rval != noreg) {
+          if (check_null) {
+            __ cmpdi(CCR0, Rval, 0);
+            __ beq(CCR0, Lnull);
+          }
+          __ store_heap_oop_not_null(Rval, offset, Rbase, /*Rval must stay uncompressed.*/ Rtmp1);
+          // Mark the card.
+          if (!(offset.is_constant() && offset.as_constant() == 0) && precise) {
+            __ add(Rbase, offset, Rbase);
+          }
+          __ g1_write_barrier_post(Rbase, Rval, Rtmp1, Rtmp2, Rtmp3, /*filtered (fast path)*/ &Ldone);
+          if (check_null) { __ b(Ldone); }
+        }
+
+        if (Rval == noreg || check_null) { // Store null oop.
+          Register Rnull = Rval;
+          __ bind(Lnull);
+          if (Rval == noreg) {
+            Rnull = Rtmp1;
+            __ li(Rnull, 0);
+          }
+          if (UseCompressedOops) {
+            __ stw(Rnull, offset, Rbase);
+          } else {
+            __ std(Rnull, offset, Rbase);
+          }
+        }
+        __ bind(Ldone);
+      }
+      break;
+#endif // SERIALGC
+    case BarrierSet::CardTableModRef:
+    case BarrierSet::CardTableExtension:
+      {
+        Label Lnull, Ldone;
+        if (Rval != noreg) {
+          if (check_null) {
+            __ cmpdi(CCR0, Rval, 0);
+            __ beq(CCR0, Lnull);
+          }
+          __ store_heap_oop_not_null(Rval, offset, Rbase, /*Rval should better stay uncompressed.*/ Rtmp1);
+          // Mark the card.
+          if (!(offset.is_constant() && offset.as_constant() == 0) && precise) {
+            __ add(Rbase, offset, Rbase);
+          }
+          __ card_write_barrier_post(Rbase, Rval, Rtmp1);
+          if (check_null) {
+            __ b(Ldone);
+          }
+        }
+
+        if (Rval == noreg || check_null) { // Store null oop.
+          Register Rnull = Rval;
+          __ bind(Lnull);
+          if (Rval == noreg) {
+            Rnull = Rtmp1;
+            __ li(Rnull, 0);
+          }
+          if (UseCompressedOops) {
+            __ stw(Rnull, offset, Rbase);
+          } else {
+            __ std(Rnull, offset, Rbase);
+          }
+        }
+        __ bind(Ldone);
+      }
+      break;
+    case BarrierSet::ModRef:
+    case BarrierSet::Other:
+      ShouldNotReachHere();
+      break;
+    default:
+      ShouldNotReachHere();
+  }
+}
+
+// ============================================================================
+// Platform-dependent initialization
+
+void TemplateTable::pd_initialize() {
+  // No ppc64 specific initialization.
+}
+
+Address TemplateTable::at_bcp(int offset) {
+  // Not used on ppc.
+  ShouldNotReachHere();
+  return Address();
+}
+
+// Patches the current bytecode (ptr to it located in bcp)
+// in the bytecode stream with a new one.
+void TemplateTable::patch_bytecode(Bytecodes::Code new_bc, Register Rnew_bc, Register Rtemp, bool load_bc_into_bc_reg /*=true*/, int byte_no) {
+  // With sharing on, may need to test method flag.
+  if (!RewriteBytecodes) return;
+  Label L_patch_done;
+
+  switch (new_bc) {
+    case Bytecodes::_fast_aputfield:
+    case Bytecodes::_fast_bputfield:
+    case Bytecodes::_fast_cputfield:
+    case Bytecodes::_fast_dputfield:
+    case Bytecodes::_fast_fputfield:
+    case Bytecodes::_fast_iputfield:
+    case Bytecodes::_fast_lputfield:
+    case Bytecodes::_fast_sputfield:
+    {
+      // We skip bytecode quickening for putfield instructions when
+      // the put_code written to the constant pool cache is zero.
+      // This is required so that every execution of this instruction
+      // calls out to InterpreterRuntime::resolve_get_put to do
+      // additional, required work.
+      assert(byte_no == f1_byte || byte_no == f2_byte, "byte_no out of range");
+      assert(load_bc_into_bc_reg, "we use bc_reg as temp");
+      __ get_cache_and_index_at_bcp(Rtemp /* dst = cache */, 1);
+      // Big Endian: ((*(cache+indices))>>((1+byte_no)*8))&0xFF
+      __ lbz(Rnew_bc, in_bytes(ConstantPoolCache::base_offset() + ConstantPoolCacheEntry::indices_offset()) + 7 - (1 + byte_no), Rtemp);
+      __ cmpwi(CCR0, Rnew_bc, 0);
+      __ li(Rnew_bc, (unsigned int)(unsigned char)new_bc);
+      __ beq(CCR0, L_patch_done);
+      // __ isync(); // acquire not needed
+      break;
+    }
+
+    default:
+      assert(byte_no == -1, "sanity");
+      if (load_bc_into_bc_reg) {
+        __ li(Rnew_bc, (unsigned int)(unsigned char)new_bc);
+      }
+  }
+
+  if (JvmtiExport::can_post_breakpoint()) {
+    Label L_fast_patch;
+    __ lbz(Rtemp, 0, R14_bcp);
+    __ cmpwi(CCR0, Rtemp, (unsigned int)(unsigned char)Bytecodes::_breakpoint);
+    __ bne(CCR0, L_fast_patch);
+    // Perform the quickening, slowly, in the bowels of the breakpoint table.
+    __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::set_original_bytecode_at), R19_method, R14_bcp, Rnew_bc);
+    __ b(L_patch_done);
+    __ bind(L_fast_patch);
+  }
+
+  // Patch bytecode.
+  __ stb(Rnew_bc, 0, R14_bcp);
+
+  __ bind(L_patch_done);
+}
+
+// ============================================================================
+// Individual instructions
+
+void TemplateTable::nop() {
+  transition(vtos, vtos);
+  // Nothing to do.
+}
+
+void TemplateTable::shouldnotreachhere() {
+  transition(vtos, vtos);
+  __ stop("shouldnotreachhere bytecode");
+}
+
+void TemplateTable::aconst_null() {
+  transition(vtos, atos);
+  __ li(R17_tos, 0);
+}
+
+void TemplateTable::iconst(int value) {
+  transition(vtos, itos);
+  assert(value >= -1 && value <= 5, "");
+  __ li(R17_tos, value);
+}
+
+void TemplateTable::lconst(int value) {
+  transition(vtos, ltos);
+  assert(value >= -1 && value <= 5, "");
+  __ li(R17_tos, value);
+}
+
+void TemplateTable::fconst(int value) {
+  transition(vtos, ftos);
+  static float zero = 0.0;
+  static float one  = 1.0;
+  static float two  = 2.0;
+  switch (value) {
+    default: ShouldNotReachHere();
+    case 0: {
+      int simm16_offset = __ load_const_optimized(R11_scratch1, (address*)&zero, R0);
+      __ lfs(F15_ftos, simm16_offset, R11_scratch1);
+      break;
+    }
+    case 1: {
+      int simm16_offset = __ load_const_optimized(R11_scratch1, (address*)&one, R0);
+      __ lfs(F15_ftos, simm16_offset, R11_scratch1);
+      break;
+    }
+    case 2: {
+      int simm16_offset = __ load_const_optimized(R11_scratch1, (address*)&two, R0);
+      __ lfs(F15_ftos, simm16_offset, R11_scratch1);
+      break;
+    }
+  }
+}
+
+void TemplateTable::dconst(int value) {
+  transition(vtos, dtos);
+  static double zero = 0.0;
+  static double one  = 1.0;
+  switch (value) {
+    case 0: {
+      int simm16_offset = __ load_const_optimized(R11_scratch1, (address*)&zero, R0);
+      __ lfd(F15_ftos, simm16_offset, R11_scratch1);
+      break;
+    }
+    case 1: {
+      int simm16_offset = __ load_const_optimized(R11_scratch1, (address*)&one, R0);
+      __ lfd(F15_ftos, simm16_offset, R11_scratch1);
+      break;
+    }
+    default: ShouldNotReachHere();
+  }
+}
+
+void TemplateTable::bipush() {
+  transition(vtos, itos);
+  __ lbz(R17_tos, 1, R14_bcp);
+  __ extsb(R17_tos, R17_tos);
+}
+
+void TemplateTable::sipush() {
+  transition(vtos, itos);
+  __ get_2_byte_integer_at_bcp(1, R17_tos, InterpreterMacroAssembler::Signed);
+}
+
+void TemplateTable::ldc(bool wide) {
+  Register Rscratch1 = R11_scratch1,
+           Rscratch2 = R12_scratch2,
+           Rcpool    = R3_ARG1;
+
+  transition(vtos, vtos);
+  Label notInt, notClass, exit;
+
+  __ get_cpool_and_tags(Rcpool, Rscratch2); // Set Rscratch2 = &tags.
+  if (wide) { // Read index.
+    __ get_2_byte_integer_at_bcp(1, Rscratch1, InterpreterMacroAssembler::Unsigned);
+  } else {
+    __ lbz(Rscratch1, 1, R14_bcp);
+  }
+
+  const int base_offset = ConstantPool::header_size() * wordSize;
+  const int tags_offset = Array<u1>::base_offset_in_bytes();
+
+  // Get type from tags.
+  __ addi(Rscratch2, Rscratch2, tags_offset);
+  __ lbzx(Rscratch2, Rscratch2, Rscratch1);
+
+  __ cmpwi(CCR0, Rscratch2, JVM_CONSTANT_UnresolvedClass); // Unresolved class?
+  __ cmpwi(CCR1, Rscratch2, JVM_CONSTANT_UnresolvedClassInError); // Unresolved class in error state?
+  __ cror(/*CR0 eq*/2, /*CR1 eq*/4+2, /*CR0 eq*/2);
+
+  // Resolved class - need to call vm to get java mirror of the class.
+  __ cmpwi(CCR1, Rscratch2, JVM_CONSTANT_Class);
+  __ crnor(/*CR0 eq*/2, /*CR1 eq*/4+2, /*CR0 eq*/2); // Neither resolved class nor unresolved case from above?
+  __ beq(CCR0, notClass);
+
+  __ li(R4, wide ? 1 : 0);
+  call_VM(R17_tos, CAST_FROM_FN_PTR(address, InterpreterRuntime::ldc), R4);
+  __ push(atos);
+  __ b(exit);
+
+  __ align(32, 12);
+  __ bind(notClass);
+  __ addi(Rcpool, Rcpool, base_offset);
+  __ sldi(Rscratch1, Rscratch1, LogBytesPerWord);
+  __ cmpdi(CCR0, Rscratch2, JVM_CONSTANT_Integer);
+  __ bne(CCR0, notInt);
+  __ isync(); // Order load of constant wrt. tags.
+  __ lwax(R17_tos, Rcpool, Rscratch1);
+  __ push(itos);
+  __ b(exit);
+
+  __ align(32, 12);
+  __ bind(notInt);
+#ifdef ASSERT
+  // String and Object are rewritten to fast_aldc
+  __ cmpdi(CCR0, Rscratch2, JVM_CONSTANT_Float);
+  __ asm_assert_eq("unexpected type", 0x8765);
+#endif
+  __ isync(); // Order load of constant wrt. tags.
+  __ lfsx(F15_ftos, Rcpool, Rscratch1);
+  __ push(ftos);
+
+  __ align(32, 12);
+  __ bind(exit);
+}
+
+// Fast path for caching oop constants.
+void TemplateTable::fast_aldc(bool wide) {
+  transition(vtos, atos);
+
+  int index_size = wide ? sizeof(u2) : sizeof(u1);
+  const Register Rscratch = R11_scratch1;
+  Label resolved;
+
+  // We are resolved if the resolved reference cache entry contains a
+  // non-null object (CallSite, etc.)
+  __ get_cache_index_at_bcp(Rscratch, 1, index_size);  // Load index.
+  __ load_resolved_reference_at_index(R17_tos, Rscratch);
+  __ cmpdi(CCR0, R17_tos, 0);
+  __ bne(CCR0, resolved);
+  __ load_const_optimized(R3_ARG1, (int)bytecode());
+
+  address entry = CAST_FROM_FN_PTR(address, InterpreterRuntime::resolve_ldc);
+
+  // First time invocation - must resolve first.
+  __ call_VM(R17_tos, entry, R3_ARG1);
+
+  __ align(32, 12);
+  __ bind(resolved);
+  __ verify_oop(R17_tos);
+}
+
+void TemplateTable::ldc2_w() {
+  transition(vtos, vtos);
+  Label Llong, Lexit;
+
+  Register Rindex = R11_scratch1,
+           Rcpool = R12_scratch2,
+           Rtag   = R3_ARG1;
+  __ get_cpool_and_tags(Rcpool, Rtag);
+  __ get_2_byte_integer_at_bcp(1, Rindex, InterpreterMacroAssembler::Unsigned);
+
+  const int base_offset = ConstantPool::header_size() * wordSize;
+  const int tags_offset = Array<u1>::base_offset_in_bytes();
+  // Get type from tags.
+  __ addi(Rcpool, Rcpool, base_offset);
+  __ addi(Rtag, Rtag, tags_offset);
+
+  __ lbzx(Rtag, Rtag, Rindex);
+
+  __ sldi(Rindex, Rindex, LogBytesPerWord);
+  __ cmpdi(CCR0, Rtag, JVM_CONSTANT_Double);
+  __ bne(CCR0, Llong);
+  // A double can be placed at word-aligned locations in the constant pool.
+  // Check out Conversions.java for an example.
+  // Also ConstantPool::header_size() is 20, which makes it very difficult
+  // to double-align double on the constant pool. SG, 11/7/97
+  __ isync(); // Order load of constant wrt. tags.
+  __ lfdx(F15_ftos, Rcpool, Rindex);
+  __ push(dtos);
+  __ b(Lexit);
+
+  __ bind(Llong);
+  __ isync(); // Order load of constant wrt. tags.
+  __ ldx(R17_tos, Rcpool, Rindex);
+  __ push(ltos);
+
+  __ bind(Lexit);
+}
+
+// Get the locals index located in the bytecode stream at bcp + offset.
+void TemplateTable::locals_index(Register Rdst, int offset) {
+  __ lbz(Rdst, offset, R14_bcp);
+}
+
+void TemplateTable::iload() {
+  transition(vtos, itos);
+
+  // Get the local value into tos
+  const Register Rindex = R22_tmp2;
+  locals_index(Rindex);
+
+  // Rewrite iload,iload  pair into fast_iload2
+  //         iload,caload pair into fast_icaload
+  if (RewriteFrequentPairs) {
+    Label Lrewrite, Ldone;
+    Register Rnext_byte  = R3_ARG1,
+             Rrewrite_to = R6_ARG4,
+             Rscratch    = R11_scratch1;
+
+    // get next byte
+    __ lbz(Rnext_byte, Bytecodes::length_for(Bytecodes::_iload), R14_bcp);
+
+    // if _iload, wait to rewrite to iload2. We only want to rewrite the
+    // last two iloads in a pair. Comparing against fast_iload means that
+    // the next bytecode is neither an iload or a caload, and therefore
+    // an iload pair.
+    __ cmpwi(CCR0, Rnext_byte, (unsigned int)(unsigned char)Bytecodes::_iload);
+    __ beq(CCR0, Ldone);
+
+    __ cmpwi(CCR1, Rnext_byte, (unsigned int)(unsigned char)Bytecodes::_fast_iload);
+    __ li(Rrewrite_to, (unsigned int)(unsigned char)Bytecodes::_fast_iload2);
+    __ beq(CCR1, Lrewrite);
+
+    __ cmpwi(CCR0, Rnext_byte, (unsigned int)(unsigned char)Bytecodes::_caload);
+    __ li(Rrewrite_to, (unsigned int)(unsigned char)Bytecodes::_fast_icaload);
+    __ beq(CCR0, Lrewrite);
+
+    __ li(Rrewrite_to, (unsigned int)(unsigned char)Bytecodes::_fast_iload);
+
+    __ bind(Lrewrite);
+    patch_bytecode(Bytecodes::_iload, Rrewrite_to, Rscratch, false);
+    __ bind(Ldone);
+  }
+
+  __ load_local_int(R17_tos, Rindex, Rindex);
+}
+
+// Load 2 integers in a row without dispatching
+void TemplateTable::fast_iload2() {
+  transition(vtos, itos);
+
+  __ lbz(R3_ARG1, 1, R14_bcp);
+  __ lbz(R17_tos, Bytecodes::length_for(Bytecodes::_iload) + 1, R14_bcp);
+
+  __ load_local_int(R3_ARG1, R11_scratch1, R3_ARG1);
+  __ load_local_int(R17_tos, R12_scratch2, R17_tos);
+  __ push_i(R3_ARG1);
+}
+
+void TemplateTable::fast_iload() {
+  transition(vtos, itos);
+  // Get the local value into tos
+
+  const Register Rindex = R11_scratch1;
+  locals_index(Rindex);
+  __ load_local_int(R17_tos, Rindex, Rindex);
+}
+
+// Load a local variable type long from locals area to TOS cache register.
+// Local index resides in bytecodestream.
+void TemplateTable::lload() {
+  transition(vtos, ltos);
+
+  const Register Rindex = R11_scratch1;
+  locals_index(Rindex);
+  __ load_local_long(R17_tos, Rindex, Rindex);
+}
+
+void TemplateTable::fload() {
+  transition(vtos, ftos);
+
+  const Register Rindex = R11_scratch1;
+  locals_index(Rindex);
+  __ load_local_float(F15_ftos, Rindex, Rindex);
+}
+
+void TemplateTable::dload() {
+  transition(vtos, dtos);
+
+  const Register Rindex = R11_scratch1;
+  locals_index(Rindex);
+  __ load_local_double(F15_ftos, Rindex, Rindex);
+}
+
+void TemplateTable::aload() {
+  transition(vtos, atos);
+
+  const Register Rindex = R11_scratch1;
+  locals_index(Rindex);
+  __ load_local_ptr(R17_tos, Rindex, Rindex);
+}
+
+void TemplateTable::locals_index_wide(Register Rdst) {
+  // Offset is 2, not 1, because Lbcp points to wide prefix code.
+  __ get_2_byte_integer_at_bcp(2, Rdst, InterpreterMacroAssembler::Unsigned);
+}
+
+void TemplateTable::wide_iload() {
+  // Get the local value into tos.
+
+  const Register Rindex = R11_scratch1;
+  locals_index_wide(Rindex);
+  __ load_local_int(R17_tos, Rindex, Rindex);
+}
+
+void TemplateTable::wide_lload() {
+  transition(vtos, ltos);
+
+  const Register Rindex = R11_scratch1;
+  locals_index_wide(Rindex);
+  __ load_local_long(R17_tos, Rindex, Rindex);
+}
+
+void TemplateTable::wide_fload() {
+  transition(vtos, ftos);
+
+  const Register Rindex = R11_scratch1;
+  locals_index_wide(Rindex);
+  __ load_local_float(F15_ftos, Rindex, Rindex);
+}
+
+void TemplateTable::wide_dload() {
+  transition(vtos, dtos);
+
+  const Register Rindex = R11_scratch1;
+  locals_index_wide(Rindex);
+  __ load_local_double(F15_ftos, Rindex, Rindex);
+}
+
+void TemplateTable::wide_aload() {
+  transition(vtos, atos);
+
+  const Register Rindex = R11_scratch1;
+  locals_index_wide(Rindex);
+  __ load_local_ptr(R17_tos, Rindex, Rindex);
+}
+
+void TemplateTable::iaload() {
+  transition(itos, itos);
+
+  const Register Rload_addr = R3_ARG1,
+                 Rarray     = R4_ARG2,
+                 Rtemp      = R5_ARG3;
+  __ index_check(Rarray, R17_tos /* index */, LogBytesPerInt, Rtemp, Rload_addr);
+  __ lwa(R17_tos, arrayOopDesc::base_offset_in_bytes(T_INT), Rload_addr);
+}
+
+void TemplateTable::laload() {
+  transition(itos, ltos);
+
+  const Register Rload_addr = R3_ARG1,
+                 Rarray     = R4_ARG2,
+                 Rtemp      = R5_ARG3;
+  __ index_check(Rarray, R17_tos /* index */, LogBytesPerLong, Rtemp, Rload_addr);
+  __ ld(R17_tos, arrayOopDesc::base_offset_in_bytes(T_LONG), Rload_addr);
+}
+
+void TemplateTable::faload() {
+  transition(itos, ftos);
+
+  const Register Rload_addr = R3_ARG1,
+                 Rarray     = R4_ARG2,
+                 Rtemp      = R5_ARG3;
+  __ index_check(Rarray, R17_tos /* index */, LogBytesPerInt, Rtemp, Rload_addr);
+  __ lfs(F15_ftos, arrayOopDesc::base_offset_in_bytes(T_FLOAT), Rload_addr);
+}
+
+void TemplateTable::daload() {
+  transition(itos, dtos);
+
+  const Register Rload_addr = R3_ARG1,
+                 Rarray     = R4_ARG2,
+                 Rtemp      = R5_ARG3;
+  __ index_check(Rarray, R17_tos /* index */, LogBytesPerLong, Rtemp, Rload_addr);
+  __ lfd(F15_ftos, arrayOopDesc::base_offset_in_bytes(T_DOUBLE), Rload_addr);
+}
+
+void TemplateTable::aaload() {
+  transition(itos, atos);
+
+  // tos: index
+  // result tos: array
+  const Register Rload_addr = R3_ARG1,
+                 Rarray     = R4_ARG2,
+                 Rtemp      = R5_ARG3;
+  __ index_check(Rarray, R17_tos /* index */, UseCompressedOops ? 2 : LogBytesPerWord, Rtemp, Rload_addr);
+  __ load_heap_oop(R17_tos, arrayOopDesc::base_offset_in_bytes(T_OBJECT), Rload_addr);
+  __ verify_oop(R17_tos);
+  //__ dcbt(R17_tos); // prefetch
+}
+
+void TemplateTable::baload() {
+  transition(itos, itos);
+
+  const Register Rload_addr = R3_ARG1,
+                 Rarray     = R4_ARG2,
+                 Rtemp      = R5_ARG3;
+  __ index_check(Rarray, R17_tos /* index */, 0, Rtemp, Rload_addr);
+  __ lbz(R17_tos, arrayOopDesc::base_offset_in_bytes(T_BYTE), Rload_addr);
+  __ extsb(R17_tos, R17_tos);
+}
+
+void TemplateTable::caload() {
+  transition(itos, itos);
+
+  const Register Rload_addr = R3_ARG1,
+                 Rarray     = R4_ARG2,
+                 Rtemp      = R5_ARG3;
+  __ index_check(Rarray, R17_tos /* index */, LogBytesPerShort, Rtemp, Rload_addr);
+  __ lhz(R17_tos, arrayOopDesc::base_offset_in_bytes(T_CHAR), Rload_addr);
+}
+
+// Iload followed by caload frequent pair.
+void TemplateTable::fast_icaload() {
+  transition(vtos, itos);
+
+  const Register Rload_addr = R3_ARG1,
+                 Rarray     = R4_ARG2,
+                 Rtemp      = R11_scratch1;
+
+  locals_index(R17_tos);
+  __ load_local_int(R17_tos, Rtemp, R17_tos);
+  __ index_check(Rarray, R17_tos /* index */, LogBytesPerShort, Rtemp, Rload_addr);
+  __ lhz(R17_tos, arrayOopDesc::base_offset_in_bytes(T_CHAR), Rload_addr);
+}
+
+void TemplateTable::saload() {
+  transition(itos, itos);
+
+  const Register Rload_addr = R11_scratch1,
+                 Rarray     = R12_scratch2,
+                 Rtemp      = R3_ARG1;
+  __ index_check(Rarray, R17_tos /* index */, LogBytesPerShort, Rtemp, Rload_addr);
+  __ lha(R17_tos, arrayOopDesc::base_offset_in_bytes(T_SHORT), Rload_addr);
+}
+
+void TemplateTable::iload(int n) {
+  transition(vtos, itos);
+
+  __ lwz(R17_tos, Interpreter::local_offset_in_bytes(n), R18_locals);
+}
+
+void TemplateTable::lload(int n) {
+  transition(vtos, ltos);
+
+  __ ld(R17_tos, Interpreter::local_offset_in_bytes(n + 1), R18_locals);
+}
+
+void TemplateTable::fload(int n) {
+  transition(vtos, ftos);
+
+  __ lfs(F15_ftos, Interpreter::local_offset_in_bytes(n), R18_locals);
+}
+
+void TemplateTable::dload(int n) {
+  transition(vtos, dtos);
+
+  __ lfd(F15_ftos, Interpreter::local_offset_in_bytes(n + 1), R18_locals);
+}
+
+void TemplateTable::aload(int n) {
+  transition(vtos, atos);
+
+  __ ld(R17_tos, Interpreter::local_offset_in_bytes(n), R18_locals);
+}
+
+void TemplateTable::aload_0() {
+  transition(vtos, atos);
+  // According to bytecode histograms, the pairs:
+  //
+  // _aload_0, _fast_igetfield
+  // _aload_0, _fast_agetfield
+  // _aload_0, _fast_fgetfield
+  //
+  // occur frequently. If RewriteFrequentPairs is set, the (slow)
+  // _aload_0 bytecode checks if the next bytecode is either
+  // _fast_igetfield, _fast_agetfield or _fast_fgetfield and then
+  // rewrites the current bytecode into a pair bytecode; otherwise it
+  // rewrites the current bytecode into _0 that doesn't do
+  // the pair check anymore.
+  //
+  // Note: If the next bytecode is _getfield, the rewrite must be
+  //       delayed, otherwise we may miss an opportunity for a pair.
+  //
+  // Also rewrite frequent pairs
+  //   aload_0, aload_1
+  //   aload_0, iload_1
+  // These bytecodes with a small amount of code are most profitable
+  // to rewrite.
+
+  if (RewriteFrequentPairs) {
+
+    Label Lrewrite, Ldont_rewrite;
+    Register Rnext_byte  = R3_ARG1,
+             Rrewrite_to = R6_ARG4,
+             Rscratch    = R11_scratch1;
+
+    // Get next byte.
+    __ lbz(Rnext_byte, Bytecodes::length_for(Bytecodes::_aload_0), R14_bcp);
+
+    // If _getfield, wait to rewrite. We only want to rewrite the last two bytecodes in a pair.
+    __ cmpwi(CCR0, Rnext_byte, (unsigned int)(unsigned char)Bytecodes::_getfield);
+    __ beq(CCR0, Ldont_rewrite);
+
+    __ cmpwi(CCR1, Rnext_byte, (unsigned int)(unsigned char)Bytecodes::_fast_igetfield);
+    __ li(Rrewrite_to, (unsigned int)(unsigned char)Bytecodes::_fast_iaccess_0);
+    __ beq(CCR1, Lrewrite);
+
+    __ cmpwi(CCR0, Rnext_byte, (unsigned int)(unsigned char)Bytecodes::_fast_agetfield);
+    __ li(Rrewrite_to, (unsigned int)(unsigned char)Bytecodes::_fast_aaccess_0);
+    __ beq(CCR0, Lrewrite);
+
+    __ cmpwi(CCR1, Rnext_byte, (unsigned int)(unsigned char)Bytecodes::_fast_fgetfield);
+    __ li(Rrewrite_to, (unsigned int)(unsigned char)Bytecodes::_fast_faccess_0);
+    __ beq(CCR1, Lrewrite);
+
+    __ li(Rrewrite_to, (unsigned int)(unsigned char)Bytecodes::_fast_aload_0);
+
+    __ bind(Lrewrite);
+    patch_bytecode(Bytecodes::_aload_0, Rrewrite_to, Rscratch, false);
+    __ bind(Ldont_rewrite);
+  }
+
+  // Do actual aload_0 (must do this after patch_bytecode which might call VM and GC might change oop).
+  aload(0);
+}
+
+void TemplateTable::istore() {
+  transition(itos, vtos);
+
+  const Register Rindex = R11_scratch1;
+  locals_index(Rindex);
+  __ store_local_int(R17_tos, Rindex);
+}
+
+void TemplateTable::lstore() {
+  transition(ltos, vtos);
+  const Register Rindex = R11_scratch1;
+  locals_index(Rindex);
+  __ store_local_long(R17_tos, Rindex);
+}
+
+void TemplateTable::fstore() {
+  transition(ftos, vtos);
+
+  const Register Rindex = R11_scratch1;
+  locals_index(Rindex);
+  __ store_local_float(F15_ftos, Rindex);
+}
+
+void TemplateTable::dstore() {
+  transition(dtos, vtos);
+
+  const Register Rindex = R11_scratch1;
+  locals_index(Rindex);
+  __ store_local_double(F15_ftos, Rindex);
+}
+
+void TemplateTable::astore() {
+  transition(vtos, vtos);
+
+  const Register Rindex = R11_scratch1;
+  __ pop_ptr();
+  __ verify_oop_or_return_address(R17_tos, Rindex);
+  locals_index(Rindex);
+  __ store_local_ptr(R17_tos, Rindex);
+}
+
+void TemplateTable::wide_istore() {
+  transition(vtos, vtos);
+
+  const Register Rindex = R11_scratch1;
+  __ pop_i();
+  locals_index_wide(Rindex);
+  __ store_local_int(R17_tos, Rindex);
+}
+
+void TemplateTable::wide_lstore() {
+  transition(vtos, vtos);
+
+  const Register Rindex = R11_scratch1;
+  __ pop_l();
+  locals_index_wide(Rindex);
+  __ store_local_long(R17_tos, Rindex);
+}
+
+void TemplateTable::wide_fstore() {
+  transition(vtos, vtos);
+
+  const Register Rindex = R11_scratch1;
+  __ pop_f();
+  locals_index_wide(Rindex);
+  __ store_local_float(F15_ftos, Rindex);
+}
+
+void TemplateTable::wide_dstore() {
+  transition(vtos, vtos);
+
+  const Register Rindex = R11_scratch1;
+  __ pop_d();
+  locals_index_wide(Rindex);
+  __ store_local_double(F15_ftos, Rindex);
+}
+
+void TemplateTable::wide_astore() {
+  transition(vtos, vtos);
+
+  const Register Rindex = R11_scratch1;
+  __ pop_ptr();
+  __ verify_oop_or_return_address(R17_tos, Rindex);
+  locals_index_wide(Rindex);
+  __ store_local_ptr(R17_tos, Rindex);
+}
+
+void TemplateTable::iastore() {
+  transition(itos, vtos);
+
+  const Register Rindex      = R3_ARG1,
+                 Rstore_addr = R4_ARG2,
+                 Rarray      = R5_ARG3,
+                 Rtemp       = R6_ARG4;
+  __ pop_i(Rindex);
+  __ index_check(Rarray, Rindex, LogBytesPerInt, Rtemp, Rstore_addr);
+  __ stw(R17_tos, arrayOopDesc::base_offset_in_bytes(T_INT), Rstore_addr);
+  }
+
+void TemplateTable::lastore() {
+  transition(ltos, vtos);
+
+  const Register Rindex      = R3_ARG1,
+                 Rstore_addr = R4_ARG2,
+                 Rarray      = R5_ARG3,
+                 Rtemp       = R6_ARG4;
+  __ pop_i(Rindex);
+  __ index_check(Rarray, Rindex, LogBytesPerLong, Rtemp, Rstore_addr);
+  __ std(R17_tos, arrayOopDesc::base_offset_in_bytes(T_LONG), Rstore_addr);
+  }
+
+void TemplateTable::fastore() {
+  transition(ftos, vtos);
+
+  const Register Rindex      = R3_ARG1,
+                 Rstore_addr = R4_ARG2,
+                 Rarray      = R5_ARG3,
+                 Rtemp       = R6_ARG4;
+  __ pop_i(Rindex);
+  __ index_check(Rarray, Rindex, LogBytesPerInt, Rtemp, Rstore_addr);
+  __ stfs(F15_ftos, arrayOopDesc::base_offset_in_bytes(T_FLOAT), Rstore_addr);
+  }
+
+void TemplateTable::dastore() {
+  transition(dtos, vtos);
+
+  const Register Rindex      = R3_ARG1,
+                 Rstore_addr = R4_ARG2,
+                 Rarray      = R5_ARG3,
+                 Rtemp       = R6_ARG4;
+  __ pop_i(Rindex);
+  __ index_check(Rarray, Rindex, LogBytesPerLong, Rtemp, Rstore_addr);
+  __ stfd(F15_ftos, arrayOopDesc::base_offset_in_bytes(T_DOUBLE), Rstore_addr);
+  }
+
+// Pop 3 values from the stack and...
+void TemplateTable::aastore() {
+  transition(vtos, vtos);
+
+  Label Lstore_ok, Lis_null, Ldone;
+  const Register Rindex    = R3_ARG1,
+                 Rarray    = R4_ARG2,
+                 Rscratch  = R11_scratch1,
+                 Rscratch2 = R12_scratch2,
+                 Rarray_klass = R5_ARG3,
+                 Rarray_element_klass = Rarray_klass,
+                 Rvalue_klass = R6_ARG4,
+                 Rstore_addr = R31;    // Use register which survives VM call.
+
+  __ ld(R17_tos, Interpreter::expr_offset_in_bytes(0), R15_esp); // Get value to store.
+  __ lwz(Rindex, Interpreter::expr_offset_in_bytes(1), R15_esp); // Get index.
+  __ ld(Rarray, Interpreter::expr_offset_in_bytes(2), R15_esp);  // Get array.
+
+  __ verify_oop(R17_tos);
+  __ index_check_without_pop(Rarray, Rindex, UseCompressedOops ? 2 : LogBytesPerWord, Rscratch, Rstore_addr);
+  // Rindex is dead!
+  Register Rscratch3 = Rindex;
+
+  // Do array store check - check for NULL value first.
+  __ cmpdi(CCR0, R17_tos, 0);
+  __ beq(CCR0, Lis_null);
+
+  __ load_klass(Rarray_klass, Rarray);
+  __ load_klass(Rvalue_klass, R17_tos);
+
+  // Do fast instanceof cache test.
+  __ ld(Rarray_element_klass, in_bytes(ObjArrayKlass::element_klass_offset()), Rarray_klass);
+
+  // Generate a fast subtype check. Branch to store_ok if no failure. Throw if failure.
+  __ gen_subtype_check(Rvalue_klass /*subklass*/, Rarray_element_klass /*superklass*/, Rscratch, Rscratch2, Rscratch3, Lstore_ok);
+
+  // Fell through: subtype check failed => throw an exception.
+  __ load_dispatch_table(R11_scratch1, (address*)Interpreter::_throw_ArrayStoreException_entry);
+  __ mtctr(R11_scratch1);
+  __ bctr();
+
+  __ bind(Lis_null);
+  do_oop_store(_masm, Rstore_addr, arrayOopDesc::base_offset_in_bytes(T_OBJECT), noreg /* 0 */,
+               Rscratch, Rscratch2, Rscratch3, _bs->kind(), true /* precise */, false /* check_null */);
+  __ profile_null_seen(Rscratch, Rscratch2);
+  __ b(Ldone);
+
+  // Store is OK.
+  __ bind(Lstore_ok);
+  do_oop_store(_masm, Rstore_addr, arrayOopDesc::base_offset_in_bytes(T_OBJECT), R17_tos /* value */,
+               Rscratch, Rscratch2, Rscratch3, _bs->kind(), true /* precise */, false /* check_null */);
+
+  __ bind(Ldone);
+  // Adjust sp (pops array, index and value).
+  __ addi(R15_esp, R15_esp, 3 * Interpreter::stackElementSize);
+}
+
+void TemplateTable::bastore() {
+  transition(itos, vtos);
+
+  const Register Rindex   = R11_scratch1,
+                 Rarray   = R12_scratch2,
+                 Rscratch = R3_ARG1;
+  __ pop_i(Rindex);
+  // tos: val
+  // Rarray: array ptr (popped by index_check)
+  __ index_check(Rarray, Rindex, 0, Rscratch, Rarray);
+  __ stb(R17_tos, arrayOopDesc::base_offset_in_bytes(T_BYTE), Rarray);
+}
+
+void TemplateTable::castore() {
+  transition(itos, vtos);
+
+  const Register Rindex   = R11_scratch1,
+                 Rarray   = R12_scratch2,
+                 Rscratch = R3_ARG1;
+  __ pop_i(Rindex);
+  // tos: val
+  // Rarray: array ptr (popped by index_check)
+  __ index_check(Rarray, Rindex, LogBytesPerShort, Rscratch, Rarray);
+  __ sth(R17_tos, arrayOopDesc::base_offset_in_bytes(T_CHAR), Rarray);
+}
+
+void TemplateTable::sastore() {
+  castore();
+}
+
+void TemplateTable::istore(int n) {
+  transition(itos, vtos);
+  __ stw(R17_tos, Interpreter::local_offset_in_bytes(n), R18_locals);
+}
+
+void TemplateTable::lstore(int n) {
+  transition(ltos, vtos);
+  __ std(R17_tos, Interpreter::local_offset_in_bytes(n + 1), R18_locals);
+}
+
+void TemplateTable::fstore(int n) {
+  transition(ftos, vtos);
+  __ stfs(F15_ftos, Interpreter::local_offset_in_bytes(n), R18_locals);
+}
+
+void TemplateTable::dstore(int n) {
+  transition(dtos, vtos);
+  __ stfd(F15_ftos, Interpreter::local_offset_in_bytes(n + 1), R18_locals);
+}
+
+void TemplateTable::astore(int n) {
+  transition(vtos, vtos);
+
+  __ pop_ptr();
+  __ verify_oop_or_return_address(R17_tos, R11_scratch1);
+  __ std(R17_tos, Interpreter::local_offset_in_bytes(n), R18_locals);
+}
+
+void TemplateTable::pop() {
+  transition(vtos, vtos);
+
+  __ addi(R15_esp, R15_esp, Interpreter::stackElementSize);
+}
+
+void TemplateTable::pop2() {
+  transition(vtos, vtos);
+
+  __ addi(R15_esp, R15_esp, Interpreter::stackElementSize * 2);
+}
+
+void TemplateTable::dup() {
+  transition(vtos, vtos);
+
+  __ ld(R11_scratch1, Interpreter::stackElementSize, R15_esp);
+  __ push_ptr(R11_scratch1);
+}
+
+void TemplateTable::dup_x1() {
+  transition(vtos, vtos);
+
+  Register Ra = R11_scratch1,
+           Rb = R12_scratch2;
+  // stack: ..., a, b
+  __ ld(Rb, Interpreter::stackElementSize,     R15_esp);
+  __ ld(Ra, Interpreter::stackElementSize * 2, R15_esp);
+  __ std(Rb, Interpreter::stackElementSize * 2, R15_esp);
+  __ std(Ra, Interpreter::stackElementSize,     R15_esp);
+  __ push_ptr(Rb);
+  // stack: ..., b, a, b
+}
+
+void TemplateTable::dup_x2() {
+  transition(vtos, vtos);
+
+  Register Ra = R11_scratch1,
+           Rb = R12_scratch2,
+           Rc = R3_ARG1;
+
+  // stack: ..., a, b, c
+  __ ld(Rc, Interpreter::stackElementSize,     R15_esp);  // load c
+  __ ld(Ra, Interpreter::stackElementSize * 3, R15_esp);  // load a
+  __ std(Rc, Interpreter::stackElementSize * 3, R15_esp); // store c in a
+  __ ld(Rb, Interpreter::stackElementSize * 2, R15_esp);  // load b
+  // stack: ..., c, b, c
+  __ std(Ra, Interpreter::stackElementSize * 2, R15_esp); // store a in b
+  // stack: ..., c, a, c
+  __ std(Rb, Interpreter::stackElementSize,     R15_esp); // store b in c
+  __ push_ptr(Rc);                                        // push c
+  // stack: ..., c, a, b, c
+}
+
+void TemplateTable::dup2() {
+  transition(vtos, vtos);
+
+  Register Ra = R11_scratch1,
+           Rb = R12_scratch2;
+  // stack: ..., a, b
+  __ ld(Rb, Interpreter::stackElementSize,     R15_esp);
+  __ ld(Ra, Interpreter::stackElementSize * 2, R15_esp);
+  __ push_2ptrs(Ra, Rb);
+  // stack: ..., a, b, a, b
+}
+
+void TemplateTable::dup2_x1() {
+  transition(vtos, vtos);
+
+  Register Ra = R11_scratch1,
+           Rb = R12_scratch2,
+           Rc = R3_ARG1;
+  // stack: ..., a, b, c
+  __ ld(Rc, Interpreter::stackElementSize,     R15_esp);
+  __ ld(Rb, Interpreter::stackElementSize * 2, R15_esp);
+  __ std(Rc, Interpreter::stackElementSize * 2, R15_esp);
+  __ ld(Ra, Interpreter::stackElementSize * 3, R15_esp);
+  __ std(Ra, Interpreter::stackElementSize,     R15_esp);
+  __ std(Rb, Interpreter::stackElementSize * 3, R15_esp);
+  // stack: ..., b, c, a
+  __ push_2ptrs(Rb, Rc);
+  // stack: ..., b, c, a, b, c
+}
+
+void TemplateTable::dup2_x2() {
+  transition(vtos, vtos);
+
+  Register Ra = R11_scratch1,
+           Rb = R12_scratch2,
+           Rc = R3_ARG1,
+           Rd = R4_ARG2;
+  // stack: ..., a, b, c, d
+  __ ld(Rb, Interpreter::stackElementSize * 3, R15_esp);
+  __ ld(Rd, Interpreter::stackElementSize,     R15_esp);
+  __ std(Rb, Interpreter::stackElementSize,     R15_esp);  // store b in d
+  __ std(Rd, Interpreter::stackElementSize * 3, R15_esp);  // store d in b
+  __ ld(Ra, Interpreter::stackElementSize * 4, R15_esp);
+  __ ld(Rc, Interpreter::stackElementSize * 2, R15_esp);
+  __ std(Ra, Interpreter::stackElementSize * 2, R15_esp);  // store a in c
+  __ std(Rc, Interpreter::stackElementSize * 4, R15_esp);  // store c in a
+  // stack: ..., c, d, a, b
+  __ push_2ptrs(Rc, Rd);
+  // stack: ..., c, d, a, b, c, d
+}
+
+void TemplateTable::swap() {
+  transition(vtos, vtos);
+  // stack: ..., a, b
+
+  Register Ra = R11_scratch1,
+           Rb = R12_scratch2;
+  // stack: ..., a, b
+  __ ld(Rb, Interpreter::stackElementSize,     R15_esp);
+  __ ld(Ra, Interpreter::stackElementSize * 2, R15_esp);
+  __ std(Rb, Interpreter::stackElementSize * 2, R15_esp);
+  __ std(Ra, Interpreter::stackElementSize,     R15_esp);
+  // stack: ..., b, a
+}
+
+void TemplateTable::iop2(Operation op) {
+  transition(itos, itos);
+
+  Register Rscratch = R11_scratch1;
+
+  __ pop_i(Rscratch);
+  // tos  = number of bits to shift
+  // Rscratch = value to shift
+  switch (op) {
+    case  add:   __ add(R17_tos, Rscratch, R17_tos); break;
+    case  sub:   __ sub(R17_tos, Rscratch, R17_tos); break;
+    case  mul:   __ mullw(R17_tos, Rscratch, R17_tos); break;
+    case  _and:  __ andr(R17_tos, Rscratch, R17_tos); break;
+    case  _or:   __ orr(R17_tos, Rscratch, R17_tos); break;
+    case  _xor:  __ xorr(R17_tos, Rscratch, R17_tos); break;
+    case  shl:   __ rldicl(R17_tos, R17_tos, 0, 64-5); __ slw(R17_tos, Rscratch, R17_tos); break;
+    case  shr:   __ rldicl(R17_tos, R17_tos, 0, 64-5); __ sraw(R17_tos, Rscratch, R17_tos); break;
+    case  ushr:  __ rldicl(R17_tos, R17_tos, 0, 64-5); __ srw(R17_tos, Rscratch, R17_tos); break;
+    default:     ShouldNotReachHere();
+  }
+}
+
+void TemplateTable::lop2(Operation op) {
+  transition(ltos, ltos);
+
+  Register Rscratch = R11_scratch1;
+  __ pop_l(Rscratch);
+  switch (op) {
+    case  add:   __ add(R17_tos, Rscratch, R17_tos); break;
+    case  sub:   __ sub(R17_tos, Rscratch, R17_tos); break;
+    case  _and:  __ andr(R17_tos, Rscratch, R17_tos); break;
+    case  _or:   __ orr(R17_tos, Rscratch, R17_tos); break;
+    case  _xor:  __ xorr(R17_tos, Rscratch, R17_tos); break;
+    default:     ShouldNotReachHere();
+  }
+}
+
+void TemplateTable::idiv() {
+  transition(itos, itos);
+
+  Label Lnormal, Lexception, Ldone;
+  Register Rdividend = R11_scratch1; // Used by irem.
+
+  __ addi(R0, R17_tos, 1);
+  __ cmplwi(CCR0, R0, 2);
+  __ bgt(CCR0, Lnormal); // divisor <-1 or >1
+
+  __ cmpwi(CCR1, R17_tos, 0);
+  __ beq(CCR1, Lexception); // divisor == 0
+
+  __ pop_i(Rdividend);
+  __ mullw(R17_tos, Rdividend, R17_tos); // div by +/-1
+  __ b(Ldone);
+
+  __ bind(Lexception);
+  __ load_dispatch_table(R11_scratch1, (address*)Interpreter::_throw_ArithmeticException_entry);
+  __ mtctr(R11_scratch1);
+  __ bctr();
+
+  __ align(32, 12);
+  __ bind(Lnormal);
+  __ pop_i(Rdividend);
+  __ divw(R17_tos, Rdividend, R17_tos); // Can't divide minint/-1.
+  __ bind(Ldone);
+}
+
+void TemplateTable::irem() {
+  transition(itos, itos);
+
+  __ mr(R12_scratch2, R17_tos);
+  idiv();
+  __ mullw(R17_tos, R17_tos, R12_scratch2);
+  __ subf(R17_tos, R17_tos, R11_scratch1); // Dividend set by idiv.
+}
+
+void TemplateTable::lmul() {
+  transition(ltos, ltos);
+
+  __ pop_l(R11_scratch1);
+  __ mulld(R17_tos, R11_scratch1, R17_tos);
+}
+
+void TemplateTable::ldiv() {
+  transition(ltos, ltos);
+
+  Label Lnormal, Lexception, Ldone;
+  Register Rdividend = R11_scratch1; // Used by lrem.
+
+  __ addi(R0, R17_tos, 1);
+  __ cmpldi(CCR0, R0, 2);
+  __ bgt(CCR0, Lnormal); // divisor <-1 or >1
+
+  __ cmpdi(CCR1, R17_tos, 0);
+  __ beq(CCR1, Lexception); // divisor == 0
+
+  __ pop_l(Rdividend);
+  __ mulld(R17_tos, Rdividend, R17_tos); // div by +/-1
+  __ b(Ldone);
+
+  __ bind(Lexception);
+  __ load_dispatch_table(R11_scratch1, (address*)Interpreter::_throw_ArithmeticException_entry);
+  __ mtctr(R11_scratch1);
+  __ bctr();
+
+  __ align(32, 12);
+  __ bind(Lnormal);
+  __ pop_l(Rdividend);
+  __ divd(R17_tos, Rdividend, R17_tos); // Can't divide minint/-1.
+  __ bind(Ldone);
+}
+
+void TemplateTable::lrem() {
+  transition(ltos, ltos);
+
+  __ mr(R12_scratch2, R17_tos);
+  ldiv();
+  __ mulld(R17_tos, R17_tos, R12_scratch2);
+  __ subf(R17_tos, R17_tos, R11_scratch1); // Dividend set by ldiv.
+}
+
+void TemplateTable::lshl() {
+  transition(itos, ltos);
+
+  __ rldicl(R17_tos, R17_tos, 0, 64-6); // Extract least significant bits.
+  __ pop_l(R11_scratch1);
+  __ sld(R17_tos, R11_scratch1, R17_tos);
+}
+
+void TemplateTable::lshr() {
+  transition(itos, ltos);
+
+  __ rldicl(R17_tos, R17_tos, 0, 64-6); // Extract least significant bits.
+  __ pop_l(R11_scratch1);
+  __ srad(R17_tos, R11_scratch1, R17_tos);
+}
+
+void TemplateTable::lushr() {
+  transition(itos, ltos);
+
+  __ rldicl(R17_tos, R17_tos, 0, 64-6); // Extract least significant bits.
+  __ pop_l(R11_scratch1);
+  __ srd(R17_tos, R11_scratch1, R17_tos);
+}
+
+void TemplateTable::fop2(Operation op) {
+  transition(ftos, ftos);
+
+  switch (op) {
+    case add: __ pop_f(F0_SCRATCH); __ fadds(F15_ftos, F0_SCRATCH, F15_ftos); break;
+    case sub: __ pop_f(F0_SCRATCH); __ fsubs(F15_ftos, F0_SCRATCH, F15_ftos); break;
+    case mul: __ pop_f(F0_SCRATCH); __ fmuls(F15_ftos, F0_SCRATCH, F15_ftos); break;
+    case div: __ pop_f(F0_SCRATCH); __ fdivs(F15_ftos, F0_SCRATCH, F15_ftos); break;
+    case rem:
+      __ pop_f(F1_ARG1);
+      __ fmr(F2_ARG2, F15_ftos);
+      __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::frem));
+      __ fmr(F15_ftos, F1_RET);
+      break;
+
+    default: ShouldNotReachHere();
+  }
+}
+
+void TemplateTable::dop2(Operation op) {
+  transition(dtos, dtos);
+
+  switch (op) {
+    case add: __ pop_d(F0_SCRATCH); __ fadd(F15_ftos, F0_SCRATCH, F15_ftos); break;
+    case sub: __ pop_d(F0_SCRATCH); __ fsub(F15_ftos, F0_SCRATCH, F15_ftos); break;
+    case mul: __ pop_d(F0_SCRATCH); __ fmul(F15_ftos, F0_SCRATCH, F15_ftos); break;
+    case div: __ pop_d(F0_SCRATCH); __ fdiv(F15_ftos, F0_SCRATCH, F15_ftos); break;
+    case rem:
+      __ pop_d(F1_ARG1);
+      __ fmr(F2_ARG2, F15_ftos);
+      __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::drem));
+      __ fmr(F15_ftos, F1_RET);
+      break;
+
+    default: ShouldNotReachHere();
+  }
+}
+
+// Negate the value in the TOS cache.
+void TemplateTable::ineg() {
+  transition(itos, itos);
+
+  __ neg(R17_tos, R17_tos);
+}
+
+// Negate the value in the TOS cache.
+void TemplateTable::lneg() {
+  transition(ltos, ltos);
+
+  __ neg(R17_tos, R17_tos);
+}
+
+void TemplateTable::fneg() {
+  transition(ftos, ftos);
+
+  __ fneg(F15_ftos, F15_ftos);
+}
+
+void TemplateTable::dneg() {
+  transition(dtos, dtos);
+
+  __ fneg(F15_ftos, F15_ftos);
+}
+
+// Increments a local variable in place.
+void TemplateTable::iinc() {
+  transition(vtos, vtos);
+
+  const Register Rindex     = R11_scratch1,
+                 Rincrement = R0,
+                 Rvalue     = R12_scratch2;
+
+  locals_index(Rindex);              // Load locals index from bytecode stream.
+  __ lbz(Rincrement, 2, R14_bcp);    // Load increment from the bytecode stream.
+  __ extsb(Rincrement, Rincrement);
+
+  __ load_local_int(Rvalue, Rindex, Rindex); // Puts address of local into Rindex.
+
+  __ add(Rvalue, Rincrement, Rvalue);
+  __ stw(Rvalue, 0, Rindex);
+}
+
+void TemplateTable::wide_iinc() {
+  transition(vtos, vtos);
+
+  Register Rindex       = R11_scratch1,
+           Rlocals_addr = Rindex,
+           Rincr        = R12_scratch2;
+  locals_index_wide(Rindex);
+  __ get_2_byte_integer_at_bcp(4, Rincr, InterpreterMacroAssembler::Signed);
+  __ load_local_int(R17_tos, Rlocals_addr, Rindex);
+  __ add(R17_tos, Rincr, R17_tos);
+  __ stw(R17_tos, 0, Rlocals_addr);
+}
+
+void TemplateTable::convert() {
+  // %%%%% Factor this first part accross platforms
+#ifdef ASSERT
+  TosState tos_in  = ilgl;
+  TosState tos_out = ilgl;
+  switch (bytecode()) {
+    case Bytecodes::_i2l: // fall through
+    case Bytecodes::_i2f: // fall through
+    case Bytecodes::_i2d: // fall through
+    case Bytecodes::_i2b: // fall through
+    case Bytecodes::_i2c: // fall through
+    case Bytecodes::_i2s: tos_in = itos; break;
+    case Bytecodes::_l2i: // fall through
+    case Bytecodes::_l2f: // fall through
+    case Bytecodes::_l2d: tos_in = ltos; break;
+    case Bytecodes::_f2i: // fall through
+    case Bytecodes::_f2l: // fall through
+    case Bytecodes::_f2d: tos_in = ftos; break;
+    case Bytecodes::_d2i: // fall through
+    case Bytecodes::_d2l: // fall through
+    case Bytecodes::_d2f: tos_in = dtos; break;
+    default             : ShouldNotReachHere();
+  }
+  switch (bytecode()) {
+    case Bytecodes::_l2i: // fall through
+    case Bytecodes::_f2i: // fall through
+    case Bytecodes::_d2i: // fall through
+    case Bytecodes::_i2b: // fall through
+    case Bytecodes::_i2c: // fall through
+    case Bytecodes::_i2s: tos_out = itos; break;
+    case Bytecodes::_i2l: // fall through
+    case Bytecodes::_f2l: // fall through
+    case Bytecodes::_d2l: tos_out = ltos; break;
+    case Bytecodes::_i2f: // fall through
+    case Bytecodes::_l2f: // fall through
+    case Bytecodes::_d2f: tos_out = ftos; break;
+    case Bytecodes::_i2d: // fall through
+    case Bytecodes::_l2d: // fall through
+    case Bytecodes::_f2d: tos_out = dtos; break;
+    default             : ShouldNotReachHere();
+  }
+  transition(tos_in, tos_out);
+#endif
+
+  // Conversion
+  Label done;
+  switch (bytecode()) {
+    case Bytecodes::_i2l:
+      __ extsw(R17_tos, R17_tos);
+      break;
+
+    case Bytecodes::_l2i:
+      // Nothing to do, we'll continue to work with the lower bits.
+      break;
+
+    case Bytecodes::_i2b:
+      __ extsb(R17_tos, R17_tos);
+      break;
+
+    case Bytecodes::_i2c:
+      __ rldicl(R17_tos, R17_tos, 0, 64-2*8);
+      break;
+
+    case Bytecodes::_i2s:
+      __ extsh(R17_tos, R17_tos);
+      break;
+
+    case Bytecodes::_i2d:
+      __ extsw(R17_tos, R17_tos);
+    case Bytecodes::_l2d:
+      __ push_l_pop_d();
+      __ fcfid(F15_ftos, F15_ftos);
+      break;
+
+    case Bytecodes::_i2f:
+      __ extsw(R17_tos, R17_tos);
+      __ push_l_pop_d();
+      if (VM_Version::has_fcfids()) { // fcfids is >= Power7 only
+        // Comment: alternatively, load with sign extend could be done by lfiwax.
+        __ fcfids(F15_ftos, F15_ftos);
+      } else {
+        __ fcfid(F15_ftos, F15_ftos);
+        __ frsp(F15_ftos, F15_ftos);
+      }
+      break;
+
+    case Bytecodes::_l2f:
+      if (VM_Version::has_fcfids()) { // fcfids is >= Power7 only
+        __ push_l_pop_d();
+        __ fcfids(F15_ftos, F15_ftos);
+      } else {
+        // Avoid rounding problem when result should be 0x3f800001: need fixup code before fcfid+frsp.
+        __ mr(R3_ARG1, R17_tos);
+        __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::l2f));
+        __ fmr(F15_ftos, F1_RET);
+      }
+      break;
+
+    case Bytecodes::_f2d:
+      // empty
+      break;
+
+    case Bytecodes::_d2f:
+      __ frsp(F15_ftos, F15_ftos);
+      break;
+
+    case Bytecodes::_d2i:
+    case Bytecodes::_f2i:
+      __ fcmpu(CCR0, F15_ftos, F15_ftos);
+      __ li(R17_tos, 0); // 0 in case of NAN
+      __ bso(CCR0, done);
+      __ fctiwz(F15_ftos, F15_ftos);
+      __ push_d_pop_l();
+      break;
+
+    case Bytecodes::_d2l:
+    case Bytecodes::_f2l:
+      __ fcmpu(CCR0, F15_ftos, F15_ftos);
+      __ li(R17_tos, 0); // 0 in case of NAN
+      __ bso(CCR0, done);
+      __ fctidz(F15_ftos, F15_ftos);
+      __ push_d_pop_l();
+      break;
+
+    default: ShouldNotReachHere();
+  }
+  __ bind(done);
+}
+
+// Long compare
+void TemplateTable::lcmp() {
+  transition(ltos, itos);
+
+  const Register Rscratch = R11_scratch1;
+  __ pop_l(Rscratch); // first operand, deeper in stack
+
+  __ cmpd(CCR0, Rscratch, R17_tos); // compare
+  __ mfcr(R17_tos); // set bit 32..33 as follows: <: 0b10, =: 0b00, >: 0b01
+  __ srwi(Rscratch, R17_tos, 30);
+  __ srawi(R17_tos, R17_tos, 31);
+  __ orr(R17_tos, Rscratch, R17_tos); // set result as follows: <: -1, =: 0, >: 1
+}
+
+// fcmpl/fcmpg and dcmpl/dcmpg bytecodes
+// unordered_result == -1 => fcmpl or dcmpl
+// unordered_result ==  1 => fcmpg or dcmpg
+void TemplateTable::float_cmp(bool is_float, int unordered_result) {
+  const FloatRegister Rfirst  = F0_SCRATCH,
+                      Rsecond = F15_ftos;
+  const Register Rscratch = R11_scratch1;
+
+  if (is_float) {
+    __ pop_f(Rfirst);
+  } else {
+    __ pop_d(Rfirst);
+  }
+
+  Label Lunordered, Ldone;
+  __ fcmpu(CCR0, Rfirst, Rsecond); // compare
+  if (unordered_result) {
+    __ bso(CCR0, Lunordered);
+  }
+  __ mfcr(R17_tos); // set bit 32..33 as follows: <: 0b10, =: 0b00, >: 0b01
+  __ srwi(Rscratch, R17_tos, 30);
+  __ srawi(R17_tos, R17_tos, 31);
+  __ orr(R17_tos, Rscratch, R17_tos); // set result as follows: <: -1, =: 0, >: 1
+  if (unordered_result) {
+    __ b(Ldone);
+    __ bind(Lunordered);
+    __ load_const_optimized(R17_tos, unordered_result);
+  }
+  __ bind(Ldone);
+}
+
+// Branch_conditional which takes TemplateTable::Condition.
+void TemplateTable::branch_conditional(ConditionRegister crx, TemplateTable::Condition cc, Label& L, bool invert) {
+  bool positive = false;
+  Assembler::Condition cond = Assembler::equal;
+  switch (cc) {
+    case TemplateTable::equal:         positive = true ; cond = Assembler::equal  ; break;
+    case TemplateTable::not_equal:     positive = false; cond = Assembler::equal  ; break;
+    case TemplateTable::less:          positive = true ; cond = Assembler::less   ; break;
+    case TemplateTable::less_equal:    positive = false; cond = Assembler::greater; break;
+    case TemplateTable::greater:       positive = true ; cond = Assembler::greater; break;
+    case TemplateTable::greater_equal: positive = false; cond = Assembler::less   ; break;
+    default: ShouldNotReachHere();
+  }
+  int bo = (positive != invert) ? Assembler::bcondCRbiIs1 : Assembler::bcondCRbiIs0;
+  int bi = Assembler::bi0(crx, cond);
+  __ bc(bo, bi, L);
+}
+
+void TemplateTable::branch(bool is_jsr, bool is_wide) {
+
+  // Note: on SPARC, we use InterpreterMacroAssembler::if_cmp also.
+  __ verify_thread();
+
+  const Register Rscratch1    = R11_scratch1,
+                 Rscratch2    = R12_scratch2,
+                 Rscratch3    = R3_ARG1,
+                 R4_counters  = R4_ARG2,
+                 bumped_count = R31,
+                 Rdisp        = R22_tmp2;
+
+  __ profile_taken_branch(Rscratch1, bumped_count);
+
+  // Get (wide) offset.
+  if (is_wide) {
+    __ get_4_byte_integer_at_bcp(1, Rdisp, InterpreterMacroAssembler::Signed);
+  } else {
+    __ get_2_byte_integer_at_bcp(1, Rdisp, InterpreterMacroAssembler::Signed);
+  }
+
+  // --------------------------------------------------------------------------
+  // Handle all the JSR stuff here, then exit.
+  // It's much shorter and cleaner than intermingling with the
+  // non-JSR normal-branch stuff occurring below.
+  if (is_jsr) {
+    // Compute return address as bci in Otos_i.
+    __ ld(Rscratch1, in_bytes(Method::const_offset()), R19_method);
+    __ addi(Rscratch2, R14_bcp, -in_bytes(ConstMethod::codes_offset()) + (is_wide ? 5 : 3));
+    __ subf(R17_tos, Rscratch1, Rscratch2);
+
+    // Bump bcp to target of JSR.
+    __ add(R14_bcp, Rdisp, R14_bcp);
+    // Push returnAddress for "ret" on stack.
+    __ push_ptr(R17_tos);
+    // And away we go!
+    __ dispatch_next(vtos);
+    return;
+  }
+
+  // --------------------------------------------------------------------------
+  // Normal (non-jsr) branch handling
+
+  const bool increment_invocation_counter_for_backward_branches = UseCompiler && UseLoopCounter;
+  if (increment_invocation_counter_for_backward_branches) {
+    //__ unimplemented("branch invocation counter");
+
+    Label Lforward;
+    __ add(R14_bcp, Rdisp, R14_bcp); // Add to bc addr.
+
+    // Check branch direction.
+    __ cmpdi(CCR0, Rdisp, 0);
+    __ bgt(CCR0, Lforward);
+
+    __ get_method_counters(R19_method, R4_counters, Lforward);
+
+    if (TieredCompilation) {
+      Label Lno_mdo, Loverflow;
+      const int increment = InvocationCounter::count_increment;
+      const int mask = ((1 << Tier0BackedgeNotifyFreqLog) - 1) << InvocationCounter::count_shift;
+      if (ProfileInterpreter) {
+        Register Rmdo = Rscratch1;
+
+        // If no method data exists, go to profile_continue.
+        __ ld(Rmdo, in_bytes(Method::method_data_offset()), R19_method);
+        __ cmpdi(CCR0, Rmdo, 0);
+        __ beq(CCR0, Lno_mdo);
+
+        // Increment backedge counter in the MDO.
+        const int mdo_bc_offs = in_bytes(MethodData::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
+        __ lwz(Rscratch2, mdo_bc_offs, Rmdo);
+        __ load_const_optimized(Rscratch3, mask, R0);
+        __ addi(Rscratch2, Rscratch2, increment);
+        __ stw(Rscratch2, mdo_bc_offs, Rmdo);
+        __ and_(Rscratch3, Rscratch2, Rscratch3);
+        __ bne(CCR0, Lforward);
+        __ b(Loverflow);
+      }
+
+      // If there's no MDO, increment counter in method.
+      const int mo_bc_offs = in_bytes(MethodCounters::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
+      __ bind(Lno_mdo);
+      __ lwz(Rscratch2, mo_bc_offs, R4_counters);
+      __ load_const_optimized(Rscratch3, mask, R0);
+      __ addi(Rscratch2, Rscratch2, increment);
+      __ stw(Rscratch2, mo_bc_offs, R19_method);
+      __ and_(Rscratch3, Rscratch2, Rscratch3);
+      __ bne(CCR0, Lforward);
+
+      __ bind(Loverflow);
+
+      // Notify point for loop, pass branch bytecode.
+      __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::frequency_counter_overflow), R14_bcp, true);
+
+      // Was an OSR adapter generated?
+      // O0 = osr nmethod
+      __ cmpdi(CCR0, R3_RET, 0);
+      __ beq(CCR0, Lforward);
+
+      // Has the nmethod been invalidated already?
+      __ lwz(R0, nmethod::entry_bci_offset(), R3_RET);
+      __ cmpwi(CCR0, R0, InvalidOSREntryBci);
+      __ beq(CCR0, Lforward);
+
+      // Migrate the interpreter frame off of the stack.
+      // We can use all registers because we will not return to interpreter from this point.
+
+      // Save nmethod.
+      const Register osr_nmethod = R31;
+      __ mr(osr_nmethod, R3_RET);
+      __ set_top_ijava_frame_at_SP_as_last_Java_frame(R1_SP, R11_scratch1);
+      __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::OSR_migration_begin), R16_thread);
+      __ reset_last_Java_frame();
+      // OSR buffer is in ARG1.
+
+      // Remove the interpreter frame.
+      __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ R0, R11_scratch1, R12_scratch2);
+
+      // Jump to the osr code.
+      __ ld(R11_scratch1, nmethod::osr_entry_point_offset(), osr_nmethod);
+      __ mtlr(R0);
+      __ mtctr(R11_scratch1);
+      __ bctr();
+
+    } else {
+
+      const Register invoke_ctr = Rscratch1;
+      // Update Backedge branch separately from invocations.
+      __ increment_backedge_counter(R4_counters, invoke_ctr, Rscratch2, Rscratch3);
+
+      if (ProfileInterpreter) {
+        __ test_invocation_counter_for_mdp(invoke_ctr, Rscratch2, Lforward);
+        if (UseOnStackReplacement) {
+          __ test_backedge_count_for_osr(bumped_count, R14_bcp, Rscratch2);
+        }
+      } else {
+        if (UseOnStackReplacement) {
+          __ test_backedge_count_for_osr(invoke_ctr, R14_bcp, Rscratch2);
+        }
+      }
+    }
+
+    __ bind(Lforward);
+
+  } else {
+    // Bump bytecode pointer by displacement (take the branch).
+    __ add(R14_bcp, Rdisp, R14_bcp); // Add to bc addr.
+  }
+  // Continue with bytecode @ target.
+  // %%%%% Like Intel, could speed things up by moving bytecode fetch to code above,
+  // %%%%% and changing dispatch_next to dispatch_only.
+  __ dispatch_next(vtos);
+}
+
+// Helper function for if_cmp* methods below.
+// Factored out common compare and branch code.
+void TemplateTable::if_cmp_common(Register Rfirst, Register Rsecond, Register Rscratch1, Register Rscratch2, Condition cc, bool is_jint, bool cmp0) {
+  Label Lnot_taken;
+  // Note: The condition code we get is the condition under which we
+  // *fall through*! So we have to inverse the CC here.
+
+  if (is_jint) {
+    if (cmp0) {
+      __ cmpwi(CCR0, Rfirst, 0);
+    } else {
+      __ cmpw(CCR0, Rfirst, Rsecond);
+    }
+  } else {
+    if (cmp0) {
+      __ cmpdi(CCR0, Rfirst, 0);
+    } else {
+      __ cmpd(CCR0, Rfirst, Rsecond);
+    }
+  }
+  branch_conditional(CCR0, cc, Lnot_taken, /*invert*/ true);
+
+  // Conition is false => Jump!
+  branch(false, false);
+
+  // Condition is not true => Continue.
+  __ align(32, 12);
+  __ bind(Lnot_taken);
+  __ profile_not_taken_branch(Rscratch1, Rscratch2);
+}
+
+// Compare integer values with zero and fall through if CC holds, branch away otherwise.
+void TemplateTable::if_0cmp(Condition cc) {
+  transition(itos, vtos);
+
+  if_cmp_common(R17_tos, noreg, R11_scratch1, R12_scratch2, cc, true, true);
+}
+
+// Compare integer values and fall through if CC holds, branch away otherwise.
+//
+// Interface:
+//  - Rfirst: First operand  (older stack value)
+//  - tos:    Second operand (younger stack value)
+void TemplateTable::if_icmp(Condition cc) {
+  transition(itos, vtos);
+
+  const Register Rfirst  = R0,
+                 Rsecond = R17_tos;
+
+  __ pop_i(Rfirst);
+  if_cmp_common(Rfirst, Rsecond, R11_scratch1, R12_scratch2, cc, true, false);
+}
+
+void TemplateTable::if_nullcmp(Condition cc) {
+  transition(atos, vtos);
+
+  if_cmp_common(R17_tos, noreg, R11_scratch1, R12_scratch2, cc, false, true);
+}
+
+void TemplateTable::if_acmp(Condition cc) {
+  transition(atos, vtos);
+
+  const Register Rfirst  = R0,
+                 Rsecond = R17_tos;
+
+  __ pop_ptr(Rfirst);
+  if_cmp_common(Rfirst, Rsecond, R11_scratch1, R12_scratch2, cc, false, false);
+}
+
+void TemplateTable::ret() {
+  locals_index(R11_scratch1);
+  __ load_local_ptr(R17_tos, R11_scratch1, R11_scratch1);
+
+  __ profile_ret(vtos, R17_tos, R11_scratch1, R12_scratch2);
+
+  __ ld(R11_scratch1, in_bytes(Method::const_offset()), R19_method);
+  __ add(R11_scratch1, R17_tos, R11_scratch1);
+  __ addi(R14_bcp, R11_scratch1, in_bytes(ConstMethod::codes_offset()));
+  __ dispatch_next(vtos);
+}
+
+void TemplateTable::wide_ret() {
+  transition(vtos, vtos);
+
+  const Register Rindex = R3_ARG1,
+                 Rscratch1 = R11_scratch1,
+                 Rscratch2 = R12_scratch2;
+
+  locals_index_wide(Rindex);
+  __ load_local_ptr(R17_tos, R17_tos, Rindex);
+  __ profile_ret(vtos, R17_tos, Rscratch1, R12_scratch2);
+  // Tos now contains the bci, compute the bcp from that.
+  __ ld(Rscratch1, in_bytes(Method::const_offset()), R19_method);
+  __ addi(Rscratch2, R17_tos, in_bytes(ConstMethod::codes_offset()));
+  __ add(R14_bcp, Rscratch1, Rscratch2);
+  __ dispatch_next(vtos);
+}
+
+void TemplateTable::tableswitch() {
+  transition(itos, vtos);
+
+  Label Ldispatch, Ldefault_case;
+  Register Rlow_byte         = R3_ARG1,
+           Rindex            = Rlow_byte,
+           Rhigh_byte        = R4_ARG2,
+           Rdef_offset_addr  = R5_ARG3, // is going to contain address of default offset
+           Rscratch1         = R11_scratch1,
+           Rscratch2         = R12_scratch2,
+           Roffset           = R6_ARG4;
+
+  // Align bcp.
+  __ addi(Rdef_offset_addr, R14_bcp, BytesPerInt);
+  __ clrrdi(Rdef_offset_addr, Rdef_offset_addr, log2_long((jlong)BytesPerInt));
+
+  // Load lo & hi.
+  __ lwz(Rlow_byte, BytesPerInt, Rdef_offset_addr);
+  __ lwz(Rhigh_byte, BytesPerInt * 2, Rdef_offset_addr);
+
+  // Check for default case (=index outside [low,high]).
+  __ cmpw(CCR0, R17_tos, Rlow_byte);
+  __ cmpw(CCR1, R17_tos, Rhigh_byte);
+  __ blt(CCR0, Ldefault_case);
+  __ bgt(CCR1, Ldefault_case);
+
+  // Lookup dispatch offset.
+  __ sub(Rindex, R17_tos, Rlow_byte);
+  __ extsw(Rindex, Rindex);
+  __ profile_switch_case(Rindex, Rhigh_byte /* scratch */, Rscratch1, Rscratch2);
+  __ sldi(Rindex, Rindex, LogBytesPerInt);
+  __ addi(Rindex, Rindex, 3 * BytesPerInt);
+  __ lwax(Roffset, Rdef_offset_addr, Rindex);
+  __ b(Ldispatch);
+
+  __ bind(Ldefault_case);
+  __ profile_switch_default(Rhigh_byte, Rscratch1);
+  __ lwa(Roffset, 0, Rdef_offset_addr);
+
+  __ bind(Ldispatch);
+
+  __ add(R14_bcp, Roffset, R14_bcp);
+  __ dispatch_next(vtos);
+}
+
+void TemplateTable::lookupswitch() {
+  transition(itos, itos);
+  __ stop("lookupswitch bytecode should have been rewritten");
+}
+
+// Table switch using linear search through cases.
+// Bytecode stream format:
+// Bytecode (1) | 4-byte padding | default offset (4) | count (4) | value/offset pair1 (8) | value/offset pair2 (8) | ...
+// Note: Everything is big-endian format here. So on little endian machines, we have to revers offset and count and cmp value.
+void TemplateTable::fast_linearswitch() {
+  transition(itos, vtos);
+
+  Label Lloop_entry, Lsearch_loop, Lfound, Lcontinue_execution, Ldefault_case;
+
+  Register Rcount           = R3_ARG1,
+           Rcurrent_pair    = R4_ARG2,
+           Rdef_offset_addr = R5_ARG3, // Is going to contain address of default offset.
+           Roffset          = R31,     // Might need to survive C call.
+           Rvalue           = R12_scratch2,
+           Rscratch         = R11_scratch1,
+           Rcmp_value       = R17_tos;
+
+  // Align bcp.
+  __ addi(Rdef_offset_addr, R14_bcp, BytesPerInt);
+  __ clrrdi(Rdef_offset_addr, Rdef_offset_addr, log2_long((jlong)BytesPerInt));
+
+  // Setup loop counter and limit.
+  __ lwz(Rcount, BytesPerInt, Rdef_offset_addr);    // Load count.
+  __ addi(Rcurrent_pair, Rdef_offset_addr, 2 * BytesPerInt); // Rcurrent_pair now points to first pair.
+
+  // Set up search loop.
+  __ cmpwi(CCR0, Rcount, 0);
+  __ beq(CCR0, Ldefault_case);
+
+  __ mtctr(Rcount);
+
+  // linear table search
+  __ bind(Lsearch_loop);
+
+  __ lwz(Rvalue, 0, Rcurrent_pair);
+  __ lwa(Roffset, 1 * BytesPerInt, Rcurrent_pair);
+
+  __ cmpw(CCR0, Rvalue, Rcmp_value);
+  __ beq(CCR0, Lfound);
+
+  __ addi(Rcurrent_pair, Rcurrent_pair, 2 * BytesPerInt);
+  __ bdnz(Lsearch_loop);
+
+  // default case
+  __ bind(Ldefault_case);
+
+  __ lwa(Roffset, 0, Rdef_offset_addr);
+  if (ProfileInterpreter) {
+    __ profile_switch_default(Rdef_offset_addr, Rcount/* scratch */);
+    __ b(Lcontinue_execution);
+  }
+
+  // Entry found, skip Roffset bytecodes and continue.
+  __ bind(Lfound);
+  if (ProfileInterpreter) {
+    // Calc the num of the pair we hit. Careful, Rcurrent_pair points 2 ints
+    // beyond the actual current pair due to the auto update load above!
+    __ sub(Rcurrent_pair, Rcurrent_pair, Rdef_offset_addr);
+    __ addi(Rcurrent_pair, Rcurrent_pair, - 2 * BytesPerInt);
+    __ srdi(Rcurrent_pair, Rcurrent_pair, LogBytesPerInt + 1);
+    __ profile_switch_case(Rcurrent_pair, Rcount /*scratch*/, Rdef_offset_addr/*scratch*/, Rscratch);
+    __ bind(Lcontinue_execution);
+  }
+  __ add(R14_bcp, Roffset, R14_bcp);
+  __ dispatch_next(vtos);
+}
+
+// Table switch using binary search (value/offset pairs are ordered).
+// Bytecode stream format:
+// Bytecode (1) | 4-byte padding | default offset (4) | count (4) | value/offset pair1 (8) | value/offset pair2 (8) | ...
+// Note: Everything is big-endian format here. So on little endian machines, we have to revers offset and count and cmp value.
+void TemplateTable::fast_binaryswitch() {
+
+  transition(itos, vtos);
+  // Implementation using the following core algorithm: (copied from Intel)
+  //
+  // int binary_search(int key, LookupswitchPair* array, int n) {
+  //   // Binary search according to "Methodik des Programmierens" by
+  //   // Edsger W. Dijkstra and W.H.J. Feijen, Addison Wesley Germany 1985.
+  //   int i = 0;
+  //   int j = n;
+  //   while (i+1 < j) {
+  //     // invariant P: 0 <= i < j <= n and (a[i] <= key < a[j] or Q)
+  //     // with      Q: for all i: 0 <= i < n: key < a[i]
+  //     // where a stands for the array and assuming that the (inexisting)
+  //     // element a[n] is infinitely big.
+  //     int h = (i + j) >> 1;
+  //     // i < h < j
+  //     if (key < array[h].fast_match()) {
+  //       j = h;
+  //     } else {
+  //       i = h;
+  //     }
+  //   }
+  //   // R: a[i] <= key < a[i+1] or Q
+  //   // (i.e., if key is within array, i is the correct index)
+  //   return i;
+  // }
+
+  // register allocation
+  const Register Rkey     = R17_tos;          // already set (tosca)
+  const Register Rarray   = R3_ARG1;
+  const Register Ri       = R4_ARG2;
+  const Register Rj       = R5_ARG3;
+  const Register Rh       = R6_ARG4;
+  const Register Rscratch = R11_scratch1;
+
+  const int log_entry_size = 3;
+  const int entry_size = 1 << log_entry_size;
+
+  Label found;
+
+  // Find Array start,
+  __ addi(Rarray, R14_bcp, 3 * BytesPerInt);
+  __ clrrdi(Rarray, Rarray, log2_long((jlong)BytesPerInt));
+
+  // initialize i & j
+  __ li(Ri,0);
+  __ lwz(Rj, -BytesPerInt, Rarray);
+
+  // and start.
+  Label entry;
+  __ b(entry);
+
+  // binary search loop
+  { Label loop;
+    __ bind(loop);
+    // int h = (i + j) >> 1;
+    __ srdi(Rh, Rh, 1);
+    // if (key < array[h].fast_match()) {
+    //   j = h;
+    // } else {
+    //   i = h;
+    // }
+    __ sldi(Rscratch, Rh, log_entry_size);
+    __ lwzx(Rscratch, Rscratch, Rarray);
+
+    // if (key < current value)
+    //   Rh = Rj
+    // else
+    //   Rh = Ri
+    Label Lgreater;
+    __ cmpw(CCR0, Rkey, Rscratch);
+    __ bge(CCR0, Lgreater);
+    __ mr(Rj, Rh);
+    __ b(entry);
+    __ bind(Lgreater);
+    __ mr(Ri, Rh);
+
+    // while (i+1 < j)
+    __ bind(entry);
+    __ addi(Rscratch, Ri, 1);
+    __ cmpw(CCR0, Rscratch, Rj);
+    __ add(Rh, Ri, Rj); // start h = i + j >> 1;
+
+    __ blt(CCR0, loop);
+  }
+
+  // End of binary search, result index is i (must check again!).
+  Label default_case;
+  Label continue_execution;
+  if (ProfileInterpreter) {
+    __ mr(Rh, Ri);              // Save index in i for profiling.
+  }
+  // Ri = value offset
+  __ sldi(Ri, Ri, log_entry_size);
+  __ add(Ri, Ri, Rarray);
+  __ lwz(Rscratch, 0, Ri);
+
+  Label not_found;
+  // Ri = offset offset
+  __ cmpw(CCR0, Rkey, Rscratch);
+  __ beq(CCR0, not_found);
+  // entry not found -> j = default offset
+  __ lwz(Rj, -2 * BytesPerInt, Rarray);
+  __ b(default_case);
+
+  __ bind(not_found);
+  // entry found -> j = offset
+  __ profile_switch_case(Rh, Rj, Rscratch, Rkey);
+  __ lwz(Rj, BytesPerInt, Ri);
+
+  if (ProfileInterpreter) {
+    __ b(continue_execution);
+  }
+
+  __ bind(default_case); // fall through (if not profiling)
+  __ profile_switch_default(Ri, Rscratch);
+
+  __ bind(continue_execution);
+
+  __ extsw(Rj, Rj);
+  __ add(R14_bcp, Rj, R14_bcp);
+  __ dispatch_next(vtos);
+}
+
+void TemplateTable::_return(TosState state) {
+  transition(state, state);
+  assert(_desc->calls_vm(),
+         "inconsistent calls_vm information"); // call in remove_activation
+
+  if (_desc->bytecode() == Bytecodes::_return_register_finalizer) {
+
+    Register Rscratch     = R11_scratch1,
+             Rklass       = R12_scratch2,
+             Rklass_flags = Rklass;
+    Label Lskip_register_finalizer;
+
+    // Check if the method has the FINALIZER flag set and call into the VM to finalize in this case.
+    assert(state == vtos, "only valid state");
+    __ ld(R17_tos, 0, R18_locals);
+
+    // Load klass of this obj.
+    __ load_klass(Rklass, R17_tos);
+    __ lwz(Rklass_flags, in_bytes(Klass::access_flags_offset()), Rklass);
+    __ testbitdi(CCR0, R0, Rklass_flags, exact_log2(JVM_ACC_HAS_FINALIZER));
+    __ bfalse(CCR0, Lskip_register_finalizer);
+
+    __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::register_finalizer), R17_tos /* obj */);
+
+    __ align(32, 12);
+    __ bind(Lskip_register_finalizer);
+  }
+
+  // Move the result value into the correct register and remove memory stack frame.
+  __ remove_activation(state, /* throw_monitor_exception */ true);
+  // Restoration of lr done by remove_activation.
+  switch (state) {
+    case ltos:
+    case btos:
+    case ctos:
+    case stos:
+    case atos:
+    case itos: __ mr(R3_RET, R17_tos); break;
+    case ftos:
+    case dtos: __ fmr(F1_RET, F15_ftos); break;
+    case vtos: // This might be a constructor. Final fields (and volatile fields on PPC64) need
+               // to get visible before the reference to the object gets stored anywhere.
+               __ membar(Assembler::StoreStore); break;
+    default  : ShouldNotReachHere();
+  }
+  __ blr();
+}
+
+// ============================================================================
+// Constant pool cache access
+//
+// Memory ordering:
+//
+// Like done in C++ interpreter, we load the fields
+//   - _indices
+//   - _f12_oop
+// acquired, because these are asked if the cache is already resolved. We don't
+// want to float loads above this check.
+// See also comments in ConstantPoolCacheEntry::bytecode_1(),
+// ConstantPoolCacheEntry::bytecode_2() and ConstantPoolCacheEntry::f1();
+
+// Call into the VM if call site is not yet resolved
+//
+// Input regs:
+//   - None, all passed regs are outputs.
+//
+// Returns:
+//   - Rcache:  The const pool cache entry that contains the resolved result.
+//   - Rresult: Either noreg or output for f1/f2.
+//
+// Kills:
+//   - Rscratch
+void TemplateTable::resolve_cache_and_index(int byte_no, Register Rcache, Register Rscratch, size_t index_size) {
+
+  __ get_cache_and_index_at_bcp(Rcache, 1, index_size);
+  Label Lresolved, Ldone;
+
+  assert(byte_no == f1_byte || byte_no == f2_byte, "byte_no out of range");
+  // We are resolved if the indices offset contains the current bytecode.
+  // Big Endian:
+  __ lbz(Rscratch, in_bytes(ConstantPoolCache::base_offset() + ConstantPoolCacheEntry::indices_offset()) + 7 - (byte_no + 1), Rcache);
+  // Acquire by cmp-br-isync (see below).
+  __ cmpdi(CCR0, Rscratch, (int)bytecode());
+  __ beq(CCR0, Lresolved);
+
+  address entry = NULL;
+  switch (bytecode()) {
+    case Bytecodes::_getstatic      : // fall through
+    case Bytecodes::_putstatic      : // fall through
+    case Bytecodes::_getfield       : // fall through
+    case Bytecodes::_putfield       : entry = CAST_FROM_FN_PTR(address, InterpreterRuntime::resolve_get_put); break;
+    case Bytecodes::_invokevirtual  : // fall through
+    case Bytecodes::_invokespecial  : // fall through
+    case Bytecodes::_invokestatic   : // fall through
+    case Bytecodes::_invokeinterface: entry = CAST_FROM_FN_PTR(address, InterpreterRuntime::resolve_invoke); break;
+    case Bytecodes::_invokehandle   : entry = CAST_FROM_FN_PTR(address, InterpreterRuntime::resolve_invokehandle); break;
+    case Bytecodes::_invokedynamic  : entry = CAST_FROM_FN_PTR(address, InterpreterRuntime::resolve_invokedynamic); break;
+    default                         : ShouldNotReachHere(); break;
+  }
+  __ li(R4_ARG2, (int)bytecode());
+  __ call_VM(noreg, entry, R4_ARG2, true);
+
+  // Update registers with resolved info.
+  __ get_cache_and_index_at_bcp(Rcache, 1, index_size);
+  __ b(Ldone);
+
+  __ bind(Lresolved);
+  __ isync(); // Order load wrt. succeeding loads.
+  __ bind(Ldone);
+}
+
+// Load the constant pool cache entry at field accesses into registers.
+// The Rcache and Rindex registers must be set before call.
+// Input:
+//   - Rcache, Rindex
+// Output:
+//   - Robj, Roffset, Rflags
+void TemplateTable::load_field_cp_cache_entry(Register Robj,
+                                              Register Rcache,
+                                              Register Rindex /* unused on PPC64 */,
+                                              Register Roffset,
+                                              Register Rflags,
+                                              bool is_static = false) {
+  assert_different_registers(Rcache, Rflags, Roffset);
+  // assert(Rindex == noreg, "parameter not used on PPC64");
+
+  ByteSize cp_base_offset = ConstantPoolCache::base_offset();
+  __ ld(Rflags, in_bytes(cp_base_offset) + in_bytes(ConstantPoolCacheEntry::flags_offset()), Rcache);
+  __ ld(Roffset, in_bytes(cp_base_offset) + in_bytes(ConstantPoolCacheEntry::f2_offset()), Rcache);
+  if (is_static) {
+    __ ld(Robj, in_bytes(cp_base_offset) + in_bytes(ConstantPoolCacheEntry::f1_offset()), Rcache);
+    __ ld(Robj, in_bytes(Klass::java_mirror_offset()), Robj);
+    // Acquire not needed here. Following access has an address dependency on this value.
+  }
+}
+
+// Load the constant pool cache entry at invokes into registers.
+// Resolve if necessary.
+
+// Input Registers:
+//   - None, bcp is used, though
+//
+// Return registers:
+//   - Rmethod       (f1 field or f2 if invokevirtual)
+//   - Ritable_index (f2 field)
+//   - Rflags        (flags field)
+//
+// Kills:
+//   - R21
+//
+void TemplateTable::load_invoke_cp_cache_entry(int byte_no,
+                                               Register Rmethod,
+                                               Register Ritable_index,
+                                               Register Rflags,
+                                               bool is_invokevirtual,
+                                               bool is_invokevfinal,
+                                               bool is_invokedynamic) {
+
+  ByteSize cp_base_offset = ConstantPoolCache::base_offset();
+  // Determine constant pool cache field offsets.
+  assert(is_invokevirtual == (byte_no == f2_byte), "is_invokevirtual flag redundant");
+  const int method_offset = in_bytes(cp_base_offset + (is_invokevirtual ? ConstantPoolCacheEntry::f2_offset() : ConstantPoolCacheEntry::f1_offset()));
+  const int flags_offset  = in_bytes(cp_base_offset + ConstantPoolCacheEntry::flags_offset());
+  // Access constant pool cache fields.
+  const int index_offset  = in_bytes(cp_base_offset + ConstantPoolCacheEntry::f2_offset());
+
+  Register Rcache = R21_tmp1; // Note: same register as R21_sender_SP.
+
+  if (is_invokevfinal) {
+    assert(Ritable_index == noreg, "register not used");
+    // Already resolved.
+    __ get_cache_and_index_at_bcp(Rcache, 1);
+  } else {
+    resolve_cache_and_index(byte_no, Rcache, R0, is_invokedynamic ? sizeof(u4) : sizeof(u2));
+  }
+
+  __ ld(Rmethod, method_offset, Rcache);
+  __ ld(Rflags, flags_offset, Rcache);
+
+  if (Ritable_index != noreg) {
+    __ ld(Ritable_index, index_offset, Rcache);
+  }
+}
+
+// ============================================================================
+// Field access
+
+// Volatile variables demand their effects be made known to all CPU's
+// in order. Store buffers on most chips allow reads & writes to
+// reorder; the JMM's ReadAfterWrite.java test fails in -Xint mode
+// without some kind of memory barrier (i.e., it's not sufficient that
+// the interpreter does not reorder volatile references, the hardware
+// also must not reorder them).
+//
+// According to the new Java Memory Model (JMM):
+// (1) All volatiles are serialized wrt to each other. ALSO reads &
+//     writes act as aquire & release, so:
+// (2) A read cannot let unrelated NON-volatile memory refs that
+//     happen after the read float up to before the read. It's OK for
+//     non-volatile memory refs that happen before the volatile read to
+//     float down below it.
+// (3) Similar a volatile write cannot let unrelated NON-volatile
+//     memory refs that happen BEFORE the write float down to after the
+//     write. It's OK for non-volatile memory refs that happen after the
+//     volatile write to float up before it.
+//
+// We only put in barriers around volatile refs (they are expensive),
+// not _between_ memory refs (that would require us to track the
+// flavor of the previous memory refs). Requirements (2) and (3)
+// require some barriers before volatile stores and after volatile
+// loads. These nearly cover requirement (1) but miss the
+// volatile-store-volatile-load case.  This final case is placed after
+// volatile-stores although it could just as well go before
+// volatile-loads.
+
+// The registers cache and index expected to be set before call.
+// Correct values of the cache and index registers are preserved.
+// Kills:
+//   Rcache (if has_tos)
+//   Rscratch
+void TemplateTable::jvmti_post_field_access(Register Rcache, Register Rscratch, bool is_static, bool has_tos) {
+
+  assert_different_registers(Rcache, Rscratch);
+
+  if (JvmtiExport::can_post_field_access()) {
+    ByteSize cp_base_offset = ConstantPoolCache::base_offset();
+    Label Lno_field_access_post;
+
+    // Check if post field access in enabled.
+    int offs = __ load_const_optimized(Rscratch, JvmtiExport::get_field_access_count_addr(), R0, true);
+    __ lwz(Rscratch, offs, Rscratch);
+
+    __ cmpwi(CCR0, Rscratch, 0);
+    __ beq(CCR0, Lno_field_access_post);
+
+    // Post access enabled - do it!
+    __ addi(Rcache, Rcache, in_bytes(cp_base_offset));
+    if (is_static) {
+      __ li(R17_tos, 0);
+    } else {
+      if (has_tos) {
+        // The fast bytecode versions have obj ptr in register.
+        // Thus, save object pointer before call_VM() clobbers it
+        // put object on tos where GC wants it.
+        __ push_ptr(R17_tos);
+      } else {
+        // Load top of stack (do not pop the value off the stack).
+        __ ld(R17_tos, Interpreter::expr_offset_in_bytes(0), R15_esp);
+      }
+      __ verify_oop(R17_tos);
+    }
+    // tos:   object pointer or NULL if static
+    // cache: cache entry pointer
+    __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::post_field_access), R17_tos, Rcache);
+    if (!is_static && has_tos) {
+      // Restore object pointer.
+      __ pop_ptr(R17_tos);
+      __ verify_oop(R17_tos);
+    } else {
+      // Cache is still needed to get class or obj.
+      __ get_cache_and_index_at_bcp(Rcache, 1);
+    }
+
+    __ align(32, 12);
+    __ bind(Lno_field_access_post);
+  }
+}
+
+// kills R11_scratch1
+void TemplateTable::pop_and_check_object(Register Roop) {
+  Register Rtmp = R11_scratch1;
+
+  assert_different_registers(Rtmp, Roop);
+  __ pop_ptr(Roop);
+  // For field access must check obj.
+  __ null_check_throw(Roop, -1, Rtmp);
+  __ verify_oop(Roop);
+}
+
+// PPC64: implement volatile loads as fence-store-acquire.
+void TemplateTable::getfield_or_static(int byte_no, bool is_static) {
+  transition(vtos, vtos);
+
+  Label Lacquire, Lisync;
+
+  const Register Rcache        = R3_ARG1,
+                 Rclass_or_obj = R22_tmp2,
+                 Roffset       = R23_tmp3,
+                 Rflags        = R31,
+                 Rbtable       = R5_ARG3,
+                 Rbc           = R6_ARG4,
+                 Rscratch      = R12_scratch2;
+
+  static address field_branch_table[number_of_states],
+                 static_branch_table[number_of_states];
+
+  address* branch_table = is_static ? static_branch_table : field_branch_table;
+
+  // Get field offset.
+  resolve_cache_and_index(byte_no, Rcache, Rscratch, sizeof(u2));
+
+  // JVMTI support
+  jvmti_post_field_access(Rcache, Rscratch, is_static, false);
+
+  // Load after possible GC.
+  load_field_cp_cache_entry(Rclass_or_obj, Rcache, noreg, Roffset, Rflags, is_static);
+
+  // Load pointer to branch table.
+  __ load_const_optimized(Rbtable, (address)branch_table, Rscratch);
+
+  // Get volatile flag.
+  __ rldicl(Rscratch, Rflags, 64-ConstantPoolCacheEntry::is_volatile_shift, 63); // Extract volatile bit.
+  // Note: sync is needed before volatile load on PPC64.
+
+  // Check field type.
+  __ rldicl(Rflags, Rflags, 64-ConstantPoolCacheEntry::tos_state_shift, 64-ConstantPoolCacheEntry::tos_state_bits);
+
+#ifdef ASSERT
+  Label LFlagInvalid;
+  __ cmpldi(CCR0, Rflags, number_of_states);
+  __ bge(CCR0, LFlagInvalid);
+#endif
+
+  // Load from branch table and dispatch (volatile case: one instruction ahead).
+  __ sldi(Rflags, Rflags, LogBytesPerWord);
+  __ cmpwi(CCR6, Rscratch, 1); // Volatile?
+  if (support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    __ sldi(Rscratch, Rscratch, exact_log2(BytesPerInstWord)); // Volatile ? size of 1 instruction : 0.
+  }
+  __ ldx(Rbtable, Rbtable, Rflags);
+
+  // Get the obj from stack.
+  if (!is_static) {
+    pop_and_check_object(Rclass_or_obj); // Kills R11_scratch1.
+  } else {
+    __ verify_oop(Rclass_or_obj);
+  }
+
+  if (support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    __ subf(Rbtable, Rscratch, Rbtable); // Point to volatile/non-volatile entry point.
+  }
+  __ mtctr(Rbtable);
+  __ bctr();
+
+#ifdef ASSERT
+  __ bind(LFlagInvalid);
+  __ stop("got invalid flag", 0x654);
+
+  // __ bind(Lvtos);
+  address pc_before_fence = __ pc();
+  __ fence(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(__ pc() - pc_before_fence == (ptrdiff_t)BytesPerInstWord, "must be single instruction");
+  assert(branch_table[vtos] == 0, "can't compute twice");
+  branch_table[vtos] = __ pc(); // non-volatile_entry point
+  __ stop("vtos unexpected", 0x655);
+#endif
+
+  __ align(32, 28, 28); // Align load.
+  // __ bind(Ldtos);
+  __ fence(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[dtos] == 0, "can't compute twice");
+  branch_table[dtos] = __ pc(); // non-volatile_entry point
+  __ lfdx(F15_ftos, Rclass_or_obj, Roffset);
+  __ push(dtos);
+  if (!is_static) patch_bytecode(Bytecodes::_fast_dgetfield, Rbc, Rscratch);
+  {
+    Label acquire_double;
+    __ beq(CCR6, acquire_double); // Volatile?
+    __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+    __ bind(acquire_double);
+    __ fcmpu(CCR0, F15_ftos, F15_ftos); // Acquire by cmp-br-isync.
+    __ beq_predict_taken(CCR0, Lisync);
+    __ b(Lisync); // In case of NAN.
+  }
+
+  __ align(32, 28, 28); // Align load.
+  // __ bind(Lftos);
+  __ fence(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[ftos] == 0, "can't compute twice");
+  branch_table[ftos] = __ pc(); // non-volatile_entry point
+  __ lfsx(F15_ftos, Rclass_or_obj, Roffset);
+  __ push(ftos);
+  if (!is_static) { patch_bytecode(Bytecodes::_fast_fgetfield, Rbc, Rscratch); }
+  {
+    Label acquire_float;
+    __ beq(CCR6, acquire_float); // Volatile?
+    __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+    __ bind(acquire_float);
+    __ fcmpu(CCR0, F15_ftos, F15_ftos); // Acquire by cmp-br-isync.
+    __ beq_predict_taken(CCR0, Lisync);
+    __ b(Lisync); // In case of NAN.
+  }
+
+  __ align(32, 28, 28); // Align load.
+  // __ bind(Litos);
+  __ fence(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[itos] == 0, "can't compute twice");
+  branch_table[itos] = __ pc(); // non-volatile_entry point
+  __ lwax(R17_tos, Rclass_or_obj, Roffset);
+  __ push(itos);
+  if (!is_static) patch_bytecode(Bytecodes::_fast_igetfield, Rbc, Rscratch);
+  __ beq(CCR6, Lacquire); // Volatile?
+  __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+  __ align(32, 28, 28); // Align load.
+  // __ bind(Lltos);
+  __ fence(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[ltos] == 0, "can't compute twice");
+  branch_table[ltos] = __ pc(); // non-volatile_entry point
+  __ ldx(R17_tos, Rclass_or_obj, Roffset);
+  __ push(ltos);
+  if (!is_static) patch_bytecode(Bytecodes::_fast_lgetfield, Rbc, Rscratch);
+  __ beq(CCR6, Lacquire); // Volatile?
+  __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+  __ align(32, 28, 28); // Align load.
+  // __ bind(Lbtos);
+  __ fence(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[btos] == 0, "can't compute twice");
+  branch_table[btos] = __ pc(); // non-volatile_entry point
+  __ lbzx(R17_tos, Rclass_or_obj, Roffset);
+  __ extsb(R17_tos, R17_tos);
+  __ push(btos);
+  if (!is_static) patch_bytecode(Bytecodes::_fast_bgetfield, Rbc, Rscratch);
+  __ beq(CCR6, Lacquire); // Volatile?
+  __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+  __ align(32, 28, 28); // Align load.
+  // __ bind(Lctos);
+  __ fence(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[ctos] == 0, "can't compute twice");
+  branch_table[ctos] = __ pc(); // non-volatile_entry point
+  __ lhzx(R17_tos, Rclass_or_obj, Roffset);
+  __ push(ctos);
+  if (!is_static) patch_bytecode(Bytecodes::_fast_cgetfield, Rbc, Rscratch);
+  __ beq(CCR6, Lacquire); // Volatile?
+  __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+  __ align(32, 28, 28); // Align load.
+  // __ bind(Lstos);
+  __ fence(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[stos] == 0, "can't compute twice");
+  branch_table[stos] = __ pc(); // non-volatile_entry point
+  __ lhax(R17_tos, Rclass_or_obj, Roffset);
+  __ push(stos);
+  if (!is_static) patch_bytecode(Bytecodes::_fast_sgetfield, Rbc, Rscratch);
+  __ beq(CCR6, Lacquire); // Volatile?
+  __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+  __ align(32, 28, 28); // Align load.
+  // __ bind(Latos);
+  __ fence(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[atos] == 0, "can't compute twice");
+  branch_table[atos] = __ pc(); // non-volatile_entry point
+  __ load_heap_oop(R17_tos, (RegisterOrConstant)Roffset, Rclass_or_obj);
+  __ verify_oop(R17_tos);
+  __ push(atos);
+  //__ dcbt(R17_tos); // prefetch
+  if (!is_static) patch_bytecode(Bytecodes::_fast_agetfield, Rbc, Rscratch);
+  __ beq(CCR6, Lacquire); // Volatile?
+  __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+  __ align(32, 12);
+  __ bind(Lacquire);
+  __ twi_0(R17_tos);
+  __ bind(Lisync);
+  __ isync(); // acquire
+
+#ifdef ASSERT
+  for (int i = 0; i<number_of_states; ++i) {
+    assert(branch_table[i], "get initialization");
+    //tty->print_cr("get: %s_branch_table[%d] = 0x%llx (opcode 0x%llx)",
+    //              is_static ? "static" : "field", i, branch_table[i], *((unsigned int*)branch_table[i]));
+  }
+#endif
+}
+
+void TemplateTable::getfield(int byte_no) {
+  getfield_or_static(byte_no, false);
+}
+
+void TemplateTable::getstatic(int byte_no) {
+  getfield_or_static(byte_no, true);
+}
+
+// The registers cache and index expected to be set before call.
+// The function may destroy various registers, just not the cache and index registers.
+void TemplateTable::jvmti_post_field_mod(Register Rcache, Register Rscratch, bool is_static) {
+
+  assert_different_registers(Rcache, Rscratch, R6_ARG4);
+
+  if (JvmtiExport::can_post_field_modification()) {
+    Label Lno_field_mod_post;
+
+    // Check if post field access in enabled.
+    int offs = __ load_const_optimized(Rscratch, JvmtiExport::get_field_modification_count_addr(), R0, true);
+    __ lwz(Rscratch, offs, Rscratch);
+
+    __ cmpwi(CCR0, Rscratch, 0);
+    __ beq(CCR0, Lno_field_mod_post);
+
+    // Do the post
+    ByteSize cp_base_offset = ConstantPoolCache::base_offset();
+    const Register Robj = Rscratch;
+
+    __ addi(Rcache, Rcache, in_bytes(cp_base_offset));
+    if (is_static) {
+      // Life is simple. Null out the object pointer.
+      __ li(Robj, 0);
+    } else {
+      // In case of the fast versions, value lives in registers => put it back on tos.
+      int offs = Interpreter::expr_offset_in_bytes(0);
+      Register base = R15_esp;
+      switch(bytecode()) {
+        case Bytecodes::_fast_aputfield: __ push_ptr(); offs+= Interpreter::stackElementSize; break;
+        case Bytecodes::_fast_iputfield: // Fall through
+        case Bytecodes::_fast_bputfield: // Fall through
+        case Bytecodes::_fast_cputfield: // Fall through
+        case Bytecodes::_fast_sputfield: __ push_i(); offs+=  Interpreter::stackElementSize; break;
+        case Bytecodes::_fast_lputfield: __ push_l(); offs+=2*Interpreter::stackElementSize; break;
+        case Bytecodes::_fast_fputfield: __ push_f(); offs+=  Interpreter::stackElementSize; break;
+        case Bytecodes::_fast_dputfield: __ push_d(); offs+=2*Interpreter::stackElementSize; break;
+        default: {
+          offs = 0;
+          base = Robj;
+          const Register Rflags = Robj;
+          Label is_one_slot;
+          // Life is harder. The stack holds the value on top, followed by the
+          // object. We don't know the size of the value, though; it could be
+          // one or two words depending on its type. As a result, we must find
+          // the type to determine where the object is.
+          __ ld(Rflags, in_bytes(ConstantPoolCacheEntry::flags_offset()), Rcache); // Big Endian
+          __ rldicl(Rflags, Rflags, 64-ConstantPoolCacheEntry::tos_state_shift, 64-ConstantPoolCacheEntry::tos_state_bits);
+
+          __ cmpwi(CCR0, Rflags, ltos);
+          __ cmpwi(CCR1, Rflags, dtos);
+          __ addi(base, R15_esp, Interpreter::expr_offset_in_bytes(1));
+          __ crnor(/*CR0 eq*/2, /*CR1 eq*/4+2, /*CR0 eq*/2);
+          __ beq(CCR0, is_one_slot);
+          __ addi(base, R15_esp, Interpreter::expr_offset_in_bytes(2));
+          __ bind(is_one_slot);
+          break;
+        }
+      }
+      __ ld(Robj, offs, base);
+      __ verify_oop(Robj);
+    }
+
+    __ addi(R6_ARG4, R15_esp, Interpreter::expr_offset_in_bytes(0));
+    __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::post_field_modification), Robj, Rcache, R6_ARG4);
+    __ get_cache_and_index_at_bcp(Rcache, 1);
+
+    // In case of the fast versions, value lives in registers => put it back on tos.
+    switch(bytecode()) {
+      case Bytecodes::_fast_aputfield: __ pop_ptr(); break;
+      case Bytecodes::_fast_iputfield: // Fall through
+      case Bytecodes::_fast_bputfield: // Fall through
+      case Bytecodes::_fast_cputfield: // Fall through
+      case Bytecodes::_fast_sputfield: __ pop_i(); break;
+      case Bytecodes::_fast_lputfield: __ pop_l(); break;
+      case Bytecodes::_fast_fputfield: __ pop_f(); break;
+      case Bytecodes::_fast_dputfield: __ pop_d(); break;
+      default: break; // Nothin' to do.
+    }
+
+    __ align(32, 12);
+    __ bind(Lno_field_mod_post);
+  }
+}
+
+// PPC64: implement volatile stores as release-store (return bytecode contains an additional release).
+void TemplateTable::putfield_or_static(int byte_no, bool is_static) {
+  Label Lvolatile;
+
+  const Register Rcache        = R5_ARG3,  // Do not use ARG1/2 (causes trouble in jvmti_post_field_mod).
+                 Rclass_or_obj = R31,      // Needs to survive C call.
+                 Roffset       = R22_tmp2, // Needs to survive C call.
+                 Rflags        = R3_ARG1,
+                 Rbtable       = R4_ARG2,
+                 Rscratch      = R11_scratch1,
+                 Rscratch2     = R12_scratch2,
+                 Rscratch3     = R6_ARG4,
+                 Rbc           = Rscratch3;
+  const ConditionRegister CR_is_vol = CCR2; // Non-volatile condition register (survives runtime call in do_oop_store).
+
+  static address field_branch_table[number_of_states],
+                 static_branch_table[number_of_states];
+
+  address* branch_table = is_static ? static_branch_table : field_branch_table;
+
+  // Stack (grows up):
+  //  value
+  //  obj
+
+  // Load the field offset.
+  resolve_cache_and_index(byte_no, Rcache, Rscratch, sizeof(u2));
+  jvmti_post_field_mod(Rcache, Rscratch, is_static);
+  load_field_cp_cache_entry(Rclass_or_obj, Rcache, noreg, Roffset, Rflags, is_static);
+
+  // Load pointer to branch table.
+  __ load_const_optimized(Rbtable, (address)branch_table, Rscratch);
+
+  // Get volatile flag.
+  __ rldicl(Rscratch, Rflags, 64-ConstantPoolCacheEntry::is_volatile_shift, 63); // Extract volatile bit.
+
+  // Check the field type.
+  __ rldicl(Rflags, Rflags, 64-ConstantPoolCacheEntry::tos_state_shift, 64-ConstantPoolCacheEntry::tos_state_bits);
+
+#ifdef ASSERT
+  Label LFlagInvalid;
+  __ cmpldi(CCR0, Rflags, number_of_states);
+  __ bge(CCR0, LFlagInvalid);
+#endif
+
+  // Load from branch table and dispatch (volatile case: one instruction ahead).
+  __ sldi(Rflags, Rflags, LogBytesPerWord);
+  if (!support_IRIW_for_not_multiple_copy_atomic_cpu) { __ cmpwi(CR_is_vol, Rscratch, 1); } // Volatile?
+  __ sldi(Rscratch, Rscratch, exact_log2(BytesPerInstWord)); // Volatile? size of instruction 1 : 0.
+  __ ldx(Rbtable, Rbtable, Rflags);
+
+  __ subf(Rbtable, Rscratch, Rbtable); // Point to volatile/non-volatile entry point.
+  __ mtctr(Rbtable);
+  __ bctr();
+
+#ifdef ASSERT
+  __ bind(LFlagInvalid);
+  __ stop("got invalid flag", 0x656);
+
+  // __ bind(Lvtos);
+  address pc_before_release = __ pc();
+  __ release(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(__ pc() - pc_before_release == (ptrdiff_t)BytesPerInstWord, "must be single instruction");
+  assert(branch_table[vtos] == 0, "can't compute twice");
+  branch_table[vtos] = __ pc(); // non-volatile_entry point
+  __ stop("vtos unexpected", 0x657);
+#endif
+
+  __ align(32, 28, 28); // Align pop.
+  // __ bind(Ldtos);
+  __ release(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[dtos] == 0, "can't compute twice");
+  branch_table[dtos] = __ pc(); // non-volatile_entry point
+  __ pop(dtos);
+  if (!is_static) { pop_and_check_object(Rclass_or_obj); } // Kills R11_scratch1.
+  __ stfdx(F15_ftos, Rclass_or_obj, Roffset);
+  if (!is_static) { patch_bytecode(Bytecodes::_fast_dputfield, Rbc, Rscratch, true, byte_no); }
+  if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    __ beq(CR_is_vol, Lvolatile); // Volatile?
+  }
+  __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+  __ align(32, 28, 28); // Align pop.
+  // __ bind(Lftos);
+  __ release(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[ftos] == 0, "can't compute twice");
+  branch_table[ftos] = __ pc(); // non-volatile_entry point
+  __ pop(ftos);
+  if (!is_static) { pop_and_check_object(Rclass_or_obj); } // Kills R11_scratch1.
+  __ stfsx(F15_ftos, Rclass_or_obj, Roffset);
+  if (!is_static) { patch_bytecode(Bytecodes::_fast_fputfield, Rbc, Rscratch, true, byte_no); }
+  if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    __ beq(CR_is_vol, Lvolatile); // Volatile?
+  }
+  __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+  __ align(32, 28, 28); // Align pop.
+  // __ bind(Litos);
+  __ release(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[itos] == 0, "can't compute twice");
+  branch_table[itos] = __ pc(); // non-volatile_entry point
+  __ pop(itos);
+  if (!is_static) { pop_and_check_object(Rclass_or_obj); } // Kills R11_scratch1.
+  __ stwx(R17_tos, Rclass_or_obj, Roffset);
+  if (!is_static) { patch_bytecode(Bytecodes::_fast_iputfield, Rbc, Rscratch, true, byte_no); }
+  if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    __ beq(CR_is_vol, Lvolatile); // Volatile?
+  }
+  __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+  __ align(32, 28, 28); // Align pop.
+  // __ bind(Lltos);
+  __ release(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[ltos] == 0, "can't compute twice");
+  branch_table[ltos] = __ pc(); // non-volatile_entry point
+  __ pop(ltos);
+  if (!is_static) { pop_and_check_object(Rclass_or_obj); } // Kills R11_scratch1.
+  __ stdx(R17_tos, Rclass_or_obj, Roffset);
+  if (!is_static) { patch_bytecode(Bytecodes::_fast_lputfield, Rbc, Rscratch, true, byte_no); }
+  if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    __ beq(CR_is_vol, Lvolatile); // Volatile?
+  }
+  __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+  __ align(32, 28, 28); // Align pop.
+  // __ bind(Lbtos);
+  __ release(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[btos] == 0, "can't compute twice");
+  branch_table[btos] = __ pc(); // non-volatile_entry point
+  __ pop(btos);
+  if (!is_static) { pop_and_check_object(Rclass_or_obj); } // Kills R11_scratch1.
+  __ stbx(R17_tos, Rclass_or_obj, Roffset);
+  if (!is_static) { patch_bytecode(Bytecodes::_fast_bputfield, Rbc, Rscratch, true, byte_no); }
+  if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    __ beq(CR_is_vol, Lvolatile); // Volatile?
+  }
+  __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+  __ align(32, 28, 28); // Align pop.
+  // __ bind(Lctos);
+  __ release(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[ctos] == 0, "can't compute twice");
+  branch_table[ctos] = __ pc(); // non-volatile_entry point
+  __ pop(ctos);
+  if (!is_static) { pop_and_check_object(Rclass_or_obj); } // Kills R11_scratch1..
+  __ sthx(R17_tos, Rclass_or_obj, Roffset);
+  if (!is_static) { patch_bytecode(Bytecodes::_fast_cputfield, Rbc, Rscratch, true, byte_no); }
+  if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    __ beq(CR_is_vol, Lvolatile); // Volatile?
+  }
+  __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+  __ align(32, 28, 28); // Align pop.
+  // __ bind(Lstos);
+  __ release(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[stos] == 0, "can't compute twice");
+  branch_table[stos] = __ pc(); // non-volatile_entry point
+  __ pop(stos);
+  if (!is_static) { pop_and_check_object(Rclass_or_obj); } // Kills R11_scratch1.
+  __ sthx(R17_tos, Rclass_or_obj, Roffset);
+  if (!is_static) { patch_bytecode(Bytecodes::_fast_sputfield, Rbc, Rscratch, true, byte_no); }
+  if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    __ beq(CR_is_vol, Lvolatile); // Volatile?
+  }
+  __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+  __ align(32, 28, 28); // Align pop.
+  // __ bind(Latos);
+  __ release(); // Volatile entry point (one instruction before non-volatile_entry point).
+  assert(branch_table[atos] == 0, "can't compute twice");
+  branch_table[atos] = __ pc(); // non-volatile_entry point
+  __ pop(atos);
+  if (!is_static) { pop_and_check_object(Rclass_or_obj); } // kills R11_scratch1
+  do_oop_store(_masm, Rclass_or_obj, Roffset, R17_tos, Rscratch, Rscratch2, Rscratch3, _bs->kind(), false /* precise */, true /* check null */);
+  if (!is_static) { patch_bytecode(Bytecodes::_fast_aputfield, Rbc, Rscratch, true, byte_no); }
+  if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    __ beq(CR_is_vol, Lvolatile); // Volatile?
+    __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+    __ align(32, 12);
+    __ bind(Lvolatile);
+    __ fence();
+  }
+  // fallthru: __ b(Lexit);
+
+#ifdef ASSERT
+  for (int i = 0; i<number_of_states; ++i) {
+    assert(branch_table[i], "put initialization");
+    //tty->print_cr("put: %s_branch_table[%d] = 0x%llx (opcode 0x%llx)",
+    //              is_static ? "static" : "field", i, branch_table[i], *((unsigned int*)branch_table[i]));
+  }
+#endif
+}
+
+void TemplateTable::putfield(int byte_no) {
+  putfield_or_static(byte_no, false);
+}
+
+void TemplateTable::putstatic(int byte_no) {
+  putfield_or_static(byte_no, true);
+}
+
+// See SPARC. On PPC64, we have a different jvmti_post_field_mod which does the job.
+void TemplateTable::jvmti_post_fast_field_mod() {
+  __ should_not_reach_here();
+}
+
+void TemplateTable::fast_storefield(TosState state) {
+  transition(state, vtos);
+
+  const Register Rcache        = R5_ARG3,  // Do not use ARG1/2 (causes trouble in jvmti_post_field_mod).
+                 Rclass_or_obj = R31,      // Needs to survive C call.
+                 Roffset       = R22_tmp2, // Needs to survive C call.
+                 Rflags        = R3_ARG1,
+                 Rscratch      = R11_scratch1,
+                 Rscratch2     = R12_scratch2,
+                 Rscratch3     = R4_ARG2;
+  const ConditionRegister CR_is_vol = CCR2; // Non-volatile condition register (survives runtime call in do_oop_store).
+
+  // Constant pool already resolved => Load flags and offset of field.
+  __ get_cache_and_index_at_bcp(Rcache, 1);
+  jvmti_post_field_mod(Rcache, Rscratch, false /* not static */);
+  load_field_cp_cache_entry(noreg, Rcache, noreg, Roffset, Rflags, false);
+
+  // Get the obj and the final store addr.
+  pop_and_check_object(Rclass_or_obj); // Kills R11_scratch1.
+
+  // Get volatile flag.
+  __ rldicl_(Rscratch, Rflags, 64-ConstantPoolCacheEntry::is_volatile_shift, 63); // Extract volatile bit.
+  if (!support_IRIW_for_not_multiple_copy_atomic_cpu) { __ cmpdi(CR_is_vol, Rscratch, 1); }
+  {
+    Label LnotVolatile;
+    __ beq(CCR0, LnotVolatile);
+    __ release();
+    __ align(32, 12);
+    __ bind(LnotVolatile);
+  }
+
+  // Do the store and fencing.
+  switch(bytecode()) {
+    case Bytecodes::_fast_aputfield:
+      // Store into the field.
+      do_oop_store(_masm, Rclass_or_obj, Roffset, R17_tos, Rscratch, Rscratch2, Rscratch3, _bs->kind(), false /* precise */, true /* check null */);
+      break;
+
+    case Bytecodes::_fast_iputfield:
+      __ stwx(R17_tos, Rclass_or_obj, Roffset);
+      break;
+
+    case Bytecodes::_fast_lputfield:
+      __ stdx(R17_tos, Rclass_or_obj, Roffset);
+      break;
+
+    case Bytecodes::_fast_bputfield:
+      __ stbx(R17_tos, Rclass_or_obj, Roffset);
+      break;
+
+    case Bytecodes::_fast_cputfield:
+    case Bytecodes::_fast_sputfield:
+      __ sthx(R17_tos, Rclass_or_obj, Roffset);
+      break;
+
+    case Bytecodes::_fast_fputfield:
+      __ stfsx(F15_ftos, Rclass_or_obj, Roffset);
+      break;
+
+    case Bytecodes::_fast_dputfield:
+      __ stfdx(F15_ftos, Rclass_or_obj, Roffset);
+      break;
+
+    default: ShouldNotReachHere();
+  }
+
+  if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
+    Label LVolatile;
+    __ beq(CR_is_vol, LVolatile);
+    __ dispatch_epilog(vtos, Bytecodes::length_for(bytecode()));
+
+    __ align(32, 12);
+    __ bind(LVolatile);
+    __ fence();
+  }
+}
+
+void TemplateTable::fast_accessfield(TosState state) {
+  transition(atos, state);
+
+  Label LisVolatile;
+  ByteSize cp_base_offset = ConstantPoolCache::base_offset();
+
+  const Register Rcache        = R3_ARG1,
+                 Rclass_or_obj = R17_tos,
+                 Roffset       = R22_tmp2,
+                 Rflags        = R23_tmp3,
+                 Rscratch      = R12_scratch2;
+
+  // Constant pool already resolved. Get the field offset.
+  __ get_cache_and_index_at_bcp(Rcache, 1);
+  load_field_cp_cache_entry(noreg, Rcache, noreg, Roffset, Rflags, false);
+
+  // JVMTI support
+  jvmti_post_field_access(Rcache, Rscratch, false, true);
+
+  // Get the load address.
+  __ null_check_throw(Rclass_or_obj, -1, Rscratch);
+
+  // Get volatile flag.
+  __ rldicl_(Rscratch, Rflags, 64-ConstantPoolCacheEntry::is_volatile_shift, 63); // Extract volatile bit.
+  __ bne(CCR0, LisVolatile);
+
+  switch(bytecode()) {
+    case Bytecodes::_fast_agetfield:
+    {
+      __ load_heap_oop(R17_tos, (RegisterOrConstant)Roffset, Rclass_or_obj);
+      __ verify_oop(R17_tos);
+      __ dispatch_epilog(state, Bytecodes::length_for(bytecode()));
+
+      __ bind(LisVolatile);
+      if (support_IRIW_for_not_multiple_copy_atomic_cpu) { __ fence(); }
+      __ load_heap_oop(R17_tos, (RegisterOrConstant)Roffset, Rclass_or_obj);
+      __ verify_oop(R17_tos);
+      __ twi_0(R17_tos);
+      __ isync();
+      break;
+    }
+    case Bytecodes::_fast_igetfield:
+    {
+      __ lwax(R17_tos, Rclass_or_obj, Roffset);
+      __ dispatch_epilog(state, Bytecodes::length_for(bytecode()));
+
+      __ bind(LisVolatile);
+      if (support_IRIW_for_not_multiple_copy_atomic_cpu) { __ fence(); }
+      __ lwax(R17_tos, Rclass_or_obj, Roffset);
+      __ twi_0(R17_tos);
+      __ isync();
+      break;
+    }
+    case Bytecodes::_fast_lgetfield:
+    {
+      __ ldx(R17_tos, Rclass_or_obj, Roffset);
+      __ dispatch_epilog(state, Bytecodes::length_for(bytecode()));
+
+      __ bind(LisVolatile);
+      if (support_IRIW_for_not_multiple_copy_atomic_cpu) { __ fence(); }
+      __ ldx(R17_tos, Rclass_or_obj, Roffset);
+      __ twi_0(R17_tos);
+      __ isync();
+      break;
+    }
+    case Bytecodes::_fast_bgetfield:
+    {
+      __ lbzx(R17_tos, Rclass_or_obj, Roffset);
+      __ extsb(R17_tos, R17_tos);
+      __ dispatch_epilog(state, Bytecodes::length_for(bytecode()));
+
+      __ bind(LisVolatile);
+      if (support_IRIW_for_not_multiple_copy_atomic_cpu) { __ fence(); }
+      __ lbzx(R17_tos, Rclass_or_obj, Roffset);
+      __ twi_0(R17_tos);
+      __ extsb(R17_tos, R17_tos);
+      __ isync();
+      break;
+    }
+    case Bytecodes::_fast_cgetfield:
+    {
+      __ lhzx(R17_tos, Rclass_or_obj, Roffset);
+      __ dispatch_epilog(state, Bytecodes::length_for(bytecode()));
+
+      __ bind(LisVolatile);
+      if (support_IRIW_for_not_multiple_copy_atomic_cpu) { __ fence(); }
+      __ lhzx(R17_tos, Rclass_or_obj, Roffset);
+      __ twi_0(R17_tos);
+      __ isync();
+      break;
+    }
+    case Bytecodes::_fast_sgetfield:
+    {
+      __ lhax(R17_tos, Rclass_or_obj, Roffset);
+      __ dispatch_epilog(state, Bytecodes::length_for(bytecode()));
+
+      __ bind(LisVolatile);
+      if (support_IRIW_for_not_multiple_copy_atomic_cpu) { __ fence(); }
+      __ lhax(R17_tos, Rclass_or_obj, Roffset);
+      __ twi_0(R17_tos);
+      __ isync();
+      break;
+    }
+    case Bytecodes::_fast_fgetfield:
+    {
+      __ lfsx(F15_ftos, Rclass_or_obj, Roffset);
+      __ dispatch_epilog(state, Bytecodes::length_for(bytecode()));
+
+      __ bind(LisVolatile);
+      Label Ldummy;
+      if (support_IRIW_for_not_multiple_copy_atomic_cpu) { __ fence(); }
+      __ lfsx(F15_ftos, Rclass_or_obj, Roffset);
+      __ fcmpu(CCR0, F15_ftos, F15_ftos); // Acquire by cmp-br-isync.
+      __ bne_predict_not_taken(CCR0, Ldummy);
+      __ bind(Ldummy);
+      __ isync();
+      break;
+    }
+    case Bytecodes::_fast_dgetfield:
+    {
+      __ lfdx(F15_ftos, Rclass_or_obj, Roffset);
+      __ dispatch_epilog(state, Bytecodes::length_for(bytecode()));
+
+      __ bind(LisVolatile);
+      Label Ldummy;
+      if (support_IRIW_for_not_multiple_copy_atomic_cpu) { __ fence(); }
+      __ lfdx(F15_ftos, Rclass_or_obj, Roffset);
+      __ fcmpu(CCR0, F15_ftos, F15_ftos); // Acquire by cmp-br-isync.
+      __ bne_predict_not_taken(CCR0, Ldummy);
+      __ bind(Ldummy);
+      __ isync();
+      break;
+    }
+    default: ShouldNotReachHere();
+  }
+}
+
+void TemplateTable::fast_xaccess(TosState state) {
+  transition(vtos, state);
+
+  Label LisVolatile;
+  ByteSize cp_base_offset = ConstantPoolCache::base_offset();
+  const Register Rcache        = R3_ARG1,
+                 Rclass_or_obj = R17_tos,
+                 Roffset       = R22_tmp2,
+                 Rflags        = R23_tmp3,
+                 Rscratch      = R12_scratch2;
+
+  __ ld(Rclass_or_obj, 0, R18_locals);
+
+  // Constant pool already resolved. Get the field offset.
+  __ get_cache_and_index_at_bcp(Rcache, 2);
+  load_field_cp_cache_entry(noreg, Rcache, noreg, Roffset, Rflags, false);
+
+  // JVMTI support not needed, since we switch back to single bytecode as soon as debugger attaches.
+
+  // Needed to report exception at the correct bcp.
+  __ addi(R14_bcp, R14_bcp, 1);
+
+  // Get the load address.
+  __ null_check_throw(Rclass_or_obj, -1, Rscratch);
+
+  // Get volatile flag.
+  __ rldicl_(Rscratch, Rflags, 64-ConstantPoolCacheEntry::is_volatile_shift, 63); // Extract volatile bit.
+  __ bne(CCR0, LisVolatile);
+
+  switch(state) {
+  case atos:
+    {
+      __ load_heap_oop(R17_tos, (RegisterOrConstant)Roffset, Rclass_or_obj);
+      __ verify_oop(R17_tos);
+      __ dispatch_epilog(state, Bytecodes::length_for(bytecode()) - 1); // Undo bcp increment.
+
+      __ bind(LisVolatile);
+      if (support_IRIW_for_not_multiple_copy_atomic_cpu) { __ fence(); }
+      __ load_heap_oop(R17_tos, (RegisterOrConstant)Roffset, Rclass_or_obj);
+      __ verify_oop(R17_tos);
+      __ twi_0(R17_tos);
+      __ isync();
+      break;
+    }
+  case itos:
+    {
+      __ lwax(R17_tos, Rclass_or_obj, Roffset);
+      __ dispatch_epilog(state, Bytecodes::length_for(bytecode()) - 1); // Undo bcp increment.
+
+      __ bind(LisVolatile);
+      if (support_IRIW_for_not_multiple_copy_atomic_cpu) { __ fence(); }
+      __ lwax(R17_tos, Rclass_or_obj, Roffset);
+      __ twi_0(R17_tos);
+      __ isync();
+      break;
+    }
+  case ftos:
+    {
+      __ lfsx(F15_ftos, Rclass_or_obj, Roffset);
+      __ dispatch_epilog(state, Bytecodes::length_for(bytecode()) - 1); // Undo bcp increment.
+
+      __ bind(LisVolatile);
+      Label Ldummy;
+      if (support_IRIW_for_not_multiple_copy_atomic_cpu) { __ fence(); }
+      __ lfsx(F15_ftos, Rclass_or_obj, Roffset);
+      __ fcmpu(CCR0, F15_ftos, F15_ftos); // Acquire by cmp-br-isync.
+      __ bne_predict_not_taken(CCR0, Ldummy);
+      __ bind(Ldummy);
+      __ isync();
+      break;
+    }
+  default: ShouldNotReachHere();
+  }
+  __ addi(R14_bcp, R14_bcp, -1);
+}
+
+// ============================================================================
+// Calls
+
+// Common code for invoke
+//
+// Input:
+//   - byte_no
+//
+// Output:
+//   - Rmethod:        The method to invoke next.
+//   - Rret_addr:      The return address to return to.
+//   - Rindex:         MethodType (invokehandle) or CallSite obj (invokedynamic)
+//   - Rrecv:          Cache for "this" pointer, might be noreg if static call.
+//   - Rflags:         Method flags from const pool cache.
+//
+//  Kills:
+//   - Rscratch1
+//
+void TemplateTable::prepare_invoke(int byte_no,
+                                   Register Rmethod,  // linked method (or i-klass)
+                                   Register Rret_addr,// return address
+                                   Register Rindex,   // itable index, MethodType, etc.
+                                   Register Rrecv,    // If caller wants to see it.
+                                   Register Rflags,   // If caller wants to test it.
+                                   Register Rscratch
+                                   ) {
+  // Determine flags.
+  const Bytecodes::Code code = bytecode();
+  const bool is_invokeinterface  = code == Bytecodes::_invokeinterface;
+  const bool is_invokedynamic    = code == Bytecodes::_invokedynamic;
+  const bool is_invokehandle     = code == Bytecodes::_invokehandle;
+  const bool is_invokevirtual    = code == Bytecodes::_invokevirtual;
+  const bool is_invokespecial    = code == Bytecodes::_invokespecial;
+  const bool load_receiver       = (Rrecv != noreg);
+  assert(load_receiver == (code != Bytecodes::_invokestatic && code != Bytecodes::_invokedynamic), "");
+
+  assert_different_registers(Rmethod, Rindex, Rflags, Rscratch);
+  assert_different_registers(Rmethod, Rrecv, Rflags, Rscratch);
+  assert_different_registers(Rret_addr, Rscratch);
+
+  load_invoke_cp_cache_entry(byte_no, Rmethod, Rindex, Rflags, is_invokevirtual, false, is_invokedynamic);
+
+  // Saving of SP done in call_from_interpreter.
+
+  // Maybe push "appendix" to arguments.
+  if (is_invokedynamic || is_invokehandle) {
+    Label Ldone;
+    __ rldicl_(R0, Rflags, 64-ConstantPoolCacheEntry::has_appendix_shift, 63);
+    __ beq(CCR0, Ldone);
+    // Push "appendix" (MethodType, CallSite, etc.).
+    // This must be done before we get the receiver,
+    // since the parameter_size includes it.
+    __ load_resolved_reference_at_index(Rscratch, Rindex);
+    __ verify_oop(Rscratch);
+    __ push_ptr(Rscratch);
+    __ bind(Ldone);
+  }
+
+  // Load receiver if needed (after appendix is pushed so parameter size is correct).
+  if (load_receiver) {
+    const Register Rparam_count = Rscratch;
+    __ andi(Rparam_count, Rflags, ConstantPoolCacheEntry::parameter_size_mask);
+    __ load_receiver(Rparam_count, Rrecv);
+    __ verify_oop(Rrecv);
+  }
+
+  // Get return address.
+  {
+    Register Rtable_addr = Rscratch;
+    Register Rret_type = Rret_addr;
+    address table_addr = (address) Interpreter::invoke_return_entry_table_for(code);
+
+    // Get return type. It's coded into the upper 4 bits of the lower half of the 64 bit value.
+    __ rldicl(Rret_type, Rflags, 64-ConstantPoolCacheEntry::tos_state_shift, 64-ConstantPoolCacheEntry::tos_state_bits);
+    __ load_dispatch_table(Rtable_addr, (address*)table_addr);
+    __ sldi(Rret_type, Rret_type, LogBytesPerWord);
+    // Get return address.
+    __ ldx(Rret_addr, Rtable_addr, Rret_type);
+  }
+}
+
+// Helper for virtual calls. Load target out of vtable and jump off!
+// Kills all passed registers.
+void TemplateTable::generate_vtable_call(Register Rrecv_klass, Register Rindex, Register Rret, Register Rtemp) {
+
+  assert_different_registers(Rrecv_klass, Rtemp, Rret);
+  const Register Rtarget_method = Rindex;
+
+  // Get target method & entry point.
+  const int base = InstanceKlass::vtable_start_offset() * wordSize;
+  // Calc vtable addr scale the vtable index by 8.
+  __ sldi(Rindex, Rindex, exact_log2(vtableEntry::size() * wordSize));
+  // Load target.
+  __ addi(Rrecv_klass, Rrecv_klass, base + vtableEntry::method_offset_in_bytes());
+  __ ldx(Rtarget_method, Rindex, Rrecv_klass);
+  __ call_from_interpreter(Rtarget_method, Rret, Rrecv_klass /* scratch1 */, Rtemp /* scratch2 */);
+}
+
+// Virtual or final call. Final calls are rewritten on the fly to run through "fast_finalcall" next time.
+void TemplateTable::invokevirtual(int byte_no) {
+  transition(vtos, vtos);
+
+  Register Rtable_addr = R11_scratch1,
+           Rret_type = R12_scratch2,
+           Rret_addr = R5_ARG3,
+           Rflags = R22_tmp2, // Should survive C call.
+           Rrecv = R3_ARG1,
+           Rrecv_klass = Rrecv,
+           Rvtableindex_or_method = R31, // Should survive C call.
+           Rnum_params = R4_ARG2,
+           Rnew_bc = R6_ARG4;
+
+  Label LnotFinal;
+
+  load_invoke_cp_cache_entry(byte_no, Rvtableindex_or_method, noreg, Rflags, /*virtual*/ true, false, false);
+
+  __ testbitdi(CCR0, R0, Rflags, ConstantPoolCacheEntry::is_vfinal_shift);
+  __ bfalse(CCR0, LnotFinal);
+
+  patch_bytecode(Bytecodes::_fast_invokevfinal, Rnew_bc, R12_scratch2);
+  invokevfinal_helper(Rvtableindex_or_method, Rflags, R11_scratch1, R12_scratch2);
+
+  __ align(32, 12);
+  __ bind(LnotFinal);
+  // Load "this" pointer (receiver).
+  __ rldicl(Rnum_params, Rflags, 64, 48);
+  __ load_receiver(Rnum_params, Rrecv);
+  __ verify_oop(Rrecv);
+
+  // Get return type. It's coded into the upper 4 bits of the lower half of the 64 bit value.
+  __ rldicl(Rret_type, Rflags, 64-ConstantPoolCacheEntry::tos_state_shift, 64-ConstantPoolCacheEntry::tos_state_bits);
+  __ load_dispatch_table(Rtable_addr, Interpreter::invoke_return_entry_table());
+  __ sldi(Rret_type, Rret_type, LogBytesPerWord);
+  __ ldx(Rret_addr, Rret_type, Rtable_addr);
+  __ null_check_throw(Rrecv, oopDesc::klass_offset_in_bytes(), R11_scratch1);
+  __ load_klass(Rrecv_klass, Rrecv);
+  __ verify_klass_ptr(Rrecv_klass);
+  __ profile_virtual_call(Rrecv_klass, R11_scratch1, R12_scratch2, false);
+
+  generate_vtable_call(Rrecv_klass, Rvtableindex_or_method, Rret_addr, R11_scratch1);
+}
+
+void TemplateTable::fast_invokevfinal(int byte_no) {
+  transition(vtos, vtos);
+
+  assert(byte_no == f2_byte, "use this argument");
+  Register Rflags  = R22_tmp2,
+           Rmethod = R31;
+  load_invoke_cp_cache_entry(byte_no, Rmethod, noreg, Rflags, /*virtual*/ true, /*is_invokevfinal*/ true, false);
+  invokevfinal_helper(Rmethod, Rflags, R11_scratch1, R12_scratch2);
+}
+
+void TemplateTable::invokevfinal_helper(Register Rmethod, Register Rflags, Register Rscratch1, Register Rscratch2) {
+
+  assert_different_registers(Rmethod, Rflags, Rscratch1, Rscratch2);
+
+  // Load receiver from stack slot.
+  Register Rrecv = Rscratch2;
+  Register Rnum_params = Rrecv;
+
+  __ ld(Rnum_params, in_bytes(Method::const_offset()), Rmethod);
+  __ lhz(Rnum_params /* number of params */, in_bytes(ConstMethod::size_of_parameters_offset()), Rnum_params);
+
+  // Get return address.
+  Register Rtable_addr = Rscratch1,
+           Rret_addr   = Rflags,
+           Rret_type   = Rret_addr;
+  // Get return type. It's coded into the upper 4 bits of the lower half of the 64 bit value.
+  __ rldicl(Rret_type, Rflags, 64-ConstantPoolCacheEntry::tos_state_shift, 64-ConstantPoolCacheEntry::tos_state_bits);
+  __ load_dispatch_table(Rtable_addr, Interpreter::invoke_return_entry_table());
+  __ sldi(Rret_type, Rret_type, LogBytesPerWord);
+  __ ldx(Rret_addr, Rret_type, Rtable_addr);
+
+  // Load receiver and receiver NULL check.
+  __ load_receiver(Rnum_params, Rrecv);
+  __ null_check_throw(Rrecv, -1, Rscratch1);
+
+  __ profile_final_call(Rrecv, Rscratch1);
+
+  // Do the call.
+  __ call_from_interpreter(Rmethod, Rret_addr, Rscratch1, Rscratch2);
+}
+
+void TemplateTable::invokespecial(int byte_no) {
+  assert(byte_no == f1_byte, "use this argument");
+  transition(vtos, vtos);
+
+  Register Rtable_addr = R3_ARG1,
+           Rret_addr   = R4_ARG2,
+           Rflags      = R5_ARG3,
+           Rreceiver   = R6_ARG4,
+           Rmethod     = R31;
+
+  prepare_invoke(byte_no, Rmethod, Rret_addr, noreg, Rreceiver, Rflags, R11_scratch1);
+
+  // Receiver NULL check.
+  __ null_check_throw(Rreceiver, -1, R11_scratch1);
+
+  __ profile_call(R11_scratch1, R12_scratch2);
+  __ call_from_interpreter(Rmethod, Rret_addr, R11_scratch1, R12_scratch2);
+}
+
+void TemplateTable::invokestatic(int byte_no) {
+  assert(byte_no == f1_byte, "use this argument");
+  transition(vtos, vtos);
+
+  Register Rtable_addr = R3_ARG1,
+           Rret_addr   = R4_ARG2,
+           Rflags      = R5_ARG3;
+
+  prepare_invoke(byte_no, R19_method, Rret_addr, noreg, noreg, Rflags, R11_scratch1);
+
+  __ profile_call(R11_scratch1, R12_scratch2);
+  __ call_from_interpreter(R19_method, Rret_addr, R11_scratch1, R12_scratch2);
+}
+
+void TemplateTable::invokeinterface_object_method(Register Rrecv_klass,
+                                                  Register Rret,
+                                                  Register Rflags,
+                                                  Register Rindex,
+                                                  Register Rtemp1,
+                                                  Register Rtemp2) {
+
+  assert_different_registers(Rindex, Rret, Rrecv_klass, Rflags, Rtemp1, Rtemp2);
+  Label LnotFinal;
+
+  // Check for vfinal.
+  __ testbitdi(CCR0, R0, Rflags, ConstantPoolCacheEntry::is_vfinal_shift);
+  __ bfalse(CCR0, LnotFinal);
+
+  Register Rscratch = Rflags; // Rflags is dead now.
+
+  // Final call case.
+  __ profile_final_call(Rtemp1, Rscratch);
+  // Do the final call - the index (f2) contains the method.
+  __ call_from_interpreter(Rindex, Rret, Rscratch, Rrecv_klass /* scratch */);
+
+  // Non-final callc case.
+  __ bind(LnotFinal);
+  __ profile_virtual_call(Rrecv_klass, Rtemp1, Rscratch, false);
+  generate_vtable_call(Rrecv_klass, Rindex, Rret, Rscratch);
+}
+
+void TemplateTable::invokeinterface(int byte_no) {
+  assert(byte_no == f1_byte, "use this argument");
+  transition(vtos, vtos);
+
+  const Register Rscratch1        = R11_scratch1,
+                 Rscratch2        = R12_scratch2,
+                 Rscratch3        = R9_ARG7,
+                 Rscratch4        = R10_ARG8,
+                 Rtable_addr      = Rscratch2,
+                 Rinterface_klass = R5_ARG3,
+                 Rret_type        = R8_ARG6,
+                 Rret_addr        = Rret_type,
+                 Rindex           = R6_ARG4,
+                 Rreceiver        = R4_ARG2,
+                 Rrecv_klass      = Rreceiver,
+                 Rflags           = R7_ARG5;
+
+  prepare_invoke(byte_no, Rinterface_klass, Rret_addr, Rindex, Rreceiver, Rflags, Rscratch1);
+
+  // Get receiver klass.
+  __ null_check_throw(Rreceiver, oopDesc::klass_offset_in_bytes(), Rscratch3);
+  __ load_klass(Rrecv_klass, Rreceiver);
+
+  // Check corner case object method.
+  Label LobjectMethod;
+
+  __ testbitdi(CCR0, R0, Rflags, ConstantPoolCacheEntry::is_forced_virtual_shift);
+  __ btrue(CCR0, LobjectMethod);
+
+  // Fallthrough: The normal invokeinterface case.
+  __ profile_virtual_call(Rrecv_klass, Rscratch1, Rscratch2, false);
+
+  // Find entry point to call.
+  Label Lthrow_icc, Lthrow_ame;
+  // Result will be returned in Rindex.
+  __ mr(Rscratch4, Rrecv_klass);
+  __ mr(Rscratch3, Rindex);
+  __ lookup_interface_method(Rrecv_klass, Rinterface_klass, Rindex, Rindex, Rscratch1, Rscratch2, Lthrow_icc);
+
+  __ cmpdi(CCR0, Rindex, 0);
+  __ beq(CCR0, Lthrow_ame);
+  // Found entry. Jump off!
+  __ call_from_interpreter(Rindex, Rret_addr, Rscratch1, Rscratch2);
+
+  // Vtable entry was NULL => Throw abstract method error.
+  __ bind(Lthrow_ame);
+  __ mr(Rrecv_klass, Rscratch4);
+  __ mr(Rindex, Rscratch3);
+  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodError));
+
+  // Interface was not found => Throw incompatible class change error.
+  __ bind(Lthrow_icc);
+  __ mr(Rrecv_klass, Rscratch4);
+  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
+
+  __ should_not_reach_here();
+
+  // Special case of invokeinterface called for virtual method of
+  // java.lang.Object. See ConstantPoolCacheEntry::set_method() for details:
+  // The invokeinterface was rewritten to a invokevirtual, hence we have
+  // to handle this corner case. This code isn't produced by javac, but could
+  // be produced by another compliant java compiler.
+  __ bind(LobjectMethod);
+  invokeinterface_object_method(Rrecv_klass, Rret_addr, Rflags, Rindex, Rscratch1, Rscratch2);
+}
+
+void TemplateTable::invokedynamic(int byte_no) {
+  transition(vtos, vtos);
+
+  const Register Rret_addr = R3_ARG1,
+                 Rflags    = R4_ARG2,
+                 Rmethod   = R22_tmp2,
+                 Rscratch1 = R11_scratch1,
+                 Rscratch2 = R12_scratch2;
+
+  if (!EnableInvokeDynamic) {
+    // We should not encounter this bytecode if !EnableInvokeDynamic.
+    // The verifier will stop it. However, if we get past the verifier,
+    // this will stop the thread in a reasonable way, without crashing the JVM.
+    __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_IncompatibleClassChangeError));
+    // The call_VM checks for exception, so we should never return here.
+    __ should_not_reach_here();
+    return;
+  }
+
+  prepare_invoke(byte_no, Rmethod, Rret_addr, Rscratch1, noreg, Rflags, Rscratch2);
+
+  // Profile this call.
+  __ profile_call(Rscratch1, Rscratch2);
+
+  // Off we go. With the new method handles, we don't jump to a method handle
+  // entry any more. Instead, we pushed an "appendix" in prepare invoke, which happens
+  // to be the callsite object the bootstrap method returned. This is passed to a
+  // "link" method which does the dispatch (Most likely just grabs the MH stored
+  // inside the callsite and does an invokehandle).
+  __ call_from_interpreter(Rmethod, Rret_addr, Rscratch1 /* scratch1 */, Rscratch2 /* scratch2 */);
+}
+
+void TemplateTable::invokehandle(int byte_no) {
+  transition(vtos, vtos);
+
+  const Register Rret_addr = R3_ARG1,
+                 Rflags    = R4_ARG2,
+                 Rrecv     = R5_ARG3,
+                 Rmethod   = R22_tmp2,
+                 Rscratch1 = R11_scratch1,
+                 Rscratch2 = R12_scratch2;
+
+  if (!EnableInvokeDynamic) {
+    // Rewriter does not generate this bytecode.
+    __ should_not_reach_here();
+    return;
+  }
+
+  prepare_invoke(byte_no, Rmethod, Rret_addr, Rscratch1, Rrecv, Rflags, Rscratch2);
+  __ verify_method_ptr(Rmethod);
+  __ null_check_throw(Rrecv, -1, Rscratch2);
+
+  __ profile_final_call(Rrecv, Rscratch1);
+
+  // Still no call from handle => We call the method handle interpreter here.
+  __ call_from_interpreter(Rmethod, Rret_addr, Rscratch1 /* scratch1 */, Rscratch2 /* scratch2 */);
+}
+
+// =============================================================================
+// Allocation
+
+// Puts allocated obj ref onto the expression stack.
+void TemplateTable::_new() {
+  transition(vtos, atos);
+
+  Label Lslow_case,
+        Ldone,
+        Linitialize_header,
+        Lallocate_shared,
+        Linitialize_object;  // Including clearing the fields.
+
+  const Register RallocatedObject = R17_tos,
+                 RinstanceKlass   = R9_ARG7,
+                 Rscratch         = R11_scratch1,
+                 Roffset          = R8_ARG6,
+                 Rinstance_size   = Roffset,
+                 Rcpool           = R4_ARG2,
+                 Rtags            = R3_ARG1,
+                 Rindex           = R5_ARG3;
+
+  const bool allow_shared_alloc = Universe::heap()->supports_inline_contig_alloc() && !CMSIncrementalMode;
+
+  // --------------------------------------------------------------------------
+  // Check if fast case is possible.
+
+  // Load pointers to const pool and const pool's tags array.
+  __ get_cpool_and_tags(Rcpool, Rtags);
+  // Load index of constant pool entry.
+  __ get_2_byte_integer_at_bcp(1, Rindex, InterpreterMacroAssembler::Unsigned);
+
+  if (UseTLAB) {
+    // Make sure the class we're about to instantiate has been resolved
+    // This is done before loading instanceKlass to be consistent with the order
+    // how Constant Pool is updated (see ConstantPoolCache::klass_at_put).
+    __ addi(Rtags, Rtags, Array<u1>::base_offset_in_bytes());
+    __ lbzx(Rtags, Rindex, Rtags);
+
+    __ cmpdi(CCR0, Rtags, JVM_CONSTANT_Class);
+    __ bne(CCR0, Lslow_case);
+
+    // Get instanceKlass (load from Rcpool + sizeof(ConstantPool) + Rindex*BytesPerWord).
+    __ sldi(Roffset, Rindex, LogBytesPerWord);
+    __ addi(Rscratch, Rcpool, sizeof(ConstantPool));
+    __ isync(); // Order load of instance Klass wrt. tags.
+    __ ldx(RinstanceKlass, Roffset, Rscratch);
+
+    // Make sure klass is fully initialized and get instance_size.
+    __ lbz(Rscratch, in_bytes(InstanceKlass::init_state_offset()), RinstanceKlass);
+    __ lwz(Rinstance_size, in_bytes(Klass::layout_helper_offset()), RinstanceKlass);
+
+    __ cmpdi(CCR1, Rscratch, InstanceKlass::fully_initialized);
+    // Make sure klass does not have has_finalizer, or is abstract, or interface or java/lang/Class.
+    __ andi_(R0, Rinstance_size, Klass::_lh_instance_slow_path_bit); // slow path bit equals 0?
+
+    __ crnand(/*CR0 eq*/2, /*CR1 eq*/4+2, /*CR0 eq*/2); // slow path bit set or not fully initialized?
+    __ beq(CCR0, Lslow_case);
+
+    // --------------------------------------------------------------------------
+    // Fast case:
+    // Allocate the instance.
+    // 1) Try to allocate in the TLAB.
+    // 2) If fail, and the TLAB is not full enough to discard, allocate in the shared Eden.
+    // 3) If the above fails (or is not applicable), go to a slow case (creates a new TLAB, etc.).
+
+    Register RoldTopValue = RallocatedObject; // Object will be allocated here if it fits.
+    Register RnewTopValue = R6_ARG4;
+    Register RendValue    = R7_ARG5;
+
+    // Check if we can allocate in the TLAB.
+    __ ld(RoldTopValue, in_bytes(JavaThread::tlab_top_offset()), R16_thread);
+    __ ld(RendValue,    in_bytes(JavaThread::tlab_end_offset()), R16_thread);
+
+    __ add(RnewTopValue, Rinstance_size, RoldTopValue);
+
+    // If there is enough space, we do not CAS and do not clear.
+    __ cmpld(CCR0, RnewTopValue, RendValue);
+    __ bgt(CCR0, allow_shared_alloc ? Lallocate_shared : Lslow_case);
+
+    __ std(RnewTopValue, in_bytes(JavaThread::tlab_top_offset()), R16_thread);
+
+    if (ZeroTLAB) {
+      // The fields have already been cleared.
+      __ b(Linitialize_header);
+    } else {
+      // Initialize both the header and fields.
+      __ b(Linitialize_object);
+    }
+
+    // Fall through: TLAB was too small.
+    if (allow_shared_alloc) {
+      Register RtlabWasteLimitValue = R10_ARG8;
+      Register RfreeValue = RnewTopValue;
+
+      __ bind(Lallocate_shared);
+      // Check if tlab should be discarded (refill_waste_limit >= free).
+      __ ld(RtlabWasteLimitValue, in_bytes(JavaThread::tlab_refill_waste_limit_offset()), R16_thread);
+      __ subf(RfreeValue, RoldTopValue, RendValue);
+      __ srdi(RfreeValue, RfreeValue, LogHeapWordSize); // in dwords
+      __ cmpld(CCR0, RtlabWasteLimitValue, RfreeValue);
+      __ bge(CCR0, Lslow_case);
+
+      // Increment waste limit to prevent getting stuck on this slow path.
+      __ addi(RtlabWasteLimitValue, RtlabWasteLimitValue, (int)ThreadLocalAllocBuffer::refill_waste_limit_increment());
+      __ std(RtlabWasteLimitValue, in_bytes(JavaThread::tlab_refill_waste_limit_offset()), R16_thread);
+    }
+    // else: No allocation in the shared eden. // fallthru: __ b(Lslow_case);
+  }
+  // else: Always go the slow path.
+
+  // --------------------------------------------------------------------------
+  // slow case
+  __ bind(Lslow_case);
+  call_VM(R17_tos, CAST_FROM_FN_PTR(address, InterpreterRuntime::_new), Rcpool, Rindex);
+
+  if (UseTLAB) {
+    __ b(Ldone);
+    // --------------------------------------------------------------------------
+    // Init1: Zero out newly allocated memory.
+
+    if (!ZeroTLAB || allow_shared_alloc) {
+      // Clear object fields.
+      __ bind(Linitialize_object);
+
+      // Initialize remaining object fields.
+      Register Rbase = Rtags;
+      __ addi(Rinstance_size, Rinstance_size, 7 - (int)sizeof(oopDesc));
+      __ addi(Rbase, RallocatedObject, sizeof(oopDesc));
+      __ srdi(Rinstance_size, Rinstance_size, 3);
+
+      // Clear out object skipping header. Takes also care of the zero length case.
+      __ clear_memory_doubleword(Rbase, Rinstance_size);
+      // fallthru: __ b(Linitialize_header);
+    }
+
+    // --------------------------------------------------------------------------
+    // Init2: Initialize the header: mark, klass
+    __ bind(Linitialize_header);
+
+    // Init mark.
+    if (UseBiasedLocking) {
+      __ ld(Rscratch, in_bytes(Klass::prototype_header_offset()), RinstanceKlass);
+    } else {
+      __ load_const_optimized(Rscratch, markOopDesc::prototype(), R0);
+    }
+    __ std(Rscratch, oopDesc::mark_offset_in_bytes(), RallocatedObject);
+
+    // Init klass.
+    __ store_klass_gap(RallocatedObject);
+    __ store_klass(RallocatedObject, RinstanceKlass, Rscratch); // klass (last for cms)
+
+    // Check and trigger dtrace event.
+    {
+      SkipIfEqualZero skip_if(_masm, Rscratch, &DTraceAllocProbes);
+      __ push(atos);
+      __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_object_alloc));
+      __ pop(atos);
+    }
+  }
+
+  // continue
+  __ bind(Ldone);
+
+  // Must prevent reordering of stores for object initialization with stores that publish the new object.
+  __ membar(Assembler::StoreStore);
+}
+
+void TemplateTable::newarray() {
+  transition(itos, atos);
+
+  __ lbz(R4, 1, R14_bcp);
+  __ extsw(R5, R17_tos);
+  call_VM(R17_tos, CAST_FROM_FN_PTR(address, InterpreterRuntime::newarray), R4, R5 /* size */);
+
+  // Must prevent reordering of stores for object initialization with stores that publish the new object.
+  __ membar(Assembler::StoreStore);
+}
+
+void TemplateTable::anewarray() {
+  transition(itos, atos);
+
+  __ get_constant_pool(R4);
+  __ get_2_byte_integer_at_bcp(1, R5, InterpreterMacroAssembler::Unsigned);
+  __ extsw(R6, R17_tos); // size
+  call_VM(R17_tos, CAST_FROM_FN_PTR(address, InterpreterRuntime::anewarray), R4 /* pool */, R5 /* index */, R6 /* size */);
+
+  // Must prevent reordering of stores for object initialization with stores that publish the new object.
+  __ membar(Assembler::StoreStore);
+}
+
+// Allocate a multi dimensional array
+void TemplateTable::multianewarray() {
+  transition(vtos, atos);
+
+  Register Rptr = R31; // Needs to survive C call.
+
+  // Put ndims * wordSize into frame temp slot
+  __ lbz(Rptr, 3, R14_bcp);
+  __ sldi(Rptr, Rptr, Interpreter::logStackElementSize);
+  // Esp points past last_dim, so set to R4 to first_dim address.
+  __ add(R4, Rptr, R15_esp);
+  call_VM(R17_tos, CAST_FROM_FN_PTR(address, InterpreterRuntime::multianewarray), R4 /* first_size_address */);
+  // Pop all dimensions off the stack.
+  __ add(R15_esp, Rptr, R15_esp);
+
+  // Must prevent reordering of stores for object initialization with stores that publish the new object.
+  __ membar(Assembler::StoreStore);
+}
+
+void TemplateTable::arraylength() {
+  transition(atos, itos);
+
+  Label LnoException;
+  __ verify_oop(R17_tos);
+  __ null_check_throw(R17_tos, arrayOopDesc::length_offset_in_bytes(), R11_scratch1);
+  __ lwa(R17_tos, arrayOopDesc::length_offset_in_bytes(), R17_tos);
+}
+
+// ============================================================================
+// Typechecks
+
+void TemplateTable::checkcast() {
+  transition(atos, atos);
+
+  Label Ldone, Lis_null, Lquicked, Lresolved;
+  Register Roffset         = R5_ARG3,
+           RobjKlass       = R4_ARG2,
+           RspecifiedKlass = R6_ARG4, // Generate_ClassCastException_verbose_handler will expect this register.
+           Rcpool          = R11_scratch1,
+           Rtags           = R12_scratch2;
+
+  // Null does not pass.
+  __ cmpdi(CCR0, R17_tos, 0);
+  __ beq(CCR0, Lis_null);
+
+  // Get constant pool tag to find out if the bytecode has already been "quickened".
+  __ get_cpool_and_tags(Rcpool, Rtags);
+
+  __ get_2_byte_integer_at_bcp(1, Roffset, InterpreterMacroAssembler::Unsigned);
+
+  __ addi(Rtags, Rtags, Array<u1>::base_offset_in_bytes());
+  __ lbzx(Rtags, Rtags, Roffset);
+
+  __ cmpdi(CCR0, Rtags, JVM_CONSTANT_Class);
+  __ beq(CCR0, Lquicked);
+
+  // Call into the VM to "quicken" instanceof.
+  __ push_ptr();  // for GC
+  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::quicken_io_cc));
+  __ get_vm_result_2(RspecifiedKlass);
+  __ pop_ptr();   // Restore receiver.
+  __ b(Lresolved);
+
+  // Extract target class from constant pool.
+  __ bind(Lquicked);
+  __ sldi(Roffset, Roffset, LogBytesPerWord);
+  __ addi(Rcpool, Rcpool, sizeof(ConstantPool));
+  __ isync(); // Order load of specified Klass wrt. tags.
+  __ ldx(RspecifiedKlass, Rcpool, Roffset);
+
+  // Do the checkcast.
+  __ bind(Lresolved);
+  // Get value klass in RobjKlass.
+  __ load_klass(RobjKlass, R17_tos);
+  // Generate a fast subtype check. Branch to cast_ok if no failure. Return 0 if failure.
+  __ gen_subtype_check(RobjKlass, RspecifiedKlass, /*3 temp regs*/ Roffset, Rcpool, Rtags, /*target if subtype*/ Ldone);
+
+  // Not a subtype; so must throw exception
+  // Target class oop is in register R6_ARG4 == RspecifiedKlass by convention.
+  __ load_dispatch_table(R11_scratch1, (address*)Interpreter::_throw_ClassCastException_entry);
+  __ mtctr(R11_scratch1);
+  __ bctr();
+
+  // Profile the null case.
+  __ align(32, 12);
+  __ bind(Lis_null);
+  __ profile_null_seen(R11_scratch1, Rtags); // Rtags used as scratch.
+
+  __ align(32, 12);
+  __ bind(Ldone);
+}
+
+// Output:
+//   - tos == 0: Obj was null or not an instance of class.
+//   - tos == 1: Obj was an instance of class.
+void TemplateTable::instanceof() {
+  transition(atos, itos);
+
+  Label Ldone, Lis_null, Lquicked, Lresolved;
+  Register Roffset         = R5_ARG3,
+           RobjKlass       = R4_ARG2,
+           RspecifiedKlass = R6_ARG4, // Generate_ClassCastException_verbose_handler will expect the value in this register.
+           Rcpool          = R11_scratch1,
+           Rtags           = R12_scratch2;
+
+  // Null does not pass.
+  __ cmpdi(CCR0, R17_tos, 0);
+  __ beq(CCR0, Lis_null);
+
+  // Get constant pool tag to find out if the bytecode has already been "quickened".
+  __ get_cpool_and_tags(Rcpool, Rtags);
+
+  __ get_2_byte_integer_at_bcp(1, Roffset, InterpreterMacroAssembler::Unsigned);
+
+  __ addi(Rtags, Rtags, Array<u1>::base_offset_in_bytes());
+  __ lbzx(Rtags, Rtags, Roffset);
+
+  __ cmpdi(CCR0, Rtags, JVM_CONSTANT_Class);
+  __ beq(CCR0, Lquicked);
+
+  // Call into the VM to "quicken" instanceof.
+  __ push_ptr();  // for GC
+  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::quicken_io_cc));
+  __ get_vm_result_2(RspecifiedKlass);
+  __ pop_ptr();   // Restore receiver.
+  __ b(Lresolved);
+
+  // Extract target class from constant pool.
+  __ bind(Lquicked);
+  __ sldi(Roffset, Roffset, LogBytesPerWord);
+  __ addi(Rcpool, Rcpool, sizeof(ConstantPool));
+  __ isync(); // Order load of specified Klass wrt. tags.
+  __ ldx(RspecifiedKlass, Rcpool, Roffset);
+
+  // Do the checkcast.
+  __ bind(Lresolved);
+  // Get value klass in RobjKlass.
+  __ load_klass(RobjKlass, R17_tos);
+  // Generate a fast subtype check. Branch to cast_ok if no failure. Return 0 if failure.
+  __ li(R17_tos, 1);
+  __ gen_subtype_check(RobjKlass, RspecifiedKlass, /*3 temp regs*/ Roffset, Rcpool, Rtags, /*target if subtype*/ Ldone);
+  __ li(R17_tos, 0);
+
+  if (ProfileInterpreter) {
+    __ b(Ldone);
+  }
+
+  // Profile the null case.
+  __ align(32, 12);
+  __ bind(Lis_null);
+  __ profile_null_seen(Rcpool, Rtags); // Rcpool and Rtags used as scratch.
+
+  __ align(32, 12);
+  __ bind(Ldone);
+}
+
+// =============================================================================
+// Breakpoints
+
+void TemplateTable::_breakpoint() {
+  transition(vtos, vtos);
+
+  // Get the unpatched byte code.
+  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::get_original_bytecode_at), R19_method, R14_bcp);
+  __ mr(R31, R3_RET);
+
+  // Post the breakpoint event.
+  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::_breakpoint), R19_method, R14_bcp);
+
+  // Complete the execution of original bytecode.
+  __ dispatch_Lbyte_code(vtos, R31, Interpreter::normal_table(vtos));
+}
+
+// =============================================================================
+// Exceptions
+
+void TemplateTable::athrow() {
+  transition(atos, vtos);
+
+  // Exception oop is in tos
+  __ verify_oop(R17_tos);
+
+  __ null_check_throw(R17_tos, -1, R11_scratch1);
+
+  // Throw exception interpreter entry expects exception oop to be in R3.
+  __ mr(R3_RET, R17_tos);
+  __ load_dispatch_table(R11_scratch1, (address*)Interpreter::throw_exception_entry());
+  __ mtctr(R11_scratch1);
+  __ bctr();
+}
+
+// =============================================================================
+// Synchronization
+// Searches the basic object lock list on the stack for a free slot
+// and uses it to lock the obect in tos.
+//
+// Recursive locking is enabled by exiting the search if the same
+// object is already found in the list. Thus, a new basic lock obj lock
+// is allocated "higher up" in the stack and thus is found first
+// at next monitor exit.
+void TemplateTable::monitorenter() {
+  transition(atos, vtos);
+
+  __ verify_oop(R17_tos);
+
+  Register Rcurrent_monitor  = R11_scratch1,
+           Rcurrent_obj      = R12_scratch2,
+           Robj_to_lock      = R17_tos,
+           Rscratch1         = R3_ARG1,
+           Rscratch2         = R4_ARG2,
+           Rscratch3         = R5_ARG3,
+           Rcurrent_obj_addr = R6_ARG4;
+
+  // ------------------------------------------------------------------------------
+  // Null pointer exception.
+  __ null_check_throw(Robj_to_lock, -1, R11_scratch1);
+
+  // Try to acquire a lock on the object.
+  // Repeat until succeeded (i.e., until monitorenter returns true).
+
+  // ------------------------------------------------------------------------------
+  // Find a free slot in the monitor block.
+  Label Lfound, Lexit, Lallocate_new;
+  ConditionRegister found_free_slot = CCR0,
+                    found_same_obj  = CCR1,
+                    reached_limit   = CCR6;
+  {
+    Label Lloop, Lentry;
+    Register Rlimit = Rcurrent_monitor;
+
+    // Set up search loop - start with topmost monitor.
+    __ add(Rcurrent_obj_addr, BasicObjectLock::obj_offset_in_bytes(), R26_monitor);
+
+    __ ld(Rlimit, 0, R1_SP);
+    __ addi(Rlimit, Rlimit, - (frame::ijava_state_size + frame::interpreter_frame_monitor_size_in_bytes() - BasicObjectLock::obj_offset_in_bytes())); // Monitor base
+
+    // Check if any slot is present => short cut to allocation if not.
+    __ cmpld(reached_limit, Rcurrent_obj_addr, Rlimit);
+    __ bgt(reached_limit, Lallocate_new);
+
+    // Pre-load topmost slot.
+    __ ld(Rcurrent_obj, 0, Rcurrent_obj_addr);
+    __ addi(Rcurrent_obj_addr, Rcurrent_obj_addr, frame::interpreter_frame_monitor_size() * wordSize);
+    // The search loop.
+    __ bind(Lloop);
+    // Found free slot?
+    __ cmpdi(found_free_slot, Rcurrent_obj, 0);
+    // Is this entry for same obj? If so, stop the search and take the found
+    // free slot or allocate a new one to enable recursive locking.
+    __ cmpd(found_same_obj, Rcurrent_obj, Robj_to_lock);
+    __ cmpld(reached_limit, Rcurrent_obj_addr, Rlimit);
+    __ beq(found_free_slot, Lexit);
+    __ beq(found_same_obj, Lallocate_new);
+    __ bgt(reached_limit, Lallocate_new);
+    // Check if last allocated BasicLockObj reached.
+    __ ld(Rcurrent_obj, 0, Rcurrent_obj_addr);
+    __ addi(Rcurrent_obj_addr, Rcurrent_obj_addr, frame::interpreter_frame_monitor_size() * wordSize);
+    // Next iteration if unchecked BasicObjectLocks exist on the stack.
+    __ b(Lloop);
+  }
+
+  // ------------------------------------------------------------------------------
+  // Check if we found a free slot.
+  __ bind(Lexit);
+
+  __ addi(Rcurrent_monitor, Rcurrent_obj_addr, -(frame::interpreter_frame_monitor_size() * wordSize) - BasicObjectLock::obj_offset_in_bytes());
+  __ addi(Rcurrent_obj_addr, Rcurrent_obj_addr, - frame::interpreter_frame_monitor_size() * wordSize);
+  __ b(Lfound);
+
+  // We didn't find a free BasicObjLock => allocate one.
+  __ align(32, 12);
+  __ bind(Lallocate_new);
+  __ add_monitor_to_stack(false, Rscratch1, Rscratch2);
+  __ mr(Rcurrent_monitor, R26_monitor);
+  __ addi(Rcurrent_obj_addr, R26_monitor, BasicObjectLock::obj_offset_in_bytes());
+
+  // ------------------------------------------------------------------------------
+  // We now have a slot to lock.
+  __ bind(Lfound);
+
+  // Increment bcp to point to the next bytecode, so exception handling for async. exceptions work correctly.
+  // The object has already been poped from the stack, so the expression stack looks correct.
+  __ addi(R14_bcp, R14_bcp, 1);
+
+  __ std(Robj_to_lock, 0, Rcurrent_obj_addr);
+  __ lock_object(Rcurrent_monitor, Robj_to_lock);
+
+  // Check if there's enough space on the stack for the monitors after locking.
+  Label Lskip_stack_check;
+  // Optimization: If the monitors stack section is less then a std page size (4K) don't run
+  // the stack check. There should be enough shadow pages to fit that in.
+  __ ld(Rscratch3, 0, R1_SP);
+  __ sub(Rscratch3, Rscratch3, R26_monitor);
+  __ cmpdi(CCR0, Rscratch3, 4*K);
+  __ blt(CCR0, Lskip_stack_check);
+
+  DEBUG_ONLY(__ untested("stack overflow check during monitor enter");)
+  __ li(Rscratch1, 0);
+  __ generate_stack_overflow_check_with_compare_and_throw(Rscratch1, Rscratch2);
+
+  __ align(32, 12);
+  __ bind(Lskip_stack_check);
+
+  // The bcp has already been incremented. Just need to dispatch to next instruction.
+  __ dispatch_next(vtos);
+}
+
+void TemplateTable::monitorexit() {
+  transition(atos, vtos);
+  __ verify_oop(R17_tos);
+
+  Register Rcurrent_monitor  = R11_scratch1,
+           Rcurrent_obj      = R12_scratch2,
+           Robj_to_lock      = R17_tos,
+           Rcurrent_obj_addr = R3_ARG1,
+           Rlimit            = R4_ARG2;
+  Label Lfound, Lillegal_monitor_state;
+
+  // Check corner case: unbalanced monitorEnter / Exit.
+  __ ld(Rlimit, 0, R1_SP);
+  __ addi(Rlimit, Rlimit, - (frame::ijava_state_size + frame::interpreter_frame_monitor_size_in_bytes())); // Monitor base
+
+  // Null pointer check.
+  __ null_check_throw(Robj_to_lock, -1, R11_scratch1);
+
+  __ cmpld(CCR0, R26_monitor, Rlimit);
+  __ bgt(CCR0, Lillegal_monitor_state);
+
+  // Find the corresponding slot in the monitors stack section.
+  {
+    Label Lloop;
+
+    // Start with topmost monitor.
+    __ addi(Rcurrent_obj_addr, R26_monitor, BasicObjectLock::obj_offset_in_bytes());
+    __ addi(Rlimit, Rlimit, BasicObjectLock::obj_offset_in_bytes());
+    __ ld(Rcurrent_obj, 0, Rcurrent_obj_addr);
+    __ addi(Rcurrent_obj_addr, Rcurrent_obj_addr, frame::interpreter_frame_monitor_size() * wordSize);
+
+    __ bind(Lloop);
+    // Is this entry for same obj?
+    __ cmpd(CCR0, Rcurrent_obj, Robj_to_lock);
+    __ beq(CCR0, Lfound);
+
+    // Check if last allocated BasicLockObj reached.
+
+    __ ld(Rcurrent_obj, 0, Rcurrent_obj_addr);
+    __ cmpld(CCR0, Rcurrent_obj_addr, Rlimit);
+    __ addi(Rcurrent_obj_addr, Rcurrent_obj_addr, frame::interpreter_frame_monitor_size() * wordSize);
+
+    // Next iteration if unchecked BasicObjectLocks exist on the stack.
+    __ ble(CCR0, Lloop);
+  }
+
+  // Fell through without finding the basic obj lock => throw up!
+  __ bind(Lillegal_monitor_state);
+  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_illegal_monitor_state_exception));
+  __ should_not_reach_here();
+
+  __ align(32, 12);
+  __ bind(Lfound);
+  __ addi(Rcurrent_monitor, Rcurrent_obj_addr,
+          -(frame::interpreter_frame_monitor_size() * wordSize) - BasicObjectLock::obj_offset_in_bytes());
+  __ unlock_object(Rcurrent_monitor);
+}
+
+// ============================================================================
+// Wide bytecodes
+
+// Wide instructions. Simply redirects to the wide entry point for that instruction.
+void TemplateTable::wide() {
+  transition(vtos, vtos);
+
+  const Register Rtable = R11_scratch1,
+                 Rindex = R12_scratch2,
+                 Rtmp   = R0;
+
+  __ lbz(Rindex, 1, R14_bcp);
+
+  __ load_dispatch_table(Rtable, Interpreter::_wentry_point);
+
+  __ slwi(Rindex, Rindex, LogBytesPerWord);
+  __ ldx(Rtmp, Rtable, Rindex);
+  __ mtctr(Rtmp);
+  __ bctr();
+  // Note: the bcp increment step is part of the individual wide bytecode implementations.
+}
+#endif // !CC_INTERP
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/src/cpu/ppc/vm/templateTable_ppc_64.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2013, 2014 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.
+ *
+ */
+
+#ifndef CPU_PPC_VM_TEMPLATETABLE_PPC_64_HPP
+#define CPU_PPC_VM_TEMPLATETABLE_PPC_64_HPP
+
+  static void prepare_invoke(int byte_no, Register Rmethod, Register Rret_addr, Register Rindex, Register Rrecv, Register Rflags, Register Rscratch);
+  static void invokevfinal_helper(Register Rmethod, Register Rflags, Register Rscratch1, Register Rscratch2);
+  static void generate_vtable_call(Register Rrecv_klass, Register Rindex, Register Rret, Register Rtemp);
+  static void invokeinterface_object_method(Register Rrecv_klass, Register Rret, Register Rflags, Register Rindex, Register Rtemp, Register Rtemp2);
+
+  // Branch_conditional which takes TemplateTable::Condition.
+  static void branch_conditional(ConditionRegister crx, TemplateTable::Condition cc, Label& L, bool invert = false);
+  static void if_cmp_common(Register Rfirst, Register Rsecond, Register Rscratch1, Register Rscratch2, Condition cc, bool is_jint, bool cmp0);
+
+#endif // CPU_PPC_VM_TEMPLATETABLE_PPC_64_HPP
--- a/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -24,7 +24,8 @@
  */
 
 #include "precompiled.hpp"
-#include "assembler_ppc.inline.hpp"
+#include "asm/assembler.inline.hpp"
+#include "asm/macroAssembler.inline.hpp"
 #include "compiler/disassembler.hpp"
 #include "memory/resourceArea.hpp"
 #include "runtime/java.hpp"
@@ -168,7 +169,7 @@
 
   uint32_t *code = (uint32_t *)a->pc();
   // Emit code.
-  void (*test1)() = (void(*)())(void *)a->emit_fd();
+  void (*test1)() = (void(*)())(void *)a->function_entry();
 
   Label l1;
 
@@ -242,7 +243,7 @@
   a->blr();
 
   // Emit code.
-  void (*test2)() = (void(*)())(void *)a->emit_fd();
+  void (*test2)() = (void(*)())(void *)a->function_entry();
   // uint32_t *code = (uint32_t *)a->pc();
 
   Label l2;
@@ -383,8 +384,12 @@
 #endif // COMPILER2
 
 void VM_Version::determine_features() {
+#if defined(ABI_ELFv2)
+  const int code_size = (num_features+1+2*7)*BytesPerInstWord; // TODO(asmundak): calculation is incorrect.
+#else
   // 7 InstWords for each call (function descriptor + blr instruction).
   const int code_size = (num_features+1+2*7)*BytesPerInstWord;
+#endif
   int features = 0;
 
   // create test area
@@ -398,7 +403,7 @@
   MacroAssembler* a = new MacroAssembler(&cb);
 
   // Emit code.
-  void (*test)(address addr, uint64_t offset)=(void(*)(address addr, uint64_t offset))(void *)a->emit_fd();
+  void (*test)(address addr, uint64_t offset)=(void(*)(address addr, uint64_t offset))(void *)a->function_entry();
   uint32_t *code = (uint32_t *)a->pc();
   // Don't use R0 in ldarx.
   // Keep R3_ARG1 unmodified, it contains &field (see below).
@@ -415,7 +420,7 @@
   a->blr();
 
   // Emit function to set one cache line to zero. Emit function descriptor and get pointer to it.
-  void (*zero_cacheline_func_ptr)(char*) = (void(*)(char*))(void *)a->emit_fd();
+  void (*zero_cacheline_func_ptr)(char*) = (void(*)(char*))(void *)a->function_entry();
   a->dcbz(R3_ARG1); // R3_ARG1 = addr
   a->blr();
 
--- a/hotspot/src/cpu/sparc/vm/cppInterpreter_sparc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/sparc/vm/cppInterpreter_sparc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -413,16 +413,15 @@
   // Update standard invocation counters
   __ increment_invocation_counter(Rcounters, O0, G4_scratch);
   if (ProfileInterpreter) {
-    Address interpreter_invocation_counter(Rcounters, 0,
+    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);
   }
 
-  Address invocation_limit(G3_scratch, (address)&InvocationCounter::InterpreterInvocationLimit);
-  __ sethi(invocation_limit);
-  __ ld(invocation_limit, G3_scratch);
+  AddressLiteral invocation_limit((address)&InvocationCounter::InterpreterInvocationLimit);
+  __ load_contents(invocation_limit, G3_scratch);
   __ cmp(O0, G3_scratch);
   __ br(Assembler::greaterEqualUnsigned, false, Assembler::pn, *overflow);
   __ delayed()->nop();
@@ -439,7 +438,7 @@
   // do nothing for empty methods (do not even increment invocation counter)
   if ( UseFastEmptyMethods) {
     // If we need a safepoint check, generate full interpreter entry.
-    Address sync_state(G3_scratch, SafepointSynchronize::address_of_state());
+    AddressLiteral sync_state(SafepointSynchronize::address_of_state());
     __ load_contents(sync_state, G3_scratch);
     __ cmp(G3_scratch, SafepointSynchronize::_not_synchronized);
     __ br(Assembler::notEqual, false, Assembler::pn, frame_manager_entry);
@@ -471,7 +470,7 @@
   if ( UseFastAccessorMethods) {
     // Check if we need to reach a safepoint and generate full interpreter
     // frame if so.
-    Address sync_state(G3_scratch, SafepointSynchronize::address_of_state());
+    AddressLiteral sync_state(SafepointSynchronize::address_of_state());
     __ load_contents(sync_state, G3_scratch);
     __ cmp(G3_scratch, SafepointSynchronize::_not_synchronized);
     __ br(Assembler::notEqual, false, Assembler::pn, slow_path);
@@ -486,8 +485,8 @@
 
     // read first instruction word and extract bytecode @ 1 and index @ 2
     // get first 4 bytes of the bytecodes (big endian!)
-    __ ld_ptr(Address(G5_method, 0, in_bytes(Method::const_offset())), G1_scratch);
-    __ ld(Address(G1_scratch, 0, in_bytes(ConstMethod::codes_offset())), G1_scratch);
+    __ ld_ptr(Address(G5_method, in_bytes(Method::const_offset())), G1_scratch);
+    __ ld(Address(G1_scratch, in_bytes(ConstMethod::codes_offset())), G1_scratch);
 
     // move index @ 2 far left then to the right most two bytes.
     __ sll(G1_scratch, 2*BitsPerByte, G1_scratch);
@@ -590,15 +589,15 @@
   const Register Gtmp1 = G3_scratch ;
   const Register Gtmp2 = G1_scratch;
   const Register RconstMethod = Gtmp1;
-  const Address constMethod(G5_method, 0, in_bytes(Method::const_offset()));
-  const Address size_of_parameters(RconstMethod, 0, in_bytes(ConstMethod::size_of_parameters_offset()));
+  const Address constMethod(G5_method, in_bytes(Method::const_offset()));
+  const Address size_of_parameters(RconstMethod, in_bytes(ConstMethod::size_of_parameters_offset()));
 
   bool inc_counter  = UseCompiler || CountCompiledCalls;
 
   // make sure registers are different!
   assert_different_registers(G2_thread, G5_method, Gargs, Gtmp1, Gtmp2);
 
-  const Address access_flags      (G5_method, 0, in_bytes(Method::access_flags_offset()));
+  const Address access_flags      (G5_method, in_bytes(Method::access_flags_offset()));
 
   Label Lentry;
   __ bind(Lentry);
@@ -643,7 +642,7 @@
   // At this point Lstate points to new interpreter state
   //
 
-  const Address do_not_unlock_if_synchronized(G2_thread, 0,
+  const Address do_not_unlock_if_synchronized(G2_thread,
       in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
   // Since at this point in the method invocation the exception handler
   // would try to exit the monitor of synchronized methods which hasn't
@@ -717,17 +716,17 @@
 
   { Label L;
     __ ld_ptr(STATE(_method), G5_method);
-    __ ld_ptr(Address(G5_method, 0, in_bytes(Method::signature_handler_offset())), G3_scratch);
+    __ ld_ptr(Address(G5_method, in_bytes(Method::signature_handler_offset())), G3_scratch);
     __ tst(G3_scratch);
     __ brx(Assembler::notZero, false, Assembler::pt, L);
     __ delayed()->nop();
     __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::prepare_native_call), G5_method, false);
     __ ld_ptr(STATE(_method), G5_method);
 
-    Address exception_addr(G2_thread, 0, in_bytes(Thread::pending_exception_offset()));
+    Address exception_addr(G2_thread, in_bytes(Thread::pending_exception_offset()));
     __ ld_ptr(exception_addr, G3_scratch);
     __ br_notnull_short(G3_scratch, Assembler::pn, pending_exception_present);
-    __ ld_ptr(Address(G5_method, 0, in_bytes(Method::signature_handler_offset())), G3_scratch);
+    __ ld_ptr(Address(G5_method, in_bytes(Method::signature_handler_offset())), G3_scratch);
     __ bind(L);
   }
 
@@ -771,13 +770,13 @@
     __ br( Assembler::zero, false, Assembler::pt, not_static);
     __ delayed()->
       // get native function entry point(O0 is a good temp until the very end)
-       ld_ptr(Address(G5_method, 0, in_bytes(Method::native_function_offset())), O0);
+       ld_ptr(Address(G5_method, in_bytes(Method::native_function_offset())), O0);
     // for static methods insert the mirror argument
     const int mirror_offset = in_bytes(Klass::java_mirror_offset());
 
-    __ ld_ptr(Address(G5_method, 0, in_bytes(Method:: const_offset())), O1);
-    __ ld_ptr(Address(O1, 0, in_bytes(ConstMethod::constants_offset())), O1);
-    __ ld_ptr(Address(O1, 0, ConstantPool::pool_holder_offset_in_bytes()), O1);
+    __ ld_ptr(Address(G5_method, in_bytes(Method:: const_offset())), O1);
+    __ ld_ptr(Address(O1, in_bytes(ConstMethod::constants_offset())), O1);
+    __ ld_ptr(Address(O1, ConstantPool::pool_holder_offset_in_bytes()), O1);
     __ ld_ptr(O1, mirror_offset, O1);
     // where the mirror handle body is allocated:
 #ifdef ASSERT
@@ -831,18 +830,17 @@
   // flush the windows now. We don't care about the current (protection) frame
   // only the outer frames
 
-  __ flush_windows();
+  __ flushw();
 
   // mark windows as flushed
   Address flags(G2_thread,
-                0,
                 in_bytes(JavaThread::frame_anchor_offset()) + in_bytes(JavaFrameAnchor::flags_offset()));
   __ set(JavaFrameAnchor::flushed, G3_scratch);
   __ st(G3_scratch, flags);
 
   // Transition from _thread_in_Java to _thread_in_native. We are already safepoint ready.
 
-  Address thread_state(G2_thread, 0, in_bytes(JavaThread::thread_state_offset()));
+  Address thread_state(G2_thread, in_bytes(JavaThread::thread_state_offset()));
 #ifdef ASSERT
   { Label L;
     __ ld(thread_state, G3_scratch);
@@ -867,7 +865,7 @@
   // Block, if necessary, before resuming in _thread_in_Java state.
   // In order for GC to work, don't clear the last_Java_sp until after blocking.
   { Label no_block;
-    Address sync_state(G3_scratch, SafepointSynchronize::address_of_state());
+    AddressLiteral sync_state(SafepointSynchronize::address_of_state());
 
     // Switch thread to "native transition" state before reading the synchronization state.
     // This additional state is necessary because reading and testing the synchronization
@@ -890,7 +888,7 @@
 
 
     Label L;
-    Address suspend_state(G2_thread, 0, in_bytes(JavaThread::suspend_flags_offset()));
+    Address suspend_state(G2_thread, in_bytes(JavaThread::suspend_flags_offset()));
     __ br(Assembler::notEqual, false, Assembler::pn, L);
     __ delayed()->
       ld(suspend_state, G3_scratch);
@@ -965,7 +963,7 @@
 
   // handle exceptions (exception handling will handle unlocking!)
   { Label L;
-    Address exception_addr (G2_thread, 0, in_bytes(Thread::pending_exception_offset()));
+    Address exception_addr (G2_thread, in_bytes(Thread::pending_exception_offset()));
 
     __ ld_ptr(exception_addr, Gtemp);
     __ tst(Gtemp);
@@ -1055,8 +1053,8 @@
   assert_different_registers(state, prev_state);
   assert_different_registers(prev_state, G3_scratch);
   const Register Gtmp = G3_scratch;
-  const Address constMethod       (G5_method, 0, in_bytes(Method::const_offset()));
-  const Address access_flags      (G5_method, 0, in_bytes(Method::access_flags_offset()));
+  const Address constMethod       (G5_method, in_bytes(Method::const_offset()));
+  const Address access_flags      (G5_method, in_bytes(Method::access_flags_offset()));
 
   // slop factor is two extra slots on the expression stack so that
   // we always have room to store a result when returning from a call without parameters
@@ -1075,7 +1073,7 @@
 
   if (native) {
     const Register RconstMethod = Gtmp;
-    const Address size_of_parameters(RconstMethod, 0, in_bytes(ConstMethod::size_of_parameters_offset()));
+    const Address size_of_parameters(RconstMethod, in_bytes(ConstMethod::size_of_parameters_offset()));
     __ ld_ptr(constMethod, RconstMethod);
     __ lduh( size_of_parameters, Gtmp );
     __ calc_mem_param_words(Gtmp, Gtmp);     // space for native call parameters passed on the stack in words
@@ -1246,8 +1244,8 @@
     if (init_value != noreg) {
       Label clear_loop;
       const Register RconstMethod = O1;
-      const Address size_of_parameters(RconstMethod, 0, in_bytes(ConstMethod::size_of_parameters_offset()));
-      const Address size_of_locals    (RconstMethod, 0, in_bytes(ConstMethod::size_of_locals_offset()));
+      const Address size_of_parameters(RconstMethod, in_bytes(ConstMethod::size_of_parameters_offset()));
+      const Address size_of_locals    (RconstMethod, in_bytes(ConstMethod::size_of_locals_offset()));
 
       // NOTE: If you change the frame layout, this code will need to
       // be updated!
@@ -1496,11 +1494,11 @@
 //
 //  assert_different_registers(state, prev_state);
   const Register Gtmp = G3_scratch;
-  const RconstMethod = G3_scratch;
+  const Register RconstMethod = G3_scratch;
   const Register tmp = O2;
-  const Address constMethod(G5_method, 0, in_bytes(Method::const_offset()));
-  const Address size_of_parameters(RconstMethod, 0, in_bytes(ConstMethod::size_of_parameters_offset()));
-  const Address size_of_locals    (RconstMethod, 0, in_bytes(ConstMethod::size_of_locals_offset()));
+  const Address constMethod(G5_method, in_bytes(Method::const_offset()));
+  const Address size_of_parameters(RconstMethod, in_bytes(ConstMethod::size_of_parameters_offset()));
+  const Address size_of_locals    (RconstMethod, in_bytes(ConstMethod::size_of_locals_offset()));
 
   __ ld_ptr(constMethod, RconstMethod);
   __ lduh(size_of_parameters, tmp);
@@ -1555,8 +1553,8 @@
   const Register Gtmp1 = G3_scratch;
   // const Register Lmirror = L1;     // native mirror (native calls only)
 
-  const Address constMethod       (G5_method, 0, in_bytes(Method::const_offset()));
-  const Address access_flags      (G5_method, 0, in_bytes(Method::access_flags_offset()));
+  const Address constMethod       (G5_method, in_bytes(Method::const_offset()));
+  const Address access_flags      (G5_method, in_bytes(Method::access_flags_offset()));
 
   address entry_point = __ pc();
   __ mov(G0, prevState);                                                 // no current activation
@@ -1709,7 +1707,7 @@
 
   // We want exception in the thread no matter what we ultimately decide about frame type.
 
-  Address exception_addr (G2_thread, 0, in_bytes(Thread::pending_exception_offset()));
+  Address exception_addr (G2_thread, in_bytes(Thread::pending_exception_offset()));
   __ verify_thread();
   __ st_ptr(O0, exception_addr);
 
--- a/hotspot/src/cpu/sparc/vm/frame_sparc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/sparc/vm/frame_sparc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -827,6 +827,7 @@
   }
 
   if (is_interpreted_frame()) {
+#ifndef CC_INTERP
     DESCRIBE_FP_OFFSET(interpreter_frame_d_scratch_fp);
     DESCRIBE_FP_OFFSET(interpreter_frame_l_scratch_fp);
     DESCRIBE_FP_OFFSET(interpreter_frame_padding);
@@ -837,6 +838,7 @@
     if ((esp >= sp()) && (esp < fp())) {
       values.describe(-1, esp, "*Lesp");
     }
+#endif
   }
 
   if (!is_compiled_frame()) {
--- a/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -2497,6 +2497,24 @@
 void InterpreterMacroAssembler::verify_FPU(int stack_depth, TosState state) {
   if (state == ftos || state == dtos) MacroAssembler::verify_FPU(stack_depth);
 }
+
+
+// Jump if ((*counter_addr += increment) & mask) satisfies the condition.
+void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr,
+                                                        int increment, int mask,
+                                                        Register scratch1, Register scratch2,
+                                                        Condition cond, Label *where) {
+  ld(counter_addr, scratch1);
+  add(scratch1, increment, scratch1);
+  if (is_simm13(mask)) {
+    andcc(scratch1, mask, G0);
+  } else {
+    set(mask, scratch2);
+    andcc(scratch1, scratch2,  G0);
+  }
+  br(cond, false, Assembler::pn, *where);
+  delayed()->st(scratch1, counter_addr);
+}
 #endif /* CC_INTERP */
 
 // Inline assembly for:
@@ -2646,20 +2664,3 @@
   }
 #endif // CC_INTERP
 }
-
-// Jump if ((*counter_addr += increment) & mask) satisfies the condition.
-void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr,
-                                                        int increment, int mask,
-                                                        Register scratch1, Register scratch2,
-                                                        Condition cond, Label *where) {
-  ld(counter_addr, scratch1);
-  add(scratch1, increment, scratch1);
-  if (is_simm13(mask)) {
-    andcc(scratch1, mask, G0);
-  } else {
-    set(mask, scratch2);
-    andcc(scratch1, scratch2,  G0);
-  }
-  br(cond, false, Assembler::pn, *where);
-  delayed()->st(scratch1, counter_addr);
-}
--- a/hotspot/src/cpu/sparc/vm/nativeInst_sparc.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/sparc/vm/nativeInst_sparc.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -23,7 +23,8 @@
  */
 
 #include "precompiled.hpp"
-#include "asm/macroAssembler.hpp"
+#include "asm/macroAssembler.inline.hpp"
+#include "code/codeCache.hpp"
 #include "memory/resourceArea.hpp"
 #include "nativeInst_sparc.hpp"
 #include "oops/oop.inline.hpp"
--- a/hotspot/src/cpu/x86/vm/assembler_x86.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/assembler_x86.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1089,6 +1089,21 @@
   emit_arith(0x23, 0xC0, dst, src);
 }
 
+void Assembler::andnl(Register dst, Register src1, Register src2) {
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  int encode = vex_prefix_0F38_and_encode(dst, src1, src2);
+  emit_int8((unsigned char)0xF2);
+  emit_int8((unsigned char)(0xC0 | encode));
+}
+
+void Assembler::andnl(Register dst, Register src1, Address src2) {
+  InstructionMark im(this);
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  vex_prefix_0F38(dst, src1, src2);
+  emit_int8((unsigned char)0xF2);
+  emit_operand(dst, src2);
+}
+
 void Assembler::bsfl(Register dst, Register src) {
   int encode = prefix_and_encode(dst->encoding(), src->encoding());
   emit_int8(0x0F);
@@ -1110,6 +1125,51 @@
   emit_int8((unsigned char)(0xC8 | encode));
 }
 
+void Assembler::blsil(Register dst, Register src) {
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  int encode = vex_prefix_0F38_and_encode(rbx, dst, src);
+  emit_int8((unsigned char)0xF3);
+  emit_int8((unsigned char)(0xC0 | encode));
+}
+
+void Assembler::blsil(Register dst, Address src) {
+  InstructionMark im(this);
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  vex_prefix_0F38(rbx, dst, src);
+  emit_int8((unsigned char)0xF3);
+  emit_operand(rbx, src);
+}
+
+void Assembler::blsmskl(Register dst, Register src) {
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  int encode = vex_prefix_0F38_and_encode(rdx, dst, src);
+  emit_int8((unsigned char)0xF3);
+  emit_int8((unsigned char)(0xC0 | encode));
+}
+
+void Assembler::blsmskl(Register dst, Address src) {
+  InstructionMark im(this);
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  vex_prefix_0F38(rdx, dst, src);
+  emit_int8((unsigned char)0xF3);
+  emit_operand(rdx, src);
+}
+
+void Assembler::blsrl(Register dst, Register src) {
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  int encode = vex_prefix_0F38_and_encode(rcx, dst, src);
+  emit_int8((unsigned char)0xF3);
+  emit_int8((unsigned char)(0xC0 | encode));
+}
+
+void Assembler::blsrl(Register dst, Address src) {
+  InstructionMark im(this);
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  vex_prefix_0F38(rcx, dst, src);
+  emit_int8((unsigned char)0xF3);
+  emit_operand(rcx, src);
+}
+
 void Assembler::call(Label& L, relocInfo::relocType rtype) {
   // suspect disp32 is always good
   int operand = LP64_ONLY(disp32_operand) NOT_LP64(imm_operand);
@@ -2878,6 +2938,24 @@
   emit_operand(dst, src);
 }
 
+void Assembler::tzcntl(Register dst, Register src) {
+  assert(VM_Version::supports_bmi1(), "tzcnt instruction not supported");
+  emit_int8((unsigned char)0xF3);
+  int encode = prefix_and_encode(dst->encoding(), src->encoding());
+  emit_int8(0x0F);
+  emit_int8((unsigned char)0xBC);
+  emit_int8((unsigned char)0xC0 | encode);
+}
+
+void Assembler::tzcntq(Register dst, Register src) {
+  assert(VM_Version::supports_bmi1(), "tzcnt instruction not supported");
+  emit_int8((unsigned char)0xF3);
+  int encode = prefixq_and_encode(dst->encoding(), src->encoding());
+  emit_int8(0x0F);
+  emit_int8((unsigned char)0xBC);
+  emit_int8((unsigned char)(0xC0 | encode));
+}
+
 void Assembler::ucomisd(XMMRegister dst, Address src) {
   NOT_LP64(assert(VM_Version::supports_sse2(), ""));
   emit_simd_arith_nonds(0x2E, dst, src, VEX_SIMD_66);
@@ -4837,6 +4915,21 @@
   emit_arith(0x23, 0xC0, dst, src);
 }
 
+void Assembler::andnq(Register dst, Register src1, Register src2) {
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  int encode = vex_prefix_0F38_and_encode_q(dst, src1, src2);
+  emit_int8((unsigned char)0xF2);
+  emit_int8((unsigned char)(0xC0 | encode));
+}
+
+void Assembler::andnq(Register dst, Register src1, Address src2) {
+  InstructionMark im(this);
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  vex_prefix_0F38_q(dst, src1, src2);
+  emit_int8((unsigned char)0xF2);
+  emit_operand(dst, src2);
+}
+
 void Assembler::bsfq(Register dst, Register src) {
   int encode = prefixq_and_encode(dst->encoding(), src->encoding());
   emit_int8(0x0F);
@@ -4858,6 +4951,51 @@
   emit_int8((unsigned char)(0xC8 | encode));
 }
 
+void Assembler::blsiq(Register dst, Register src) {
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  int encode = vex_prefix_0F38_and_encode_q(rbx, dst, src);
+  emit_int8((unsigned char)0xF3);
+  emit_int8((unsigned char)(0xC0 | encode));
+}
+
+void Assembler::blsiq(Register dst, Address src) {
+  InstructionMark im(this);
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  vex_prefix_0F38_q(rbx, dst, src);
+  emit_int8((unsigned char)0xF3);
+  emit_operand(rbx, src);
+}
+
+void Assembler::blsmskq(Register dst, Register src) {
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  int encode = vex_prefix_0F38_and_encode_q(rdx, dst, src);
+  emit_int8((unsigned char)0xF3);
+  emit_int8((unsigned char)(0xC0 | encode));
+}
+
+void Assembler::blsmskq(Register dst, Address src) {
+  InstructionMark im(this);
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  vex_prefix_0F38_q(rdx, dst, src);
+  emit_int8((unsigned char)0xF3);
+  emit_operand(rdx, src);
+}
+
+void Assembler::blsrq(Register dst, Register src) {
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  int encode = vex_prefix_0F38_and_encode_q(rcx, dst, src);
+  emit_int8((unsigned char)0xF3);
+  emit_int8((unsigned char)(0xC0 | encode));
+}
+
+void Assembler::blsrq(Register dst, Address src) {
+  InstructionMark im(this);
+  assert(VM_Version::supports_bmi1(), "bit manipulation instructions not supported");
+  vex_prefix_0F38_q(rcx, dst, src);
+  emit_int8((unsigned char)0xF3);
+  emit_operand(rcx, src);
+}
+
 void Assembler::cdqq() {
   prefix(REX_W);
   emit_int8((unsigned char)0x99);
--- a/hotspot/src/cpu/x86/vm/assembler_x86.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/assembler_x86.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -590,10 +590,35 @@
     vex_prefix(src, nds_enc, dst_enc, pre, VEX_OPCODE_0F, false, vector256);
   }
 
+  void vex_prefix_0F38(Register dst, Register nds, Address src) {
+    bool vex_w = false;
+    bool vector256 = false;
+    vex_prefix(src, nds->encoding(), dst->encoding(),
+               VEX_SIMD_NONE, VEX_OPCODE_0F_38, vex_w, vector256);
+  }
+
+  void vex_prefix_0F38_q(Register dst, Register nds, Address src) {
+    bool vex_w = true;
+    bool vector256 = false;
+    vex_prefix(src, nds->encoding(), dst->encoding(),
+               VEX_SIMD_NONE, VEX_OPCODE_0F_38, vex_w, vector256);
+  }
   int  vex_prefix_and_encode(int dst_enc, int nds_enc, int src_enc,
                              VexSimdPrefix pre, VexOpcode opc,
                              bool vex_w, bool vector256);
 
+  int  vex_prefix_0F38_and_encode(Register dst, Register nds, Register src) {
+    bool vex_w = false;
+    bool vector256 = false;
+    return vex_prefix_and_encode(dst->encoding(), nds->encoding(), src->encoding(),
+                                 VEX_SIMD_NONE, VEX_OPCODE_0F_38, vex_w, vector256);
+  }
+  int  vex_prefix_0F38_and_encode_q(Register dst, Register nds, Register src) {
+    bool vex_w = true;
+    bool vector256 = false;
+    return vex_prefix_and_encode(dst->encoding(), nds->encoding(), src->encoding(),
+                                 VEX_SIMD_NONE, VEX_OPCODE_0F_38, vex_w, vector256);
+  }
   int  vex_prefix_and_encode(XMMRegister dst, XMMRegister nds, XMMRegister src,
                              VexSimdPrefix pre, bool vector256 = false,
                              VexOpcode opc = VEX_OPCODE_0F) {
@@ -897,6 +922,27 @@
   void andq(Register dst, Address src);
   void andq(Register dst, Register src);
 
+  // BMI instructions
+  void andnl(Register dst, Register src1, Register src2);
+  void andnl(Register dst, Register src1, Address src2);
+  void andnq(Register dst, Register src1, Register src2);
+  void andnq(Register dst, Register src1, Address src2);
+
+  void blsil(Register dst, Register src);
+  void blsil(Register dst, Address src);
+  void blsiq(Register dst, Register src);
+  void blsiq(Register dst, Address src);
+
+  void blsmskl(Register dst, Register src);
+  void blsmskl(Register dst, Address src);
+  void blsmskq(Register dst, Register src);
+  void blsmskq(Register dst, Address src);
+
+  void blsrl(Register dst, Register src);
+  void blsrl(Register dst, Address src);
+  void blsrq(Register dst, Register src);
+  void blsrq(Register dst, Address src);
+
   void bsfl(Register dst, Register src);
   void bsrl(Register dst, Register src);
 
@@ -1574,6 +1620,9 @@
   void testq(Register dst, int32_t imm32);
   void testq(Register dst, Register src);
 
+  // BMI - count trailing zeros
+  void tzcntl(Register dst, Register src);
+  void tzcntq(Register dst, Register src);
 
   // Unordered Compare Scalar Double-Precision Floating-Point Values and set EFLAGS
   void ucomisd(XMMRegister dst, Address src);
--- a/hotspot/src/cpu/x86/vm/bytecodeInterpreter_x86.inline.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/bytecodeInterpreter_x86.inline.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -250,7 +250,7 @@
   return op1 - op2;
 }
 
-inline jint BytecodeInterpreter::VMintUshr(jint op1, jint op2) {
+inline juint BytecodeInterpreter::VMintUshr(jint op1, jint op2) {
   return ((juint) op1) >> (op2 & 0x1f);
 }
 
--- a/hotspot/src/cpu/x86/vm/cppInterpreter_x86.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/cppInterpreter_x86.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -574,7 +574,7 @@
                 MethodCounters::invocation_counter_offset() +
                 InvocationCounter::counter_offset());
   const Address backedge_counter  (rax,
-                MethodCounter::backedge_counter_offset() +
+                MethodCounters::backedge_counter_offset() +
                 InvocationCounter::counter_offset());
 
   __ get_method_counters(rbx, rax, done);
@@ -982,16 +982,18 @@
   //      to save/restore.
   address entry_point = __ pc();
 
-  const Address constMethod       (rbx, Method::const_offset());
   const Address access_flags      (rbx, Method::access_flags_offset());
-  const Address size_of_parameters(rcx, ConstMethod::size_of_parameters_offset());
 
   // rsi/r13 == state/locals rdi == prevstate
   const Register locals = rdi;
 
   // get parameter size (always needed)
-  __ movptr(rcx, constMethod);
-  __ load_unsigned_short(rcx, size_of_parameters);
+  {
+    const Address constMethod       (rbx, Method::const_offset());
+    const Address size_of_parameters(rcx, ConstMethod::size_of_parameters_offset());
+    __ movptr(rcx, constMethod);
+    __ load_unsigned_short(rcx, size_of_parameters);
+  }
 
   // rbx: Method*
   // rcx: size of parameters
@@ -1111,14 +1113,16 @@
   const Register method = rbx;
   const Register thread = LP64_ONLY(r15_thread) NOT_LP64(rdi);
   const Register t      = InterpreterRuntime::SignatureHandlerGenerator::temp();    // rcx|rscratch1
-  const Address constMethod       (method, Method::const_offset());
-  const Address size_of_parameters(t, ConstMethod::size_of_parameters_offset());
-
-  // allocate space for parameters
+
+ // allocate space for parameters
   __ movptr(method, STATE(_method));
   __ verify_method_ptr(method);
-  __ movptr(t, constMethod);
-  __ load_unsigned_short(t, size_of_parameters);
+  {
+    const Address constMethod       (method, Method::const_offset());
+    const Address size_of_parameters(t, ConstMethod::size_of_parameters_offset());
+    __ movptr(t, constMethod);
+    __ load_unsigned_short(t, size_of_parameters);
+  }
   __ shll(t, 2);
 #ifdef _LP64
   __ subptr(rsp, t);
@@ -2221,7 +2225,6 @@
     case Interpreter::empty                  : entry_point = ((InterpreterGenerator*)this)->generate_empty_entry();        break;
     case Interpreter::accessor               : entry_point = ((InterpreterGenerator*)this)->generate_accessor_entry();     break;
     case Interpreter::abstract               : entry_point = ((InterpreterGenerator*)this)->generate_abstract_entry();     break;
-    case Interpreter::method_handle          : entry_point = ((InterpreterGenerator*)this)->generate_method_handle_entry(); break;
 
     case Interpreter::java_lang_math_sin     : // fall thru
     case Interpreter::java_lang_math_cos     : // fall thru
@@ -2229,7 +2232,10 @@
     case Interpreter::java_lang_math_abs     : // fall thru
     case Interpreter::java_lang_math_log     : // fall thru
     case Interpreter::java_lang_math_log10   : // fall thru
-    case Interpreter::java_lang_math_sqrt    : entry_point = ((InterpreterGenerator*)this)->generate_math_entry(kind);     break;
+    case Interpreter::java_lang_math_sqrt    : // fall thru
+    case Interpreter::java_lang_math_pow     : // fall thru
+    case Interpreter::java_lang_math_exp     : // fall thru
+      entry_point = ((InterpreterGenerator*)this)->generate_math_entry(kind);     break;
     case Interpreter::java_lang_ref_reference_get
                                              : entry_point = ((InterpreterGenerator*)this)->generate_Reference_get_entry(); break;
     default                                  : ShouldNotReachHere();                                                       break;
@@ -2451,4 +2457,22 @@
   return frame_size/BytesPerWord;
 }
 
+bool AbstractInterpreter::can_be_compiled(methodHandle m) {
+  switch (method_kind(m)) {
+    case Interpreter::java_lang_math_sin     : // fall thru
+    case Interpreter::java_lang_math_cos     : // fall thru
+    case Interpreter::java_lang_math_tan     : // fall thru
+    case Interpreter::java_lang_math_abs     : // fall thru
+    case Interpreter::java_lang_math_log     : // fall thru
+    case Interpreter::java_lang_math_log10   : // fall thru
+    case Interpreter::java_lang_math_sqrt    : // fall thru
+    case Interpreter::java_lang_math_pow     : // fall thru
+    case Interpreter::java_lang_math_exp     :
+      return false;
+    default:
+      return true;
+  }
+}
+
+
 #endif // CC_INTERP (all)
--- a/hotspot/src/cpu/x86/vm/frame_x86.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/frame_x86.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -687,6 +687,7 @@
 
 void frame::describe_pd(FrameValues& values, int frame_no) {
   if (is_interpreted_frame()) {
+#ifndef CC_INTERP
     DESCRIBE_FP_OFFSET(interpreter_frame_sender_sp);
     DESCRIBE_FP_OFFSET(interpreter_frame_last_sp);
     DESCRIBE_FP_OFFSET(interpreter_frame_method);
@@ -695,6 +696,7 @@
     DESCRIBE_FP_OFFSET(interpreter_frame_locals);
     DESCRIBE_FP_OFFSET(interpreter_frame_bcx);
     DESCRIBE_FP_OFFSET(interpreter_frame_initial_sp);
+#endif
   }
 }
 #endif
--- a/hotspot/src/cpu/x86/vm/globals_x86.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/globals_x86.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -135,5 +135,11 @@
                                                                             \
   product(bool, UseCountLeadingZerosInstruction, false,                     \
           "Use count leading zeros instruction")                            \
+                                                                            \
+  product(bool, UseCountTrailingZerosInstruction, false,                    \
+          "Use count trailing zeros instruction")                           \
+                                                                            \
+  product(bool, UseBMI1Instructions, false,                                 \
+          "Use BMI instructions")
 
 #endif // CPU_X86_VM_GLOBALS_X86_HPP
--- a/hotspot/src/cpu/x86/vm/interp_masm_x86_32.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/interp_masm_x86_32.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -266,20 +266,6 @@
   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) {
@@ -678,6 +664,20 @@
 
 #endif /* !CC_INTERP */
 
+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);
+}
+
 
 // Lock object
 //
@@ -1359,6 +1359,19 @@
   if (state == ftos || state == dtos) MacroAssembler::verify_FPU(stack_depth);
 }
 
+// Jump if ((*counter_addr += increment) & mask) satisfies the condition.
+void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr,
+                                                        int increment, int mask,
+                                                        Register scratch, bool preloaded,
+                                                        Condition cond, Label* where) {
+  if (!preloaded) {
+    movl(scratch, counter_addr);
+  }
+  incrementl(scratch, increment);
+  movl(counter_addr, scratch);
+  andl(scratch, mask);
+  jcc(cond, *where);
+}
 #endif /* CC_INTERP */
 
 
@@ -1430,17 +1443,3 @@
     NOT_CC_INTERP(pop(state));
   }
 }
-
-// Jump if ((*counter_addr += increment) & mask) satisfies the condition.
-void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr,
-                                                        int increment, int mask,
-                                                        Register scratch, bool preloaded,
-                                                        Condition cond, Label* where) {
-  if (!preloaded) {
-    movl(scratch, counter_addr);
-  }
-  incrementl(scratch, increment);
-  movl(counter_addr, scratch);
-  andl(scratch, mask);
-  jcc(cond, *where);
-}
--- a/hotspot/src/cpu/x86/vm/interp_masm_x86_32.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/interp_masm_x86_32.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -77,7 +77,6 @@
   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);
@@ -156,6 +155,7 @@
                          bool install_monitor_exception = true,
                          bool notify_jvmdi = true);
 #endif /* !CC_INTERP */
+  void get_method_counters(Register method, Register mcs, Label& skip);
 
   // Debugging
   void verify_oop(Register reg, TosState state = atos);    // only if +VerifyOops && state == atos
--- a/hotspot/src/cpu/x86/vm/interp_masm_x86_64.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/interp_masm_x86_64.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -271,20 +271,6 @@
   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) {
@@ -676,6 +662,21 @@
 
 #endif // C_INTERP
 
+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);
+}
+
+
 // Lock object
 //
 // Args:
@@ -1423,6 +1424,20 @@
 
 void InterpreterMacroAssembler::verify_FPU(int stack_depth, TosState state) {
 }
+
+// Jump if ((*counter_addr += increment) & mask) satisfies the condition.
+void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr,
+                                                        int increment, int mask,
+                                                        Register scratch, bool preloaded,
+                                                        Condition cond, Label* where) {
+  if (!preloaded) {
+    movl(scratch, counter_addr);
+  }
+  incrementl(scratch, increment);
+  movl(counter_addr, scratch);
+  andl(scratch, mask);
+  jcc(cond, *where);
+}
 #endif // !CC_INTERP
 
 
@@ -1491,16 +1506,3 @@
   }
 }
 
-// Jump if ((*counter_addr += increment) & mask) satisfies the condition.
-void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr,
-                                                        int increment, int mask,
-                                                        Register scratch, bool preloaded,
-                                                        Condition cond, Label* where) {
-  if (!preloaded) {
-    movl(scratch, counter_addr);
-  }
-  incrementl(scratch, increment);
-  movl(counter_addr, scratch);
-  andl(scratch, mask);
-  jcc(cond, *where);
-}
--- a/hotspot/src/cpu/x86/vm/interp_masm_x86_64.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/interp_masm_x86_64.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -99,7 +99,6 @@
   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);
@@ -172,6 +171,7 @@
                          bool install_monitor_exception = true,
                          bool notify_jvmdi = true);
 #endif // CC_INTERP
+  void get_method_counters(Register method, Register mcs, Label& skip);
 
   // Object locking
   void lock_object  (Register lock_reg);
--- a/hotspot/src/cpu/x86/vm/interpreter_x86_32.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/interpreter_x86_32.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -229,10 +229,12 @@
 
   // abstract method entry
 
+#ifndef CC_INTERP
   //  pop return address, reset last_sp to NULL
   __ empty_expression_stack();
   __ restore_bcp();      // rsi must be correct for exception handler   (was destroyed)
   __ restore_locals();   // make sure locals pointer is correct as well (was destroyed)
+#endif
 
   // throw exception
   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodError));
--- a/hotspot/src/cpu/x86/vm/interpreter_x86_64.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/interpreter_x86_64.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -310,10 +310,12 @@
 
   // abstract method entry
 
+#ifndef CC_INTERP
   //  pop return address, reset last_sp to NULL
   __ empty_expression_stack();
   __ restore_bcp();      // rsi must be correct for exception handler   (was destroyed)
   __ restore_locals();   // make sure locals pointer is correct as well (was destroyed)
+#endif
 
   // throw exception
   __ call_VM(noreg, CAST_FROM_FN_PTR(address,
--- a/hotspot/src/cpu/x86/vm/vm_version_x86.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/vm_version_x86.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -429,7 +429,7 @@
   }
 
   char buf[256];
-  jio_snprintf(buf, sizeof(buf), "(%u cores per cpu, %u threads per core) family %d model %d stepping %d%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
+  jio_snprintf(buf, sizeof(buf), "(%u cores per cpu, %u threads per core) family %d model %d stepping %d%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
                cores_per_cpu(), threads_per_core(),
                cpu_family(), _model, _stepping,
                (supports_cmov() ? ", cmov" : ""),
@@ -455,7 +455,9 @@
                (supports_ht() ? ", ht": ""),
                (supports_tsc() ? ", tsc": ""),
                (supports_tscinv_bit() ? ", tscinvbit": ""),
-               (supports_tscinv() ? ", tscinv": ""));
+               (supports_tscinv() ? ", tscinv": ""),
+               (supports_bmi1() ? ", bmi1" : ""),
+               (supports_bmi2() ? ", bmi2" : ""));
   _features_str = strdup(buf);
 
   // UseSSE is set to the smaller of what hardware supports and what
@@ -600,13 +602,6 @@
       }
     }
 
-    // Use count leading zeros count instruction if available.
-    if (supports_lzcnt()) {
-      if (FLAG_IS_DEFAULT(UseCountLeadingZerosInstruction)) {
-        UseCountLeadingZerosInstruction = true;
-      }
-    }
-
     // some defaults for AMD family 15h
     if ( cpu_family() == 0x15 ) {
       // On family 15h processors default is no sw prefetch
@@ -692,6 +687,35 @@
     }
 #endif // COMPILER2
 
+  // Use count leading zeros count instruction if available.
+  if (supports_lzcnt()) {
+    if (FLAG_IS_DEFAULT(UseCountLeadingZerosInstruction)) {
+      UseCountLeadingZerosInstruction = true;
+    }
+   } else if (UseCountLeadingZerosInstruction) {
+    warning("lzcnt instruction is not available on this CPU");
+    FLAG_SET_DEFAULT(UseCountLeadingZerosInstruction, false);
+  }
+
+  if (supports_bmi1()) {
+    if (FLAG_IS_DEFAULT(UseBMI1Instructions)) {
+      UseBMI1Instructions = true;
+    }
+  } else if (UseBMI1Instructions) {
+    warning("BMI1 instructions are not available on this CPU");
+    FLAG_SET_DEFAULT(UseBMI1Instructions, false);
+  }
+
+  // Use count trailing zeros instruction if available
+  if (supports_bmi1()) {
+    if (FLAG_IS_DEFAULT(UseCountTrailingZerosInstruction)) {
+      UseCountTrailingZerosInstruction = UseBMI1Instructions;
+    }
+  } else if (UseCountTrailingZerosInstruction) {
+    warning("tzcnt instruction is not available on this CPU");
+    FLAG_SET_DEFAULT(UseCountTrailingZerosInstruction, false);
+  }
+
   // Use population count instruction if available.
   if (supports_popcnt()) {
     if (FLAG_IS_DEFAULT(UsePopCountInstruction)) {
--- a/hotspot/src/cpu/x86/vm/vm_version_x86.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/vm_version_x86.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -141,7 +141,8 @@
     struct {
       uint32_t LahfSahf     : 1,
                CmpLegacy    : 1,
-                            : 4,
+                            : 3,
+               lzcnt_intel  : 1,
                lzcnt        : 1,
                sse4a        : 1,
                misalignsse  : 1,
@@ -251,7 +252,9 @@
     CPU_AVX2   = (1 << 18),
     CPU_AES    = (1 << 19),
     CPU_ERMS   = (1 << 20), // enhanced 'rep movsb/stosb' instructions
-    CPU_CLMUL  = (1 << 21) // carryless multiply for CRC
+    CPU_CLMUL  = (1 << 21), // carryless multiply for CRC
+    CPU_BMI1   = (1 << 22),
+    CPU_BMI2   = (1 << 23)
   } cpuFeatureFlags;
 
   enum {
@@ -423,6 +426,8 @@
       if (_cpuid_info.sef_cpuid7_ebx.bits.avx2 != 0)
         result |= CPU_AVX2;
     }
+    if(_cpuid_info.sef_cpuid7_ebx.bits.bmi1 != 0)
+      result |= CPU_BMI1;
     if (_cpuid_info.std_cpuid1_edx.bits.tsc != 0)
       result |= CPU_TSC;
     if (_cpuid_info.ext_cpuid7_edx.bits.tsc_invariance != 0)
@@ -444,6 +449,13 @@
       if (_cpuid_info.ext_cpuid1_ecx.bits.sse4a != 0)
         result |= CPU_SSE4A;
     }
+    // Intel features.
+    if(is_intel()) {
+      if(_cpuid_info.sef_cpuid7_ebx.bits.bmi2 != 0)
+        result |= CPU_BMI2;
+      if(_cpuid_info.ext_cpuid1_ecx.bits.lzcnt_intel != 0)
+        result |= CPU_LZCNT;
+    }
 
     return result;
   }
@@ -560,7 +572,8 @@
   static bool supports_aes()      { return (_cpuFeatures & CPU_AES) != 0; }
   static bool supports_erms()     { return (_cpuFeatures & CPU_ERMS) != 0; }
   static bool supports_clmul()    { return (_cpuFeatures & CPU_CLMUL) != 0; }
-
+  static bool supports_bmi1()     { return (_cpuFeatures & CPU_BMI1) != 0; }
+  static bool supports_bmi2()     { return (_cpuFeatures & CPU_BMI2) != 0; }
   // Intel features
   static bool is_intel_family_core() { return is_intel() &&
                                        extended_cpu_family() == CPU_FAMILY_INTEL_CORE; }
--- a/hotspot/src/cpu/x86/vm/x86_32.ad	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/x86_32.ad	Wed Jul 05 19:33:51 2017 +0200
@@ -5163,6 +5163,19 @@
 %}
 
 instruct countTrailingZerosI(rRegI dst, rRegI src, eFlagsReg cr) %{
+  predicate(UseCountTrailingZerosInstruction);
+  match(Set dst (CountTrailingZerosI src));
+  effect(KILL cr);
+
+  format %{ "TZCNT    $dst, $src\t# count trailing zeros (int)" %}
+  ins_encode %{
+    __ tzcntl($dst$$Register, $src$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+instruct countTrailingZerosI_bsf(rRegI dst, rRegI src, eFlagsReg cr) %{
+  predicate(!UseCountTrailingZerosInstruction);
   match(Set dst (CountTrailingZerosI src));
   effect(KILL cr);
 
@@ -5182,6 +5195,30 @@
 %}
 
 instruct countTrailingZerosL(rRegI dst, eRegL src, eFlagsReg cr) %{
+  predicate(UseCountTrailingZerosInstruction);
+  match(Set dst (CountTrailingZerosL src));
+  effect(TEMP dst, KILL cr);
+
+  format %{ "TZCNT  $dst, $src.lo\t# count trailing zeros (long) \n\t"
+            "JNC    done\n\t"
+            "TZCNT  $dst, $src.hi\n\t"
+            "ADD    $dst, 32\n"
+            "done:" %}
+  ins_encode %{
+    Register Rdst = $dst$$Register;
+    Register Rsrc = $src$$Register;
+    Label done;
+    __ tzcntl(Rdst, Rsrc);
+    __ jccb(Assembler::carryClear, done);
+    __ tzcntl(Rdst, HIGH_FROM_LOW(Rsrc));
+    __ addl(Rdst, BitsPerInt);
+    __ bind(done);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+instruct countTrailingZerosL_bsf(rRegI dst, eRegL src, eFlagsReg cr) %{
+  predicate(!UseCountTrailingZerosInstruction);
   match(Set dst (CountTrailingZerosL src));
   effect(TEMP dst, KILL cr);
 
@@ -8027,6 +8064,123 @@
   ins_pipe( ialu_mem_imm );
 %}
 
+// BMI1 instructions
+instruct andnI_rReg_rReg_rReg(rRegI dst, rRegI src1, rRegI src2, immI_M1 minus_1, eFlagsReg cr) %{
+  match(Set dst (AndI (XorI src1 minus_1) src2));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  format %{ "ANDNL  $dst, $src1, $src2" %}
+
+  ins_encode %{
+    __ andnl($dst$$Register, $src1$$Register, $src2$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+instruct andnI_rReg_rReg_mem(rRegI dst, rRegI src1, memory src2, immI_M1 minus_1, eFlagsReg cr) %{
+  match(Set dst (AndI (XorI src1 minus_1) (LoadI src2) ));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  ins_cost(125);
+  format %{ "ANDNL  $dst, $src1, $src2" %}
+
+  ins_encode %{
+    __ andnl($dst$$Register, $src1$$Register, $src2$$Address);
+  %}
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct blsiI_rReg_rReg(rRegI dst, rRegI src, immI0 imm_zero, eFlagsReg cr) %{
+  match(Set dst (AndI (SubI imm_zero src) src));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  format %{ "BLSIL  $dst, $src" %}
+
+  ins_encode %{
+    __ blsil($dst$$Register, $src$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+instruct blsiI_rReg_mem(rRegI dst, memory src, immI0 imm_zero, eFlagsReg cr) %{
+  match(Set dst (AndI (SubI imm_zero (LoadI src) ) (LoadI src) ));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  ins_cost(125);
+  format %{ "BLSIL  $dst, $src" %}
+
+  ins_encode %{
+    __ blsil($dst$$Register, $src$$Address);
+  %}
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct blsmskI_rReg_rReg(rRegI dst, rRegI src, immI_M1 minus_1, eFlagsReg cr)
+%{
+  match(Set dst (XorI (AddI src minus_1) src));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  format %{ "BLSMSKL $dst, $src" %}
+
+  ins_encode %{
+    __ blsmskl($dst$$Register, $src$$Register);
+  %}
+
+  ins_pipe(ialu_reg);
+%}
+
+instruct blsmskI_rReg_mem(rRegI dst, memory src, immI_M1 minus_1, eFlagsReg cr)
+%{
+  match(Set dst (XorI (AddI (LoadI src) minus_1) (LoadI src) ));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  ins_cost(125);
+  format %{ "BLSMSKL $dst, $src" %}
+
+  ins_encode %{
+    __ blsmskl($dst$$Register, $src$$Address);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct blsrI_rReg_rReg(rRegI dst, rRegI src, immI_M1 minus_1, eFlagsReg cr)
+%{
+  match(Set dst (AndI (AddI src minus_1) src) );
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  format %{ "BLSRL  $dst, $src" %}
+
+  ins_encode %{
+    __ blsrl($dst$$Register, $src$$Register);
+  %}
+
+  ins_pipe(ialu_reg);
+%}
+
+instruct blsrI_rReg_mem(rRegI dst, memory src, immI_M1 minus_1, eFlagsReg cr)
+%{
+  match(Set dst (AndI (AddI (LoadI src) minus_1) (LoadI src) ));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  ins_cost(125);
+  format %{ "BLSRL  $dst, $src" %}
+
+  ins_encode %{
+    __ blsrl($dst$$Register, $src$$Address);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
 // Or Instructions
 // Or Register with Register
 instruct orI_eReg(rRegI dst, rRegI src, eFlagsReg cr) %{
@@ -8649,6 +8803,210 @@
   ins_pipe( ialu_reg_long_mem );
 %}
 
+// BMI1 instructions
+instruct andnL_eReg_eReg_eReg(eRegL dst, eRegL src1, eRegL src2, immL_M1 minus_1, eFlagsReg cr) %{
+  match(Set dst (AndL (XorL src1 minus_1) src2));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr, TEMP dst);
+
+  format %{ "ANDNL  $dst.lo, $src1.lo, $src2.lo\n\t"
+            "ANDNL  $dst.hi, $src1.hi, $src2.hi"
+         %}
+
+  ins_encode %{
+    Register Rdst = $dst$$Register;
+    Register Rsrc1 = $src1$$Register;
+    Register Rsrc2 = $src2$$Register;
+    __ andnl(Rdst, Rsrc1, Rsrc2);
+    __ andnl(HIGH_FROM_LOW(Rdst), HIGH_FROM_LOW(Rsrc1), HIGH_FROM_LOW(Rsrc2));
+  %}
+  ins_pipe(ialu_reg_reg_long);
+%}
+
+instruct andnL_eReg_eReg_mem(eRegL dst, eRegL src1, memory src2, immL_M1 minus_1, eFlagsReg cr) %{
+  match(Set dst (AndL (XorL src1 minus_1) (LoadL src2) ));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr, TEMP dst);
+
+  ins_cost(125);
+  format %{ "ANDNL  $dst.lo, $src1.lo, $src2\n\t"
+            "ANDNL  $dst.hi, $src1.hi, $src2+4"
+         %}
+
+  ins_encode %{
+    Register Rdst = $dst$$Register;
+    Register Rsrc1 = $src1$$Register;
+    Address src2_hi = Address::make_raw($src2$$base, $src2$$index, $src2$$scale, $src2$$disp + 4, relocInfo::none);
+
+    __ andnl(Rdst, Rsrc1, $src2$$Address);
+    __ andnl(HIGH_FROM_LOW(Rdst), HIGH_FROM_LOW(Rsrc1), src2_hi);
+  %}
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct blsiL_eReg_eReg(eRegL dst, eRegL src, immL0 imm_zero, eFlagsReg cr) %{
+  match(Set dst (AndL (SubL imm_zero src) src));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr, TEMP dst);
+
+  format %{ "MOVL   $dst.hi, 0\n\t"
+            "BLSIL  $dst.lo, $src.lo\n\t"
+            "JNZ    done\n\t"
+            "BLSIL  $dst.hi, $src.hi\n"
+            "done:"
+         %}
+
+  ins_encode %{
+    Label done;
+    Register Rdst = $dst$$Register;
+    Register Rsrc = $src$$Register;
+    __ movl(HIGH_FROM_LOW(Rdst), 0);
+    __ blsil(Rdst, Rsrc);
+    __ jccb(Assembler::notZero, done);
+    __ blsil(HIGH_FROM_LOW(Rdst), HIGH_FROM_LOW(Rsrc));
+    __ bind(done);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+instruct blsiL_eReg_mem(eRegL dst, memory src, immL0 imm_zero, eFlagsReg cr) %{
+  match(Set dst (AndL (SubL imm_zero (LoadL src) ) (LoadL src) ));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr, TEMP dst);
+
+  ins_cost(125);
+  format %{ "MOVL   $dst.hi, 0\n\t"
+            "BLSIL  $dst.lo, $src\n\t"
+            "JNZ    done\n\t"
+            "BLSIL  $dst.hi, $src+4\n"
+            "done:"
+         %}
+
+  ins_encode %{
+    Label done;
+    Register Rdst = $dst$$Register;
+    Address src_hi = Address::make_raw($src$$base, $src$$index, $src$$scale, $src$$disp + 4, relocInfo::none);
+
+    __ movl(HIGH_FROM_LOW(Rdst), 0);
+    __ blsil(Rdst, $src$$Address);
+    __ jccb(Assembler::notZero, done);
+    __ blsil(HIGH_FROM_LOW(Rdst), src_hi);
+    __ bind(done);
+  %}
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct blsmskL_eReg_eReg(eRegL dst, eRegL src, immL_M1 minus_1, eFlagsReg cr)
+%{
+  match(Set dst (XorL (AddL src minus_1) src));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr, TEMP dst);
+
+  format %{ "MOVL    $dst.hi, 0\n\t"
+            "BLSMSKL $dst.lo, $src.lo\n\t"
+            "JNC     done\n\t"
+            "BLSMSKL $dst.hi, $src.hi\n"
+            "done:"
+         %}
+
+  ins_encode %{
+    Label done;
+    Register Rdst = $dst$$Register;
+    Register Rsrc = $src$$Register;
+    __ movl(HIGH_FROM_LOW(Rdst), 0);
+    __ blsmskl(Rdst, Rsrc);
+    __ jccb(Assembler::carryClear, done);
+    __ blsmskl(HIGH_FROM_LOW(Rdst), HIGH_FROM_LOW(Rsrc));
+    __ bind(done);
+  %}
+
+  ins_pipe(ialu_reg);
+%}
+
+instruct blsmskL_eReg_mem(eRegL dst, memory src, immL_M1 minus_1, eFlagsReg cr)
+%{
+  match(Set dst (XorL (AddL (LoadL src) minus_1) (LoadL src) ));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr, TEMP dst);
+
+  ins_cost(125);
+  format %{ "MOVL    $dst.hi, 0\n\t"
+            "BLSMSKL $dst.lo, $src\n\t"
+            "JNC     done\n\t"
+            "BLSMSKL $dst.hi, $src+4\n"
+            "done:"
+         %}
+
+  ins_encode %{
+    Label done;
+    Register Rdst = $dst$$Register;
+    Address src_hi = Address::make_raw($src$$base, $src$$index, $src$$scale, $src$$disp + 4, relocInfo::none);
+
+    __ movl(HIGH_FROM_LOW(Rdst), 0);
+    __ blsmskl(Rdst, $src$$Address);
+    __ jccb(Assembler::carryClear, done);
+    __ blsmskl(HIGH_FROM_LOW(Rdst), src_hi);
+    __ bind(done);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct blsrL_eReg_eReg(eRegL dst, eRegL src, immL_M1 minus_1, eFlagsReg cr)
+%{
+  match(Set dst (AndL (AddL src minus_1) src) );
+  predicate(UseBMI1Instructions);
+  effect(KILL cr, TEMP dst);
+
+  format %{ "MOVL   $dst.hi, $src.hi\n\t"
+            "BLSRL  $dst.lo, $src.lo\n\t"
+            "JNC    done\n\t"
+            "BLSRL  $dst.hi, $src.hi\n"
+            "done:"
+  %}
+
+  ins_encode %{
+    Label done;
+    Register Rdst = $dst$$Register;
+    Register Rsrc = $src$$Register;
+    __ movl(HIGH_FROM_LOW(Rdst), HIGH_FROM_LOW(Rsrc));
+    __ blsrl(Rdst, Rsrc);
+    __ jccb(Assembler::carryClear, done);
+    __ blsrl(HIGH_FROM_LOW(Rdst), HIGH_FROM_LOW(Rsrc));
+    __ bind(done);
+  %}
+
+  ins_pipe(ialu_reg);
+%}
+
+instruct blsrL_eReg_mem(eRegL dst, memory src, immL_M1 minus_1, eFlagsReg cr)
+%{
+  match(Set dst (AndL (AddL (LoadL src) minus_1) (LoadL src) ));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr, TEMP dst);
+
+  ins_cost(125);
+  format %{ "MOVL   $dst.hi, $src+4\n\t"
+            "BLSRL  $dst.lo, $src\n\t"
+            "JNC    done\n\t"
+            "BLSRL  $dst.hi, $src+4\n"
+            "done:"
+  %}
+
+  ins_encode %{
+    Label done;
+    Register Rdst = $dst$$Register;
+    Address src_hi = Address::make_raw($src$$base, $src$$index, $src$$scale, $src$$disp + 4, relocInfo::none);
+    __ movl(HIGH_FROM_LOW(Rdst), src_hi);
+    __ blsrl(Rdst, $src$$Address);
+    __ jccb(Assembler::carryClear, done);
+    __ blsrl(HIGH_FROM_LOW(Rdst), src_hi);
+    __ bind(done);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
 // Or Long Register with Register
 instruct orl_eReg(eRegL dst, eRegL src, eFlagsReg cr) %{
   match(Set dst (OrL dst src));
--- a/hotspot/src/cpu/x86/vm/x86_64.ad	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/cpu/x86/vm/x86_64.ad	Wed Jul 05 19:33:51 2017 +0200
@@ -6022,6 +6022,19 @@
 %}
 
 instruct countTrailingZerosI(rRegI dst, rRegI src, rFlagsReg cr) %{
+  predicate(UseCountTrailingZerosInstruction);
+  match(Set dst (CountTrailingZerosI src));
+  effect(KILL cr);
+
+  format %{ "tzcntl    $dst, $src\t# count trailing zeros (int)" %}
+  ins_encode %{
+    __ tzcntl($dst$$Register, $src$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+instruct countTrailingZerosI_bsf(rRegI dst, rRegI src, rFlagsReg cr) %{
+  predicate(!UseCountTrailingZerosInstruction);
   match(Set dst (CountTrailingZerosI src));
   effect(KILL cr);
 
@@ -6041,6 +6054,19 @@
 %}
 
 instruct countTrailingZerosL(rRegI dst, rRegL src, rFlagsReg cr) %{
+  predicate(UseCountTrailingZerosInstruction);
+  match(Set dst (CountTrailingZerosL src));
+  effect(KILL cr);
+
+  format %{ "tzcntq    $dst, $src\t# count trailing zeros (long)" %}
+  ins_encode %{
+    __ tzcntq($dst$$Register, $src$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+instruct countTrailingZerosL_bsf(rRegI dst, rRegL src, rFlagsReg cr) %{
+  predicate(!UseCountTrailingZerosInstruction);
   match(Set dst (CountTrailingZerosL src));
   effect(KILL cr);
 
@@ -8622,6 +8648,122 @@
   ins_pipe(ialu_mem_imm);
 %}
 
+// BMI1 instructions
+instruct andnI_rReg_rReg_mem(rRegI dst, rRegI src1, memory src2, immI_M1 minus_1, rFlagsReg cr) %{
+  match(Set dst (AndI (XorI src1 minus_1) (LoadI src2)));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  ins_cost(125);
+  format %{ "andnl  $dst, $src1, $src2" %}
+
+  ins_encode %{
+    __ andnl($dst$$Register, $src1$$Register, $src2$$Address);
+  %}
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct andnI_rReg_rReg_rReg(rRegI dst, rRegI src1, rRegI src2, immI_M1 minus_1, rFlagsReg cr) %{
+  match(Set dst (AndI (XorI src1 minus_1) src2));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  format %{ "andnl  $dst, $src1, $src2" %}
+
+  ins_encode %{
+    __ andnl($dst$$Register, $src1$$Register, $src2$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+instruct blsiI_rReg_rReg(rRegI dst, rRegI src, immI0 imm_zero, rFlagsReg cr) %{
+  match(Set dst (AndI (SubI imm_zero src) src));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  format %{ "blsil  $dst, $src" %}
+
+  ins_encode %{
+    __ blsil($dst$$Register, $src$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+instruct blsiI_rReg_mem(rRegI dst, memory src, immI0 imm_zero, rFlagsReg cr) %{
+  match(Set dst (AndI (SubI imm_zero (LoadI src) ) (LoadI src) ));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  ins_cost(125);
+  format %{ "blsil  $dst, $src" %}
+
+  ins_encode %{
+    __ blsil($dst$$Register, $src$$Address);
+  %}
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct blsmskI_rReg_mem(rRegI dst, memory src, immI_M1 minus_1, rFlagsReg cr)
+%{
+  match(Set dst (XorI (AddI (LoadI src) minus_1) (LoadI src) ) );
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  ins_cost(125);
+  format %{ "blsmskl $dst, $src" %}
+
+  ins_encode %{
+    __ blsmskl($dst$$Register, $src$$Address);
+  %}
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct blsmskI_rReg_rReg(rRegI dst, rRegI src, immI_M1 minus_1, rFlagsReg cr)
+%{
+  match(Set dst (XorI (AddI src minus_1) src));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  format %{ "blsmskl $dst, $src" %}
+
+  ins_encode %{
+    __ blsmskl($dst$$Register, $src$$Register);
+  %}
+
+  ins_pipe(ialu_reg);
+%}
+
+instruct blsrI_rReg_rReg(rRegI dst, rRegI src, immI_M1 minus_1, rFlagsReg cr)
+%{
+  match(Set dst (AndI (AddI src minus_1) src) );
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  format %{ "blsrl  $dst, $src" %}
+
+  ins_encode %{
+    __ blsrl($dst$$Register, $src$$Register);
+  %}
+
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct blsrI_rReg_mem(rRegI dst, memory src, immI_M1 minus_1, rFlagsReg cr)
+%{
+  match(Set dst (AndI (AddI (LoadI src) minus_1) (LoadI src) ) );
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  ins_cost(125);
+  format %{ "blsrl  $dst, $src" %}
+
+  ins_encode %{
+    __ blsrl($dst$$Register, $src$$Address);
+  %}
+
+  ins_pipe(ialu_reg);
+%}
+
 // Or Instructions
 // Or Register with Register
 instruct orI_rReg(rRegI dst, rRegI src, rFlagsReg cr)
@@ -8853,6 +8995,122 @@
   ins_pipe(ialu_mem_imm);
 %}
 
+// BMI1 instructions
+instruct andnL_rReg_rReg_mem(rRegL dst, rRegL src1, memory src2, immL_M1 minus_1, rFlagsReg cr) %{
+  match(Set dst (AndL (XorL src1 minus_1) (LoadL src2)));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  ins_cost(125);
+  format %{ "andnq  $dst, $src1, $src2" %}
+
+  ins_encode %{
+    __ andnq($dst$$Register, $src1$$Register, $src2$$Address);
+  %}
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct andnL_rReg_rReg_rReg(rRegL dst, rRegL src1, rRegL src2, immL_M1 minus_1, rFlagsReg cr) %{
+  match(Set dst (AndL (XorL src1 minus_1) src2));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  format %{ "andnq  $dst, $src1, $src2" %}
+
+  ins_encode %{
+  __ andnq($dst$$Register, $src1$$Register, $src2$$Register);
+  %}
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct blsiL_rReg_rReg(rRegL dst, rRegL src, immL0 imm_zero, rFlagsReg cr) %{
+  match(Set dst (AndL (SubL imm_zero src) src));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  format %{ "blsiq  $dst, $src" %}
+
+  ins_encode %{
+    __ blsiq($dst$$Register, $src$$Register);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+instruct blsiL_rReg_mem(rRegL dst, memory src, immL0 imm_zero, rFlagsReg cr) %{
+  match(Set dst (AndL (SubL imm_zero (LoadL src) ) (LoadL src) ));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  ins_cost(125);
+  format %{ "blsiq  $dst, $src" %}
+
+  ins_encode %{
+    __ blsiq($dst$$Register, $src$$Address);
+  %}
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct blsmskL_rReg_mem(rRegL dst, memory src, immL_M1 minus_1, rFlagsReg cr)
+%{
+  match(Set dst (XorL (AddL (LoadL src) minus_1) (LoadL src) ) );
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  ins_cost(125);
+  format %{ "blsmskq $dst, $src" %}
+
+  ins_encode %{
+    __ blsmskq($dst$$Register, $src$$Address);
+  %}
+  ins_pipe(ialu_reg_mem);
+%}
+
+instruct blsmskL_rReg_rReg(rRegL dst, rRegL src, immL_M1 minus_1, rFlagsReg cr)
+%{
+  match(Set dst (XorL (AddL src minus_1) src));
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  format %{ "blsmskq $dst, $src" %}
+
+  ins_encode %{
+    __ blsmskq($dst$$Register, $src$$Register);
+  %}
+
+  ins_pipe(ialu_reg);
+%}
+
+instruct blsrL_rReg_rReg(rRegL dst, rRegL src, immL_M1 minus_1, rFlagsReg cr)
+%{
+  match(Set dst (AndL (AddL src minus_1) src) );
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  format %{ "blsrq  $dst, $src" %}
+
+  ins_encode %{
+    __ blsrq($dst$$Register, $src$$Register);
+  %}
+
+  ins_pipe(ialu_reg);
+%}
+
+instruct blsrL_rReg_mem(rRegL dst, memory src, immL_M1 minus_1, rFlagsReg cr)
+%{
+  match(Set dst (AndL (AddL (LoadL src) minus_1) (LoadL src)) );
+  predicate(UseBMI1Instructions);
+  effect(KILL cr);
+
+  ins_cost(125);
+  format %{ "blsrq  $dst, $src" %}
+
+  ins_encode %{
+    __ blsrq($dst$$Register, $src$$Address);
+  %}
+
+  ins_pipe(ialu_reg);
+%}
+
 // Or Instructions
 // Or Register with Register
 instruct orL_rReg(rRegL dst, rRegL src, rFlagsReg cr)
--- a/hotspot/src/os/aix/vm/os_aix.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/os/aix/vm/os_aix.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1135,15 +1135,10 @@
 }
 
 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) {
-  {
-    // gettimeofday - based on time in seconds since the Epoch thus does not wrap
-    info_ptr->max_value = ALL_64_BITS;
-
-    // gettimeofday is a real time clock so it skips
-    info_ptr->may_skip_backward = true;
-    info_ptr->may_skip_forward = true;
-  }
-
+  info_ptr->max_value = ALL_64_BITS;
+  // mread_real_time() is monotonic (see 'os::javaTimeNanos()')
+  info_ptr->may_skip_backward = false;
+  info_ptr->may_skip_forward = false;
   info_ptr->kind = JVMTI_TIMER_ELAPSED;    // elapsed not CPU time
 }
 
@@ -2799,105 +2794,6 @@
   return ::read(fd, buf, nBytes);
 }
 
-#define NANOSECS_PER_MILLISEC 1000000
-
-int os::sleep(Thread* thread, jlong millis, bool interruptible) {
-  assert(thread == Thread::current(), "thread consistency check");
-
-  // Prevent nasty overflow in deadline calculation
-  // by handling long sleeps similar to solaris or windows.
-  const jlong limit = INT_MAX;
-  int result;
-  while (millis > limit) {
-    if ((result = os::sleep(thread, limit, interruptible)) != OS_OK) {
-      return result;
-    }
-    millis -= limit;
-  }
-
-  ParkEvent * const slp = thread->_SleepEvent;
-  slp->reset();
-  OrderAccess::fence();
-
-  if (interruptible) {
-    jlong prevtime = javaTimeNanos();
-
-    // Prevent precision loss and too long sleeps
-    jlong deadline = prevtime + millis * NANOSECS_PER_MILLISEC;
-
-    for (;;) {
-      if (os::is_interrupted(thread, true)) {
-        return OS_INTRPT;
-      }
-
-      jlong newtime = javaTimeNanos();
-
-      assert(newtime >= prevtime, "time moving backwards");
-      // Doing prevtime and newtime in microseconds doesn't help precision,
-      // and trying to round up to avoid lost milliseconds can result in a
-      // too-short delay.
-      millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
-
-      if (millis <= 0) {
-        return OS_OK;
-      }
-
-      // Stop sleeping if we passed the deadline
-      if (newtime >= deadline) {
-        return OS_OK;
-      }
-
-      prevtime = newtime;
-
-      {
-        assert(thread->is_Java_thread(), "sanity check");
-        JavaThread *jt = (JavaThread *) thread;
-        ThreadBlockInVM tbivm(jt);
-        OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */);
-
-        jt->set_suspend_equivalent();
-
-        slp->park(millis);
-
-        // were we externally suspended while we were waiting?
-        jt->check_and_wait_while_suspended();
-      }
-    }
-  } else {
-    OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
-    jlong prevtime = javaTimeNanos();
-
-    // Prevent precision loss and too long sleeps
-    jlong deadline = prevtime + millis * NANOSECS_PER_MILLISEC;
-
-    for (;;) {
-      // It'd be nice to avoid the back-to-back javaTimeNanos() calls on
-      // the 1st iteration ...
-      jlong newtime = javaTimeNanos();
-
-      if (newtime - prevtime < 0) {
-        // time moving backwards, should only happen if no monotonic clock
-        // not a guarantee() because JVM should not abort on kernel/glibc bugs
-        // - HS14 Commented out as not implemented.
-        // - TODO Maybe we should implement it?
-        //assert(!Aix::supports_monotonic_clock(), "time moving backwards");
-      } else {
-        millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
-      }
-
-      if (millis <= 0) break;
-
-      if (newtime >= deadline) {
-        break;
-      }
-
-      prevtime = newtime;
-      slp->park(millis);
-    }
-    return OS_OK;
-  }
-}
-
 void os::naked_short_sleep(jlong ms) {
   struct timespec req;
 
@@ -3246,50 +3142,6 @@
   guarantee(osthread->sr.is_running(), "Must be running!");
 }
 
-////////////////////////////////////////////////////////////////////////////////
-// interrupt support
-
-void os::interrupt(Thread* thread) {
-  assert(Thread::current() == thread || Threads_lock->owned_by_self(),
-    "possibility of dangling Thread pointer");
-
-  OSThread* osthread = thread->osthread();
-
-  if (!osthread->interrupted()) {
-    osthread->set_interrupted(true);
-    // More than one thread can get here with the same value of osthread,
-    // resulting in multiple notifications.  We do, however, want the store
-    // to interrupted() to be visible to other threads before we execute unpark().
-    OrderAccess::fence();
-    ParkEvent * const slp = thread->_SleepEvent;
-    if (slp != NULL) slp->unpark();
-  }
-
-  // For JSR166. Unpark even if interrupt status already was set
-  if (thread->is_Java_thread())
-    ((JavaThread*)thread)->parker()->unpark();
-
-  ParkEvent * ev = thread->_ParkEvent;
-  if (ev != NULL) ev->unpark();
-
-}
-
-bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
-  assert(Thread::current() == thread || Threads_lock->owned_by_self(),
-    "possibility of dangling Thread pointer");
-
-  OSThread* osthread = thread->osthread();
-
-  bool interrupted = osthread->interrupted();
-
-  if (interrupted && clear_interrupted) {
-    osthread->set_interrupted(false);
-    // consider thread->_SleepEvent->reset() ... optional optimization
-  }
-
-  return interrupted;
-}
-
 ///////////////////////////////////////////////////////////////////////////////////
 // signal handling (except suspend/resume)
 
--- a/hotspot/src/os/aix/vm/os_aix.inline.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/os/aix/vm/os_aix.inline.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -283,4 +283,10 @@
                             const char* optval, socklen_t optlen) {
   return ::setsockopt(fd, level, optname, optval, optlen);
 }
+
+inline bool os::supports_monotonic_clock() {
+  // mread_real_time() is monotonic on AIX (see os::javaTimeNanos() comments)
+  return true;
+}
+
 #endif // OS_AIX_VM_OS_AIX_INLINE_HPP
--- a/hotspot/src/os/linux/vm/os_linux.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/os/linux/vm/os_linux.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -5284,7 +5284,6 @@
 
 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
   static bool proc_task_unchecked = true;
-  static const char *proc_stat_path = "/proc/%d/stat";
   pid_t  tid = thread->osthread()->thread_id();
   char *s;
   char stat[2048];
@@ -5297,6 +5296,8 @@
   long ldummy;
   FILE *fp;
 
+  snprintf(proc_name, 64, "/proc/%d/stat", tid);
+
   // 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.
@@ -5308,12 +5309,11 @@
     proc_task_unchecked = false;
     fp = fopen("/proc/self/task", "r");
     if (fp != NULL) {
-      proc_stat_path = "/proc/self/task/%d/stat";
+      snprintf(proc_name, 64, "/proc/self/task/%d/stat", tid);
       fclose(fp);
     }
   }
 
-  sprintf(proc_name, proc_stat_path, tid);
   fp = fopen(proc_name, "r");
   if ( fp == NULL ) return -1;
   statlen = fread(stat, 1, 2047, fp);
--- a/hotspot/src/os/windows/vm/os_windows.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/os/windows/vm/os_windows.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -3619,13 +3619,14 @@
          "possibility of dangling Thread pointer");
 
   OSThread* osthread = thread->osthread();
-  bool interrupted = osthread->interrupted();
   // There is no synchronization between the setting of the interrupt
   // and it being cleared here. It is critical - see 6535709 - that
   // we only clear the interrupt state, and reset the interrupt event,
   // if we are going to report that we were indeed interrupted - else
   // an interrupt can be "lost", leading to spurious wakeups or lost wakeups
-  // depending on the timing
+  // depending on the timing. By checking thread interrupt event to see
+  // if the thread gets real interrupt thus prevent spurious wakeup.
+  bool interrupted = osthread->interrupted() && (WaitForSingleObject(osthread->interrupt_event(), 0) == WAIT_OBJECT_0);
   if (interrupted && clear_interrupted) {
     osthread->set_interrupted(false);
     ResetEvent(osthread->interrupt_event());
--- a/hotspot/src/share/vm/adlc/formssel.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/adlc/formssel.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -660,6 +660,7 @@
   int USE_of_memory  = 0;
   int DEF_of_memory  = 0;
   const char*    last_memory_DEF = NULL; // to test DEF/USE pairing in asserts
+  const char*    last_memory_USE = NULL;
   Component     *unique          = NULL;
   Component     *comp            = NULL;
   ComponentList &components      = (ComponentList &)_components;
@@ -681,7 +682,16 @@
           assert(0 == strcmp(last_memory_DEF, comp->_name), "every memory DEF is followed by a USE of the same name");
           last_memory_DEF = NULL;
         }
-        USE_of_memory++;
+        // Handles same memory being used multiple times in the case of BMI1 instructions.
+        if (last_memory_USE != NULL) {
+          if (strcmp(comp->_name, last_memory_USE) != 0) {
+            USE_of_memory++;
+          }
+        } else {
+          USE_of_memory++;
+        }
+        last_memory_USE = comp->_name;
+
         if (DEF_of_memory == 0)  // defs take precedence
           unique = comp;
       } else {
--- a/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1436,7 +1436,7 @@
 
   bool need_mem_bar = false;
   if (method()->name() == ciSymbol::object_initializer_name() &&
-      scope()->wrote_final()) {
+      (scope()->wrote_final() || (AlwaysSafeConstructors && scope()->wrote_fields()))) {
     need_mem_bar = true;
   }
 
@@ -1550,6 +1550,10 @@
     scope()->set_wrote_final();
   }
 
+  if (code == Bytecodes::_putfield) {
+    scope()->set_wrote_fields();
+  }
+
   const int offset = !needs_patching ? field->offset() : -1;
   switch (code) {
     case Bytecodes::_getstatic: {
@@ -3767,11 +3771,14 @@
   }
 
   // now perform tests that are based on flag settings
-  if (callee->force_inline()) {
-    if (inline_level() > MaxForceInlineLevel) INLINE_BAILOUT("MaxForceInlineLevel");
-    print_inlining(callee, "force inline by annotation");
-  } else if (callee->should_inline()) {
-    print_inlining(callee, "force inline by CompileOracle");
+  if (callee->force_inline() || callee->should_inline()) {
+    if (inline_level() > MaxForceInlineLevel                    ) INLINE_BAILOUT("MaxForceInlineLevel");
+    if (recursive_inline_level(callee) > MaxRecursiveInlineLevel) INLINE_BAILOUT("recursive inlining too deep");
+
+    const char* msg = "";
+    if (callee->force_inline())  msg = "force inline by annotation";
+    if (callee->should_inline()) msg = "force inline by CompileOracle";
+    print_inlining(callee, msg);
   } else {
     // use heuristic controls on inlining
     if (inline_level() > MaxInlineLevel                         ) INLINE_BAILOUT("inlining too deep");
--- a/hotspot/src/share/vm/c1/c1_IR.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/c1/c1_IR.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -142,6 +142,7 @@
   _number_of_locks    = 0;
   _monitor_pairing_ok = method->has_balanced_monitors();
   _wrote_final        = false;
+  _wrote_fields       = false;
   _start              = NULL;
 
   if (osr_bci == -1) {
--- a/hotspot/src/share/vm/c1/c1_IR.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/c1/c1_IR.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -150,6 +150,7 @@
   int           _number_of_locks;                // the number of monitor lock slots needed
   bool          _monitor_pairing_ok;             // the monitor pairing info
   bool          _wrote_final;                    // has written final field
+  bool          _wrote_fields;                   // has written fields
   BlockBegin*   _start;                          // the start block, successsors are method entries
 
   BitMap        _requires_phi_function;          // bit is set if phi functions at loop headers are necessary for a local variable
@@ -184,6 +185,9 @@
   BlockBegin*   start() const                    { return _start; }
   void          set_wrote_final()                { _wrote_final = true; }
   bool          wrote_final    () const          { return _wrote_final; }
+  void          set_wrote_fields()               { _wrote_fields = true; }
+  bool          wrote_fields    () const         { return _wrote_fields; }
+
 };
 
 
--- a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1734,7 +1734,8 @@
                 (info ? new CodeEmitInfo(info) : NULL));
   }
 
-  if (is_volatile && !needs_patching) {
+  bool needs_atomic_access = is_volatile || AlwaysAtomicAccesses;
+  if (needs_atomic_access && !needs_patching) {
     volatile_field_store(value.result(), address, info);
   } else {
     LIR_PatchCode patch_code = needs_patching ? lir_patch_normal : lir_patch_none;
@@ -1807,7 +1808,8 @@
     address = generate_address(object.result(), x->offset(), field_type);
   }
 
-  if (is_volatile && !needs_patching) {
+  bool needs_atomic_access = is_volatile || AlwaysAtomicAccesses;
+  if (needs_atomic_access && !needs_patching) {
     volatile_field_load(address, reg, info);
   } else {
     LIR_PatchCode patch_code = needs_patching ? lir_patch_normal : lir_patch_none;
--- a/hotspot/src/share/vm/c1/c1_Runtime1.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/c1/c1_Runtime1.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -809,11 +809,10 @@
   int bci = vfst.bci();
   Bytecodes::Code code = caller_method()->java_code_at(bci);
 
-#ifndef PRODUCT
   // this is used by assertions in the access_field_patching_id
   BasicType patch_field_type = T_ILLEGAL;
-#endif // PRODUCT
   bool deoptimize_for_volatile = false;
+  bool deoptimize_for_atomic = false;
   int patch_field_offset = -1;
   KlassHandle init_klass(THREAD, NULL); // klass needed by load_klass_patching code
   KlassHandle load_klass(THREAD, NULL); // klass needed by load_klass_patching code
@@ -839,11 +838,24 @@
     // is the path for patching field offsets.  load_klass is only
     // used for patching references to oops which don't need special
     // handling in the volatile case.
+
     deoptimize_for_volatile = result.access_flags().is_volatile();
 
-#ifndef PRODUCT
+    // If we are patching a field which should be atomic, then
+    // the generated code is not correct either, force deoptimizing.
+    // We need to only cover T_LONG and T_DOUBLE fields, as we can
+    // break access atomicity only for them.
+
+    // Strictly speaking, the deoptimizaation on 64-bit platforms
+    // is unnecessary, and T_LONG stores on 32-bit platforms need
+    // to be handled by special patching code when AlwaysAtomicAccesses
+    // becomes product feature. At this point, we are still going
+    // for the deoptimization for consistency against volatile
+    // accesses.
+
     patch_field_type = result.field_type();
-#endif
+    deoptimize_for_atomic = (AlwaysAtomicAccesses && (patch_field_type == T_DOUBLE || patch_field_type == T_LONG));
+
   } else if (load_klass_or_mirror_patch_id) {
     Klass* k = NULL;
     switch (code) {
@@ -918,13 +930,19 @@
     ShouldNotReachHere();
   }
 
-  if (deoptimize_for_volatile) {
-    // At compile time we assumed the field wasn't volatile but after
-    // loading it turns out it was volatile so we have to throw the
+  if (deoptimize_for_volatile || deoptimize_for_atomic) {
+    // At compile time we assumed the field wasn't volatile/atomic but after
+    // loading it turns out it was volatile/atomic so we have to throw the
     // compiled code out and let it be regenerated.
     if (TracePatching) {
-      tty->print_cr("Deoptimizing for patching volatile field reference");
+      if (deoptimize_for_volatile) {
+        tty->print_cr("Deoptimizing for patching volatile field reference");
+      }
+      if (deoptimize_for_atomic) {
+        tty->print_cr("Deoptimizing for patching atomic field reference");
+      }
     }
+
     // It's possible the nmethod was invalidated in the last
     // safepoint, but if it's still alive then make it not_entrant.
     nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
--- a/hotspot/src/share/vm/ci/ciMethod.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/ci/ciMethod.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -724,6 +724,11 @@
 
   VM_ENTRY_MARK;
 
+  // Disable CHA for default methods for now
+  if (root_m->get_Method()->is_default_method()) {
+    return NULL;
+  }
+
   methodHandle target;
   {
     MutexLocker locker(Compile_lock);
--- a/hotspot/src/share/vm/ci/ciMethodData.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/ci/ciMethodData.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -87,8 +87,9 @@
   DataLayout* dp_dst  = extra_data_base();
   for (;; dp_src = MethodData::next_extra(dp_src), dp_dst = MethodData::next_extra(dp_dst)) {
     assert(dp_src < end_src, "moved past end of extra data");
-    assert(dp_src->tag() == dp_dst->tag(), err_msg("should be same tags %d != %d", dp_src->tag(), dp_dst->tag()));
-    switch(dp_src->tag()) {
+    // New traps in the MDO can be added as we translate the copy so
+    // look at the entries in the copy.
+    switch(dp_dst->tag()) {
     case DataLayout::speculative_trap_data_tag: {
       ciSpeculativeTrapData* data_dst = new ciSpeculativeTrapData(dp_dst);
       SpeculativeTrapData* data_src = new SpeculativeTrapData(dp_src);
@@ -102,7 +103,7 @@
       // An empty slot or ArgInfoData entry marks the end of the trap data
       return;
     default:
-      fatal(err_msg("bad tag = %d", dp_src->tag()));
+      fatal(err_msg("bad tag = %d", dp_dst->tag()));
     }
   }
 }
--- a/hotspot/src/share/vm/code/codeCache.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/code/codeCache.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -198,14 +198,12 @@
   }
   maxCodeCacheUsed = MAX2(maxCodeCacheUsed, ((address)_heap->high_boundary() -
                           (address)_heap->low_boundary()) - unallocated_capacity());
-  verify_if_often();
   print_trace("allocation", cb, size);
   return cb;
 }
 
 void CodeCache::free(CodeBlob* cb) {
   assert_locked_or_safepoint(CodeCache_lock);
-  verify_if_often();
 
   print_trace("free", cb);
   if (cb->is_nmethod()) {
@@ -221,7 +219,6 @@
 
   _heap->deallocate(cb);
 
-  verify_if_often();
   assert(_number_of_blobs >= 0, "sanity check");
 }
 
@@ -244,12 +241,6 @@
 }
 
 
-void CodeCache::flush() {
-  assert_locked_or_safepoint(CodeCache_lock);
-  Unimplemented();
-}
-
-
 // Iteration over CodeBlobs
 
 #define FOR_ALL_BLOBS(var)       for (CodeBlob *var =       first() ; var != NULL; var =       next(var) )
@@ -269,7 +260,7 @@
 CodeBlob* CodeCache::find_blob(void* start) {
   CodeBlob* result = find_blob_unsafe(start);
   if (result == NULL) return NULL;
-  // We could potientially look up non_entrant methods
+  // We could potentially look up non_entrant methods
   guarantee(!result->is_zombie() || result->is_locked_by_vm() || is_error_reported(), "unsafe access to zombie method");
   return result;
 }
@@ -741,17 +732,26 @@
   }
 }
 
+void CodeCache::print_memory_overhead() {
+  size_t wasted_bytes = 0;
+  CodeBlob *cb;
+  for (cb = first(); cb != NULL; cb = next(cb)) {
+    HeapBlock* heap_block = ((HeapBlock*)cb) - 1;
+    wasted_bytes += heap_block->length() * CodeCacheSegmentSize - cb->size();
+  }
+  // Print bytes that are allocated in the freelist
+  ttyLocker ttl;
+  tty->print_cr("Number of elements in freelist: %d",    freelist_length());
+  tty->print_cr("Allocated in freelist:          %dkB",  bytes_allocated_in_freelist()/K);
+  tty->print_cr("Unused bytes in CodeBlobs:      %dkB",  (int)(wasted_bytes/K));
+  tty->print_cr("Segment map size:               %dkB",  allocated_segments()/K); // 1 byte per segment
+}
+
 //------------------------------------------------------------------------------------------------
 // Non-product version
 
 #ifndef PRODUCT
 
-void CodeCache::verify_if_often() {
-  if (VerifyCodeCacheOften) {
-    _heap->verify();
-  }
-}
-
 void CodeCache::print_trace(const char* event, CodeBlob* cb, int size) {
   if (PrintCodeCache2) {  // Need to add a new flag
     ResourceMark rm;
@@ -774,7 +774,7 @@
   int nmethodUnloaded = 0;
   int nmethodJava = 0;
   int nmethodNative = 0;
-  int maxCodeSize = 0;
+  int max_nm_size = 0;
   ResourceMark rm;
 
   CodeBlob *cb;
@@ -798,13 +798,11 @@
       if(nm->is_not_entrant()) { nmethodNotEntrant++; }
       if(nm->is_zombie()) { nmethodZombie++; }
       if(nm->is_unloaded()) { nmethodUnloaded++; }
-      if(nm->is_native_method()) { nmethodNative++; }
+      if(nm->method() != NULL && nm->is_native_method()) { nmethodNative++; }
 
       if(nm->method() != NULL && nm->is_java_method()) {
         nmethodJava++;
-        if (nm->insts_size() > maxCodeSize) {
-          maxCodeSize = nm->insts_size();
-        }
+        max_nm_size = MAX2(max_nm_size, nm->size());
       }
     } else if (cb->is_runtime_stub()) {
       runtimeStubCount++;
@@ -820,18 +818,19 @@
   }
 
   int bucketSize = 512;
-  int bucketLimit = maxCodeSize / bucketSize + 1;
+  int bucketLimit = max_nm_size / bucketSize + 1;
   int *buckets = NEW_C_HEAP_ARRAY(int, bucketLimit, mtCode);
-  memset(buckets,0,sizeof(int) * bucketLimit);
+  memset(buckets, 0, sizeof(int) * bucketLimit);
 
   for (cb = first(); cb != NULL; cb = next(cb)) {
     if (cb->is_nmethod()) {
       nmethod* nm = (nmethod*)cb;
       if(nm->is_java_method()) {
-        buckets[nm->insts_size() / bucketSize]++;
-      }
+        buckets[nm->size() / bucketSize]++;
+       }
     }
   }
+
   tty->print_cr("Code Cache Entries (total of %d)",total);
   tty->print_cr("-------------------------------------------------");
   tty->print_cr("nmethods: %d",nmethodCount);
@@ -858,6 +857,7 @@
   }
 
   FREE_C_HEAP_ARRAY(int, buckets, mtCode);
+  print_memory_overhead();
 }
 
 #endif // !PRODUCT
--- a/hotspot/src/share/vm/code/codeCache.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/code/codeCache.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -58,12 +58,13 @@
   static bool _needs_cache_clean;
   static nmethod* _scavenge_root_nmethods;  // linked via nm->scavenge_root_link()
 
-  static void verify_if_often() PRODUCT_RETURN;
-
   static void mark_scavenge_root_nmethods() PRODUCT_RETURN;
   static void verify_perm_nmethods(CodeBlobClosure* f_or_null) PRODUCT_RETURN;
 
   static int _codemem_full_count;
+  static size_t bytes_allocated_in_freelist() { return _heap->allocated_in_freelist(); }
+  static int    allocated_segments()          { return _heap->allocated_segments(); }
+  static size_t freelist_length()             { return _heap->freelist_length(); }
 
  public:
 
@@ -78,7 +79,6 @@
   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)
   static void free(CodeBlob* cb);                   // frees a CodeBlob
-  static void flush();                              // flushes all CodeBlobs
   static bool contains(void *p);                    // returns whether p is included
   static void blobs_do(void f(CodeBlob* cb));       // iterates over all CodeBlobs
   static void blobs_do(CodeBlobClosure* f);         // iterates over all CodeBlobs
@@ -150,6 +150,7 @@
   // Printing/debugging
   static void print();                           // prints summary
   static void print_internals();
+  static void print_memory_overhead();
   static void verify();                          // verifies the code cache
   static void print_trace(const char* event, CodeBlob* cb, int size = 0) PRODUCT_RETURN;
   static void print_summary(outputStream* st, bool detailed = true); // Prints a summary of the code cache usage
--- a/hotspot/src/share/vm/code/debugInfo.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/code/debugInfo.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -273,8 +273,8 @@
   }
   Method* read_method() {
     Method* o = (Method*)(code()->metadata_at(read_int()));
-    assert(o == NULL ||
-           o->is_metaspace_object(), "meta data only");
+    // is_metadata() is a faster check than is_metaspace_object()
+    assert(o == NULL || o->is_metadata(), "meta data only");
     return o;
   }
   ScopeValue* read_object_value();
--- a/hotspot/src/share/vm/code/dependencies.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/code/dependencies.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -725,13 +725,13 @@
 }
 
 // ----------------- DependencySignature --------------------------------------
-bool DependencySignature::equals(DependencySignature* sig) const {
-  if ((type() != sig->type()) || (args_count() != sig->args_count())) {
+bool DependencySignature::equals(DependencySignature const& s1, DependencySignature const& s2) {
+  if ((s1.type() != s2.type()) || (s1.args_count() != s2.args_count())) {
     return false;
   }
 
-  for (int i = 0; i < sig->args_count(); i++) {
-    if (arg(i) != sig->arg(i)) {
+  for (int i = 0; i < s1.args_count(); i++) {
+    if (s1.arg(i) != s2.arg(i)) {
       return false;
     }
   }
--- a/hotspot/src/share/vm/code/dependencies.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/code/dependencies.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -527,7 +527,7 @@
 };
 
 
-class DependencySignature : public GenericHashtableEntry<DependencySignature, ResourceObj> {
+class DependencySignature : public ResourceObj {
  private:
   int                   _args_count;
   uintptr_t             _argument_hash[Dependencies::max_arg_count];
@@ -542,12 +542,13 @@
     }
   }
 
-  bool equals(DependencySignature* sig) const;
-  uintptr_t key() const { return _argument_hash[0] >> 2; }
+  static bool     equals(DependencySignature const& s1, DependencySignature const& s2);
+  static unsigned hash  (DependencySignature const& s1) { return s1.arg(0) >> 2; }
 
   int args_count()             const { return _args_count; }
   uintptr_t arg(int idx)       const { return _argument_hash[idx]; }
   Dependencies::DepType type() const { return _type; }
+
 };
 
 
--- a/hotspot/src/share/vm/code/nmethod.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/code/nmethod.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -39,6 +39,7 @@
 #include "prims/jvmtiImpl.hpp"
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/sweeper.hpp"
+#include "utilities/resourceHash.hpp"
 #include "utilities/dtrace.hpp"
 #include "utilities/events.hpp"
 #include "utilities/xmlstream.hpp"
@@ -2135,7 +2136,11 @@
   // Turn off dependency tracing while actually testing dependencies.
   NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) );
 
- GenericHashtable<DependencySignature, ResourceObj>* table = new GenericHashtable<DependencySignature, ResourceObj>(11027);
+ typedef ResourceHashtable<DependencySignature, int, &DependencySignature::hash,
+                           &DependencySignature::equals, 11027> DepTable;
+
+ DepTable* table = new DepTable();
+
   // Iterate over live nmethods and check dependencies of all nmethods that are not
   // marked for deoptimization. A particular dependency is only checked once.
   for(nmethod* nm = CodeCache::alive_nmethod(CodeCache::first()); nm != NULL; nm = CodeCache::alive_nmethod(CodeCache::next(nm))) {
@@ -2143,9 +2148,10 @@
       for (Dependencies::DepStream deps(nm); deps.next(); ) {
         // Construct abstraction of a dependency.
         DependencySignature* current_sig = new DependencySignature(deps);
-        // Determine if 'deps' is already checked. table->add() returns
-        // 'true' if the dependency was added (i.e., was not in the hashtable).
-        if (table->add(current_sig)) {
+
+        // Determine if dependency is already checked. table->put(...) returns
+        // 'true' if the dependency is added (i.e., was not in the hashtable).
+        if (table->put(*current_sig, 1)) {
           if (deps.check_dependency() != NULL) {
             // Dependency checking failed. Print out information about the failed
             // dependency and finally fail with an assert. We can fail here, since
--- a/hotspot/src/share/vm/compiler/compilerOracle.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/compiler/compilerOracle.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -374,25 +374,8 @@
         "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
 
 #define RANGE0 "[*" RANGEBASE "]"
-#define RANGEDOT "[*" RANGEBASE ".]"
 #define RANGESLASH "[*" RANGEBASE "/]"
 
-
-// Accept several syntaxes for these patterns
-//  original syntax
-//   cmd  java.lang.String foo
-//  PrintCompilation syntax
-//   cmd  java.lang.String::foo
-//  VM syntax
-//   cmd  java/lang/String[. ]foo
-//
-
-static const char* patterns[] = {
-  "%*[ \t]%255" RANGEDOT    " "     "%255"  RANGE0 "%n",
-  "%*[ \t]%255" RANGEDOT   "::"     "%255"  RANGE0 "%n",
-  "%*[ \t]%255" RANGESLASH "%*[ .]" "%255"  RANGE0 "%n",
-};
-
 static MethodMatcher::Mode check_mode(char name[], const char*& error_msg) {
   int match = MethodMatcher::Exact;
   while (name[0] == '*') {
@@ -421,12 +404,10 @@
                       int* bytes_read, const char*& error_msg) {
   *bytes_read = 0;
   error_msg = NULL;
-  for (uint i = 0; i < ARRAY_SIZE(patterns); i++) {
-    if (2 == sscanf(line, patterns[i], class_name, method_name, bytes_read)) {
-      *c_mode = check_mode(class_name, error_msg);
-      *m_mode = check_mode(method_name, error_msg);
-      return *c_mode != MethodMatcher::Unknown && *m_mode != MethodMatcher::Unknown;
-    }
+  if (2 == sscanf(line, "%*[ \t]%255" RANGESLASH "%*[ ]" "%255"  RANGE0 "%n", class_name, method_name, bytes_read)) {
+    *c_mode = check_mode(class_name, error_msg);
+    *m_mode = check_mode(method_name, error_msg);
+    return *c_mode != MethodMatcher::Unknown && *m_mode != MethodMatcher::Unknown;
   }
   return false;
 }
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -280,6 +280,16 @@
       if (UseAdaptiveGenerationSizePolicyAtMajorCollection &&
           ((gc_cause != GCCause::_java_lang_system_gc) ||
             UseAdaptiveSizePolicyWithSystemGC)) {
+        // Swap the survivor spaces if from_space is empty. The
+        // resize_young_gen() called below is normally used after
+        // a successful young GC and swapping of survivor spaces;
+        // otherwise, it will fail to resize the young gen with
+        // the current implementation.
+        if (young_gen->from_space()->is_empty()) {
+          young_gen->from_space()->clear(SpaceDecorator::Mangle);
+          young_gen->swap_spaces();
+        }
+
         // Calculate optimal free space amounts
         assert(young_gen->max_size() >
           young_gen->from_space()->capacity_in_bytes() +
@@ -318,12 +328,8 @@
 
         heap->resize_old_gen(size_policy->calculated_old_free_size_in_bytes());
 
-        // Don't resize the young generation at an major collection.  A
-        // desired young generation size may have been calculated but
-        // resizing the young generation complicates the code because the
-        // resizing of the old generation may have moved the boundary
-        // between the young generation and the old generation.  Let the
-        // young generation resizing happen at the minor collections.
+        heap->resize_young_gen(size_policy->calculated_eden_size_in_bytes(),
+                               size_policy->calculated_survivor_size_in_bytes());
       }
       if (PrintAdaptiveSizePolicy) {
         gclog_or_tty->print_cr("AdaptiveSizeStop: collection: %d ",
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -43,6 +43,7 @@
 #include "gc_implementation/shared/gcTrace.hpp"
 #include "gc_implementation/shared/gcTraceTime.hpp"
 #include "gc_implementation/shared/isGCActiveMark.hpp"
+#include "gc_implementation/shared/spaceDecorator.hpp"
 #include "gc_interface/gcCause.hpp"
 #include "memory/gcLocker.inline.hpp"
 #include "memory/referencePolicy.hpp"
@@ -2115,6 +2116,16 @@
       if (UseAdaptiveGenerationSizePolicyAtMajorCollection &&
           ((gc_cause != GCCause::_java_lang_system_gc) ||
             UseAdaptiveSizePolicyWithSystemGC)) {
+        // Swap the survivor spaces if from_space is empty. The
+        // resize_young_gen() called below is normally used after
+        // a successful young GC and swapping of survivor spaces;
+        // otherwise, it will fail to resize the young gen with
+        // the current implementation.
+        if (young_gen->from_space()->is_empty()) {
+          young_gen->from_space()->clear(SpaceDecorator::Mangle);
+          young_gen->swap_spaces();
+        }
+
         // Calculate optimal free space amounts
         assert(young_gen->max_size() >
           young_gen->from_space()->capacity_in_bytes() +
@@ -2154,12 +2165,8 @@
         heap->resize_old_gen(
           size_policy->calculated_old_free_size_in_bytes());
 
-        // Don't resize the young generation at an major collection.  A
-        // desired young generation size may have been calculated but
-        // resizing the young generation complicates the code because the
-        // resizing of the old generation may have moved the boundary
-        // between the young generation and the old generation.  Let the
-        // young generation resizing happen at the minor collections.
+        heap->resize_young_gen(size_policy->calculated_eden_size_in_bytes(),
+                               size_policy->calculated_survivor_size_in_bytes());
       }
       if (PrintAdaptiveSizePolicy) {
         gclog_or_tty->print_cr("AdaptiveSizeStop: collection: %d ",
--- a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -3475,7 +3475,7 @@
   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(ZERO)
+#if !defined(ZERO) && defined(PPC)
   tty->print_cr("last_Java_fp: " INTPTR_FORMAT, (uintptr_t) this->_last_Java_fp);
 #endif // !ZERO
   tty->print_cr("self_link: " INTPTR_FORMAT, (uintptr_t) this->_self_link);
--- a/hotspot/src/share/vm/interpreter/templateTable.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/interpreter/templateTable.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -376,6 +376,9 @@
 #ifdef TARGET_ARCH_MODEL_ppc_32
 # include "templateTable_ppc_32.hpp"
 #endif
+#ifdef TARGET_ARCH_MODEL_ppc_64
+# include "templateTable_ppc_64.hpp"
+#endif
 
 };
 #endif /* !CC_INTERP */
--- a/hotspot/src/share/vm/memory/collectorPolicy.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/memory/collectorPolicy.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -304,10 +304,13 @@
   }
 
   // Now take the actual NewSize into account. We will silently increase NewSize
-  // if the user specified a smaller value.
+  // if the user specified a smaller or unaligned value.
   smallest_new_size = MAX2(smallest_new_size, (uintx)align_size_down(NewSize, _gen_alignment));
   if (smallest_new_size != NewSize) {
-    FLAG_SET_ERGO(uintx, NewSize, smallest_new_size);
+    // Do not use FLAG_SET_ERGO to update NewSize here, since this will override
+    // if NewSize was set on the command line or not. This information is needed
+    // later when setting the initial and minimum young generation size.
+    NewSize = smallest_new_size;
   }
   _initial_gen0_size = NewSize;
 
--- a/hotspot/src/share/vm/memory/filemap.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/memory/filemap.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -78,6 +78,10 @@
   va_start(ap, msg);
   if (RequireSharedSpaces) {
     fail(msg, ap);
+  } else {
+    if (PrintSharedSpaces) {
+      tty->print_cr("UseSharedSpaces: %s", msg);
+    }
   }
   va_end(ap);
   UseSharedSpaces = false;
--- a/hotspot/src/share/vm/memory/heap.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/memory/heap.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -43,6 +43,7 @@
   _next_segment                 = 0;
   _freelist                     = NULL;
   _freelist_segments            = 0;
+  _freelist_length              = 0;
 }
 
 
@@ -53,7 +54,7 @@
   address p = (address)_segmap.low() + beg;
   address q = (address)_segmap.low() + end;
   // initialize interval
-  while (p < q) *p++ = 0xFF;
+  while (p < q) *p++ = free_sentinel;
 }
 
 
@@ -67,7 +68,7 @@
   int i = 0;
   while (p < q) {
     *p++ = i++;
-    if (i == 0xFF) i = 1;
+    if (i == free_sentinel) i = 1;
   }
 }
 
@@ -139,11 +140,6 @@
 }
 
 
-void CodeHeap::release() {
-  Unimplemented();
-}
-
-
 bool CodeHeap::expand_by(size_t size) {
   // expand _memory space
   size_t dm = align_to_page_size(_memory.committed_size() + size) - _memory.committed_size();
@@ -157,8 +153,8 @@
     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();
-    if (ds > 0) {
-      if (!_segmap.expand_by(ds)) return false;
+    if ((ds > 0) && !_segmap.expand_by(ds)) {
+      return false;
     }
     assert(_segmap.committed_size() >= (size_t) _number_of_committed_segments, "just checking");
     // initialize additional segmap entries
@@ -167,12 +163,6 @@
   return true;
 }
 
-
-void CodeHeap::shrink_by(size_t size) {
-  Unimplemented();
-}
-
-
 void CodeHeap::clear() {
   _next_segment = 0;
   mark_segmap_as_free(0, _number_of_committed_segments);
@@ -180,26 +170,23 @@
 
 
 void* CodeHeap::allocate(size_t instance_size, bool is_critical) {
-  size_t number_of_segments = size_to_segments(instance_size + sizeof(HeapBlock));
+  size_t number_of_segments = size_to_segments(instance_size + header_size());
   assert(segments_to_size(number_of_segments) >= sizeof(FreeBlock), "not enough room for FreeList");
 
   // First check if we can satisfy request from freelist
-  debug_only(verify());
+  NOT_PRODUCT(verify());
   HeapBlock* block = search_freelist(number_of_segments, is_critical);
-  debug_only(if (VerifyCodeCacheOften) verify());
+  NOT_PRODUCT(verify());
+
   if (block != NULL) {
     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, instance_size);
-#endif
+    DEBUG_ONLY(memset((void*)block->allocated_space(), badCodeHeapNewVal, instance_size));
     return block->allocated_space();
   }
 
   // Ensure minimum size for allocation to the heap.
-  if (number_of_segments < CodeCacheMinBlockLength) {
-    number_of_segments = CodeCacheMinBlockLength;
-  }
+  number_of_segments = MAX2((int)CodeCacheMinBlockLength, (int)number_of_segments);
 
   if (!is_critical) {
     // Make sure the allocation fits in the unallocated heap without using
@@ -215,9 +202,7 @@
     HeapBlock* b =  block_at(_next_segment);
     b->initialize(number_of_segments);
     _next_segment += number_of_segments;
-#ifdef ASSERT
-    memset((void *)b->allocated_space(), badCodeHeapNewVal, instance_size);
-#endif
+    DEBUG_ONLY(memset((void *)b->allocated_space(), badCodeHeapNewVal, instance_size));
     return b->allocated_space();
   } else {
     return NULL;
@@ -230,28 +215,56 @@
   // Find start of HeapBlock
   HeapBlock* b = (((HeapBlock *)p) - 1);
   assert(b->allocated_space() == p, "sanity check");
-#ifdef ASSERT
-  memset((void *)b->allocated_space(),
-         badCodeHeapFreeVal,
-         segments_to_size(b->length()) - sizeof(HeapBlock));
-#endif
+  DEBUG_ONLY(memset((void *)b->allocated_space(), badCodeHeapFreeVal,
+             segments_to_size(b->length()) - sizeof(HeapBlock)));
   add_to_freelist(b);
-
-  debug_only(if (VerifyCodeCacheOften) verify());
+  NOT_PRODUCT(verify());
 }
 
-
+/**
+ * Uses segment map to find the the start (header) of a nmethod. This works as follows:
+ * The memory of the code cache is divided into 'segments'. The size of a segment is
+ * determined by -XX:CodeCacheSegmentSize=XX. Allocation in the code cache can only
+ * happen at segment boundaries. A pointer in the code cache can be mapped to a segment
+ * by calling segment_for(addr). Each time memory is requested from the code cache,
+ * the segmap is updated accordingly. See the following example, which illustrates the
+ * state of code cache and the segment map: (seg -> segment, nm ->nmethod)
+ *
+ *          code cache          segmap
+ *         -----------        ---------
+ * seg 1   | nm 1    |   ->   | 0     |
+ * seg 2   | nm 1    |   ->   | 1     |
+ * ...     | nm 1    |   ->   | ..    |
+ * seg m   | nm 2    |   ->   | 0     |
+ * seg m+1 | nm 2    |   ->   | 1     |
+ * ...     | nm 2    |   ->   | 2     |
+ * ...     | nm 2    |   ->   | ..    |
+ * ...     | nm 2    |   ->   | 0xFE  |
+ * seg m+n | nm 2    |   ->   | 1     |
+ * ...     | nm 2    |   ->   |       |
+ *
+ * A value of '0' in the segmap indicates that this segment contains the beginning of
+ * an nmethod. Let's walk through a simple example: If we want to find the start of
+ * an nmethod that falls into seg 2, we read the value of the segmap[2]. The value
+ * is an offset that points to the segment that contains the start of the nmethod.
+ * Another example: If we want to get the start of nm 2, and we happen to get a pointer
+ * that points to seg m+n, we first read seg[n+m], which returns '1'. So we have to
+ * do one more read of the segmap[m+n-1] to finally get the segment header.
+ */
 void* CodeHeap::find_start(void* p) const {
   if (!contains(p)) {
     return NULL;
   }
-  size_t i = segment_for(p);
-  address b = (address)_segmap.low();
-  if (b[i] == 0xFF) {
+  size_t seg_idx = segment_for(p);
+  address seg_map = (address)_segmap.low();
+  if (is_segment_unused(seg_map[seg_idx])) {
     return NULL;
   }
-  while (b[i] > 0) i -= (int)b[i];
-  HeapBlock* h = block_at(i);
+  while (seg_map[seg_idx] > 0) {
+    seg_idx -= (int)seg_map[seg_idx];
+  }
+
+  HeapBlock* h = block_at(seg_idx);
   if (h->free()) {
     return NULL;
   }
@@ -272,7 +285,7 @@
 }
 
 // Finds the next free heapblock. If the current one is free, that it returned
-void* CodeHeap::next_free(HeapBlock *b) const {
+void* CodeHeap::next_free(HeapBlock* b) const {
   // Since free blocks are merged, there is max. on free block
   // between two used ones
   if (b != NULL && b->free()) b = next_block(b);
@@ -287,7 +300,7 @@
   return NULL;
 }
 
-HeapBlock *CodeHeap::block_start(void *q) const {
+HeapBlock* CodeHeap::block_start(void* q) const {
   HeapBlock* b = (HeapBlock*)find_start(q);
   if (b == NULL) return NULL;
   return b - 1;
@@ -312,6 +325,10 @@
   return _memory.reserved_size();
 }
 
+int CodeHeap::allocated_segments() const {
+  return (int)_next_segment;
+}
+
 size_t CodeHeap::allocated_capacity() const {
   // size of used heap - size on freelist
   return segments_to_size(_next_segment - _freelist_segments);
@@ -325,7 +342,7 @@
 
 // Free list management
 
-FreeBlock *CodeHeap::following_block(FreeBlock *b) {
+FreeBlock* CodeHeap::following_block(FreeBlock *b) {
   return (FreeBlock*)(((address)b) + _segment_size * b->length());
 }
 
@@ -343,7 +360,7 @@
 }
 
 // Try to merge this block with the following block
-void CodeHeap::merge_right(FreeBlock *a) {
+bool CodeHeap::merge_right(FreeBlock* a) {
   assert(a->free(), "must be a free block");
   if (following_block(a) == a->link()) {
     assert(a->link() != NULL && a->link()->free(), "must be free too");
@@ -353,13 +370,20 @@
     // Update find_start map
     size_t beg = segment_for(a);
     mark_segmap_as_used(beg, beg + a->length());
+    _freelist_length--;
+    return true;
   }
+  return false;
 }
 
-void CodeHeap::add_to_freelist(HeapBlock *a) {
+
+void CodeHeap::add_to_freelist(HeapBlock* a) {
   FreeBlock* b = (FreeBlock*)a;
+  _freelist_length++;
+
   assert(b != _freelist, "cannot be removed twice");
 
+
   // Mark as free and update free space count
   _freelist_segments += b->length();
   b->set_free();
@@ -371,95 +395,96 @@
     return;
   }
 
-  // Scan for right place to put into list. List
-  // is sorted by increasing addresses
-  FreeBlock* prev = NULL;
-  FreeBlock* cur  = _freelist;
-  while(cur != NULL && cur < b) {
-    assert(prev == NULL || prev < cur, "must be ordered");
-    prev = cur;
-    cur  = cur->link();
-  }
-
-  assert( (prev == NULL && b < _freelist) ||
-          (prev < b && (cur == NULL || b < cur)), "list must be ordered");
-
-  if (prev == NULL) {
+  // Since the freelist is ordered (smaller addresses -> larger addresses) and the
+  // element we want to insert into the freelist has a smaller address than the first
+  // element, we can simply add 'b' as the first element and we are done.
+  if (b < _freelist) {
     // Insert first in list
     b->set_link(_freelist);
     _freelist = b;
     merge_right(_freelist);
-  } else {
-    insert_after(prev, b);
+    return;
   }
+
+  // Scan for right place to put into list. List
+  // is sorted by increasing addresses
+  FreeBlock* prev = _freelist;
+  FreeBlock* cur  = _freelist->link();
+  while(cur != NULL && cur < b) {
+    assert(prev < cur, "Freelist must be ordered");
+    prev = cur;
+    cur  = cur->link();
+  }
+  assert((prev < b) && (cur == NULL || b < cur), "free-list must be ordered");
+  insert_after(prev, b);
 }
 
-// Search freelist for an entry on the list with the best fit
-// Return NULL if no one was found
+/**
+ * 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, bool is_critical) {
-  FreeBlock *best_block = NULL;
-  FreeBlock *best_prev  = NULL;
-  size_t best_length = 0;
+  FreeBlock* found_block = NULL;
+  FreeBlock* found_prev  = NULL;
+  size_t     found_length = 0;
 
-  // Search for smallest block which is bigger than length
-  FreeBlock *prev = NULL;
-  FreeBlock *cur = _freelist;
+  FreeBlock* prev = NULL;
+  FreeBlock* cur = _freelist;
+  const size_t critical_boundary = (size_t)high_boundary() - CodeCacheMinimumFreeSpace;
+
+  // Search for first block that fits
   while(cur != NULL) {
-    size_t l = cur->length();
-    if (l >= length && (best_block == NULL || best_length > l)) {
-
+    if (cur->length() >= length) {
       // 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;
-        }
+      // Make sure the end of the allocation doesn't cross into the last part of the code heap.
+      if (!is_critical && (((size_t)cur + length) > critical_boundary)) {
+        // The freelist is sorted by address - if one fails, all consecutive will also fail.
+        break;
       }
+      // Remember block, its previous element, and its length
+      found_block = cur;
+      found_prev  = prev;
+      found_length = found_block->length();
 
-      // Remember best block, its previous element, and its length
-      best_block = cur;
-      best_prev  = prev;
-      best_length = best_block->length();
+      break;
     }
-
     // Next element in list
     prev = cur;
     cur  = cur->link();
   }
 
-  if (best_block == NULL) {
+  if (found_block == NULL) {
     // None found
     return NULL;
   }
 
-  assert((best_prev == NULL && _freelist == best_block ) ||
-         (best_prev != NULL && best_prev->link() == best_block), "sanity check");
-
   // Exact (or at least good enough) fit. Remove from list.
   // Don't leave anything on the freelist smaller than CodeCacheMinBlockLength.
-  if (best_length < length + CodeCacheMinBlockLength) {
-    length = best_length;
-    if (best_prev == NULL) {
-      assert(_freelist == best_block, "sanity check");
+  if (found_length - length < CodeCacheMinBlockLength) {
+    _freelist_length--;
+    length = found_length;
+    if (found_prev == NULL) {
+      assert(_freelist == found_block, "sanity check");
       _freelist = _freelist->link();
     } else {
+      assert((found_prev->link() == found_block), "sanity check");
       // Unmap element
-      best_prev->set_link(best_block->link());
+      found_prev->set_link(found_block->link());
     }
   } else {
     // Truncate block and return a pointer to the following block
-    best_block->set_length(best_length - length);
-    best_block = following_block(best_block);
     // Set used bit and length on new block
-    size_t beg = segment_for(best_block);
+    found_block->set_length(found_length - length);
+    found_block = following_block(found_block);
+
+    size_t beg = segment_for(found_block);
     mark_segmap_as_used(beg, beg + length);
-    best_block->set_length(length);
+    found_block->set_length(length);
   }
 
-  best_block->set_used();
+  found_block->set_used();
   _freelist_segments -= length;
-  return best_block;
+  return found_block;
 }
 
 //----------------------------------------------------------------------------
@@ -471,33 +496,34 @@
   tty->print_cr("The Heap");
 }
 
-#endif
-
 void CodeHeap::verify() {
-  // Count the number of blocks on the freelist, and the amount of space
-  // represented.
-  int count = 0;
-  size_t len = 0;
-  for(FreeBlock* b = _freelist; b != NULL; b = b->link()) {
-    len += b->length();
-    count++;
-  }
-
-  // Verify that freelist contains the right amount of free space
-  //  guarantee(len == _freelist_segments, "wrong freelist");
+  if (VerifyCodeCache) {
+    size_t len = 0;
+    int count = 0;
+    for(FreeBlock* b = _freelist; b != NULL; b = b->link()) {
+      len += b->length();
+      count++;
+      // Check if we have merged all free blocks
+      assert(merge_right(b) == false, "Missed merging opportunity");
+    }
+    // Verify that freelist contains the right amount of free space
+    assert(len == _freelist_segments, "wrong freelist");
 
-  // Verify that the number of free blocks is not out of hand.
-  static int free_block_threshold = 10000;
-  if (count > free_block_threshold) {
-    warning("CodeHeap: # of free blocks > %d", free_block_threshold);
-    // Double the warning limit
-    free_block_threshold *= 2;
-  }
+    for(HeapBlock* h = first_block(); h != NULL; h = next_block(h)) {
+      if (h->free()) count--;
+    }
+    // Verify that the freelist contains the same number of blocks
+    // than free blocks found on the full list.
+    assert(count == 0, "missing free blocks");
 
-  // Verify that the freelist contains the same number of free blocks that is
-  // found on the full list.
-  for(HeapBlock *h = first_block(); h != NULL; h = next_block(h)) {
-    if (h->free()) count--;
+    // Verify that the number of free blocks is not out of hand.
+    static int free_block_threshold = 10000;
+    if (count > free_block_threshold) {
+      warning("CodeHeap: # of free blocks > %d", free_block_threshold);
+      // Double the warning limit
+      free_block_threshold *= 2;
+    }
   }
-  //  guarantee(count == 0, "missing free blocks");
 }
+
+#endif
--- a/hotspot/src/share/vm/memory/heap.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/memory/heap.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -92,24 +92,28 @@
 
   FreeBlock*   _freelist;
   size_t       _freelist_segments;               // No. of segments in freelist
+  int          _freelist_length;
+
+  enum { free_sentinel = 0xFF };
 
   // Helper functions
   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; }
+  bool     is_segment_unused(int val) const      { return val == free_sentinel; }
   HeapBlock* block_at(size_t i) const            { return (HeapBlock*)(_memory.low() + (i << _log2_segment_size)); }
 
   void  mark_segmap_as_free(size_t beg, size_t end);
   void  mark_segmap_as_used(size_t beg, size_t end);
 
   // Freelist management helpers
-  FreeBlock* following_block(FreeBlock *b);
+  FreeBlock* following_block(FreeBlock* b);
   void insert_after(FreeBlock* a, FreeBlock* b);
-  void merge_right (FreeBlock* a);
+  bool merge_right (FreeBlock* a);
 
   // Toplevel freelist management
-  void add_to_freelist(HeapBlock *b);
+  void add_to_freelist(HeapBlock* b);
   FreeBlock* search_freelist(size_t length, bool is_critical);
 
   // Iteration helpers
@@ -120,20 +124,18 @@
 
   // to perform additional actions on creation of executable code
   void on_code_mapping(char* base, size_t size);
+  void clear();                                 // clears all heap contents
 
  public:
   CodeHeap();
 
   // Heap extents
   bool  reserve(size_t reserved_size, size_t committed_size, size_t segment_size);
-  void  release();                               // releases all allocated memory
   bool  expand_by(size_t size);                  // expands committed memory by size
-  void  shrink_by(size_t size);                  // shrinks committed memory by size
-  void  clear();                                 // clears all heap contents
 
   // Memory allocation
   void* allocate  (size_t size, bool is_critical);  // allocates a block of size or returns NULL
-  void  deallocate(void* p);                     // deallocates a block
+  void  deallocate(void* p);                        // deallocates a block
 
   // Attributes
   char* low_boundary() const                     { return _memory.low_boundary (); }
@@ -141,12 +143,13 @@
   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
+  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
+  size_t allocated_in_freelist() const           { return _freelist_segments * CodeCacheSegmentSize; }
+  int    freelist_length()       const           { return _freelist_length; } // number of elements in the freelist
 
   // returns the first block or NULL
   void* first() const       { return next_free(first_block()); }
@@ -156,6 +159,7 @@
   // Statistics
   size_t capacity() const;
   size_t max_capacity() const;
+  int    allocated_segments() const;
   size_t allocated_capacity() const;
   size_t unallocated_capacity() const            { return max_capacity() - allocated_capacity(); }
 
@@ -164,7 +168,7 @@
 
 public:
   // Debugging
-  void verify();
+  void verify() PRODUCT_RETURN;
   void print()  PRODUCT_RETURN;
 };
 
--- a/hotspot/src/share/vm/oops/constantPool.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/oops/constantPool.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1295,6 +1295,7 @@
   } break;
 
   case JVM_CONSTANT_UnresolvedClass:
+  case JVM_CONSTANT_UnresolvedClassInError:
   {
     // Can be resolved after checking tag, so check the slot first.
     CPSlot entry = from_cp->slot_at(from_i);
--- a/hotspot/src/share/vm/oops/metadata.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/oops/metadata.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -42,6 +42,7 @@
   // Rehashing support for tables containing pointers to this
   unsigned int new_hash(juint seed)   { ShouldNotReachHere();  return 0; }
 
+  virtual bool is_metadata()           const volatile { return true; }
   virtual bool is_klass()              const volatile { return false; }
   virtual bool is_method()             const volatile { return false; }
   virtual bool is_methodData()         const volatile { return false; }
--- a/hotspot/src/share/vm/oops/method.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/oops/method.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -108,12 +108,16 @@
 #endif
   u2                _method_size;                // size of this object
   u1                _intrinsic_id;               // vmSymbols::intrinsic_id (0 == _none)
-  u1                _jfr_towrite      : 1,       // Flags
-                    _caller_sensitive : 1,
-                    _force_inline     : 1,
-                    _hidden           : 1,
-                    _dont_inline      : 1,
-                                      : 3;
+
+  // Flags
+  enum Flags {
+    _jfr_towrite      = 1 << 0,
+    _caller_sensitive = 1 << 1,
+    _force_inline     = 1 << 2,
+    _dont_inline      = 1 << 3,
+    _hidden           = 1 << 4
+  };
+  u1 _flags;
 
 #ifndef PRODUCT
   int               _compiled_invocation_count;  // Number of nmethod invocations so far (for perf. debugging)
@@ -759,16 +763,41 @@
   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 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;           }
+  bool jfr_towrite() {
+    return (_flags & _jfr_towrite) != 0;
+  }
+  void set_jfr_towrite(bool x) {
+    _flags = x ? (_flags | _jfr_towrite) : (_flags & ~_jfr_towrite);
+  }
+
+  bool caller_sensitive() {
+    return (_flags & _caller_sensitive) != 0;
+  }
+  void set_caller_sensitive(bool x) {
+    _flags = x ? (_flags | _caller_sensitive) : (_flags & ~_caller_sensitive);
+  }
+
+  bool force_inline() {
+    return (_flags & _force_inline) != 0;
+  }
+  void set_force_inline(bool x) {
+    _flags = x ? (_flags | _force_inline) : (_flags & ~_force_inline);
+  }
+
+  bool dont_inline() {
+    return (_flags & _dont_inline) != 0;
+  }
+  void set_dont_inline(bool x) {
+    _flags = x ? (_flags | _dont_inline) : (_flags & ~_dont_inline);
+  }
+
+  bool is_hidden() {
+    return (_flags & _hidden) != 0;
+  }
+  void set_hidden(bool x) {
+    _flags = x ? (_flags | _hidden) : (_flags & ~_hidden);
+  }
+
   ConstMethod::MethodType method_type() const {
       return _constMethod->method_type();
   }
--- a/hotspot/src/share/vm/oops/methodData.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/oops/methodData.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1071,7 +1071,8 @@
 }
 
 // Initialize the MethodData* corresponding to a given method.
-MethodData::MethodData(methodHandle method, int size, TRAPS) {
+MethodData::MethodData(methodHandle method, int size, TRAPS)
+  : _extra_data_lock(Monitor::leaf, "MDO extra data lock") {
   No_Safepoint_Verifier no_safepoint;  // init function atomic wrt GC
   ResourceMark rm;
   // Set the method back-pointer.
@@ -1235,7 +1236,7 @@
   return (DataLayout*)((address)dp + DataLayout::compute_size_in_bytes(nb_cells));
 }
 
-ProfileData* MethodData::bci_to_extra_data_helper(int bci, Method* m, DataLayout*& dp) {
+ProfileData* MethodData::bci_to_extra_data_helper(int bci, Method* m, DataLayout*& dp, bool concurrent) {
   DataLayout* end = extra_data_limit();
 
   for (;; dp = next_extra(dp)) {
@@ -1257,10 +1258,11 @@
       if (m != NULL) {
         SpeculativeTrapData* data = new SpeculativeTrapData(dp);
         // data->method() may be null in case of a concurrent
-        // allocation. Assume it's for the same method and use that
+        // allocation. Maybe it's for the same method. Try to use that
         // entry in that case.
         if (dp->bci() == bci) {
           if (data->method() == NULL) {
+            assert(concurrent, "impossible because no concurrent allocation");
             return NULL;
           } else if (data->method() == m) {
             return data;
@@ -1289,40 +1291,40 @@
   // Allocation in the extra data space has to be atomic because not
   // all entries have the same size and non atomic concurrent
   // allocation would result in a corrupted extra data space.
-  while (true) {
-    ProfileData* result = bci_to_extra_data_helper(bci, m, dp);
-    if (result != NULL) {
+  ProfileData* result = bci_to_extra_data_helper(bci, m, dp, true);
+  if (result != NULL) {
+    return result;
+  }
+
+  if (create_if_missing && dp < end) {
+    MutexLocker ml(&_extra_data_lock);
+    // Check again now that we have the lock. Another thread may
+    // have added extra data entries.
+    ProfileData* result = bci_to_extra_data_helper(bci, m, dp, false);
+    if (result != NULL || dp >= end) {
       return result;
     }
 
-    if (create_if_missing && dp < end) {
-      assert(dp->tag() == DataLayout::no_tag || (dp->tag() == DataLayout::speculative_trap_data_tag && m != NULL), "should be free");
-      assert(next_extra(dp)->tag() == DataLayout::no_tag || next_extra(dp)->tag() == DataLayout::arg_info_data_tag, "should be free or arg info");
-      u1 tag = m == NULL ? DataLayout::bit_data_tag : DataLayout::speculative_trap_data_tag;
-      // SpeculativeTrapData is 2 slots. Make sure we have room.
-      if (m != NULL && next_extra(dp)->tag() != DataLayout::no_tag) {
-        return NULL;
-      }
-      DataLayout temp;
-      temp.initialize(tag, bci, 0);
-      // May have been set concurrently
-      if (dp->header() != temp.header() && !dp->atomic_set_header(temp.header())) {
-        // Allocation failure because of concurrent allocation. Try
-        // again.
-        continue;
-      }
-      assert(dp->tag() == tag, "sane");
-      assert(dp->bci() == bci, "no concurrent allocation");
-      if (tag == DataLayout::bit_data_tag) {
-        return new BitData(dp);
-      } else {
-        // If being allocated concurrently, one trap may be lost
-        SpeculativeTrapData* data = new SpeculativeTrapData(dp);
-        data->set_method(m);
-        return data;
-      }
+    assert(dp->tag() == DataLayout::no_tag || (dp->tag() == DataLayout::speculative_trap_data_tag && m != NULL), "should be free");
+    assert(next_extra(dp)->tag() == DataLayout::no_tag || next_extra(dp)->tag() == DataLayout::arg_info_data_tag, "should be free or arg info");
+    u1 tag = m == NULL ? DataLayout::bit_data_tag : DataLayout::speculative_trap_data_tag;
+    // SpeculativeTrapData is 2 slots. Make sure we have room.
+    if (m != NULL && next_extra(dp)->tag() != DataLayout::no_tag) {
+      return NULL;
     }
-    return NULL;
+    DataLayout temp;
+    temp.initialize(tag, bci, 0);
+
+    dp->set_header(temp.header());
+    assert(dp->tag() == tag, "sane");
+    assert(dp->bci() == bci, "no concurrent allocation");
+    if (tag == DataLayout::bit_data_tag) {
+      return new BitData(dp);
+    } else {
+      SpeculativeTrapData* data = new SpeculativeTrapData(dp);
+      data->set_method(m);
+      return data;
+    }
   }
   return NULL;
 }
--- a/hotspot/src/share/vm/oops/methodData.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/oops/methodData.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -190,12 +190,6 @@
   void set_header(intptr_t value) {
     _header._bits = value;
   }
-  bool atomic_set_header(intptr_t value) {
-    if (Atomic::cmpxchg_ptr(value, (volatile intptr_t*)&_header._bits, 0) == 0) {
-      return true;
-    }
-    return false;
-  }
   intptr_t header() {
     return _header._bits;
   }
@@ -2047,10 +2041,12 @@
   // Cached hint for bci_to_dp and bci_to_data
   int _hint_di;
 
+  Mutex _extra_data_lock;
+
   MethodData(methodHandle method, int size, TRAPS);
 public:
   static MethodData* allocate(ClassLoaderData* loader_data, methodHandle method, TRAPS);
-  MethodData() {}; // For ciMethodData
+  MethodData() : _extra_data_lock(Monitor::leaf, "MDO extra data lock") {}; // For ciMethodData
 
   bool is_methodData() const volatile { return true; }
 
@@ -2155,7 +2151,7 @@
   // What is the index of the first data entry?
   int first_di() const { return 0; }
 
-  ProfileData* bci_to_extra_data_helper(int bci, Method* m, DataLayout*& dp);
+  ProfileData* bci_to_extra_data_helper(int bci, Method* m, DataLayout*& dp, bool concurrent);
   // Find or create an extra ProfileData:
   ProfileData* bci_to_extra_data(int bci, Method* m, bool create_if_missing);
 
--- a/hotspot/src/share/vm/opto/c2_globals.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/opto/c2_globals.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -452,7 +452,7 @@
   product(bool, EliminateAutoBox, true,                                     \
           "Control optimizations for autobox elimination")                  \
                                                                             \
-  experimental(bool, UseImplicitStableValues, false,                        \
+  diagnostic(bool, UseImplicitStableValues, true,                           \
           "Mark well-known stable fields as such (e.g. String.value)")      \
                                                                             \
   product(intx, AutoBoxCacheMax, 128,                                       \
@@ -650,7 +650,7 @@
   experimental(bool, ReplaceInParentMaps, false,                            \
           "Propagate type improvements in callers of inlinee if possible")  \
                                                                             \
-  experimental(bool, UseTypeSpeculation, false,                             \
+  product(bool, UseTypeSpeculation, true,                                   \
           "Speculatively propagate types from profiles")                    \
                                                                             \
   diagnostic(bool, UseInlineDepthForSpeculativeTypes, true,                 \
--- a/hotspot/src/share/vm/opto/graphKit.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/opto/graphKit.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -3007,22 +3007,28 @@
   }
 
   Node* cast_obj = NULL;
-  const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
-  // We may not have profiling here or it may not help us. If we have
-  // a speculative type use it to perform an exact cast.
-  ciKlass* spec_obj_type = obj_type->speculative_type();
-  if (spec_obj_type != NULL ||
-      (data != NULL &&
-       // Counter has never been decremented (due to cast failure).
-       // ...This is a reasonable thing to expect.  It is true of
-       // all casts inserted by javac to implement generic types.
-       data->as_CounterData()->count() >= 0)) {
-    cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk->klass(), spec_obj_type, safe_for_replace);
-    if (cast_obj != NULL) {
-      if (failure_control != NULL) // failure is now impossible
-        (*failure_control) = top();
-      // adjust the type of the phi to the exact klass:
-      phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
+  if (tk->klass_is_exact()) {
+    // The following optimization tries to statically cast the speculative type of the object
+    // (for example obtained during profiling) to the type of the superklass and then do a
+    // dynamic check that the type of the object is what we expect. To work correctly
+    // for checkcast and aastore the type of superklass should be exact.
+    const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
+    // We may not have profiling here or it may not help us. If we have
+    // a speculative type use it to perform an exact cast.
+    ciKlass* spec_obj_type = obj_type->speculative_type();
+    if (spec_obj_type != NULL ||
+        (data != NULL &&
+         // Counter has never been decremented (due to cast failure).
+         // ...This is a reasonable thing to expect.  It is true of
+         // all casts inserted by javac to implement generic types.
+         data->as_CounterData()->count() >= 0)) {
+      cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk->klass(), spec_obj_type, safe_for_replace);
+      if (cast_obj != NULL) {
+        if (failure_control != NULL) // failure is now impossible
+          (*failure_control) = top();
+        // adjust the type of the phi to the exact klass:
+        phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
+      }
     }
   }
 
--- a/hotspot/src/share/vm/opto/library_call.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/opto/library_call.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -3180,7 +3180,8 @@
 // private native boolean java.lang.Thread.isInterrupted(boolean ClearInterrupted);
 bool LibraryCallKit::inline_native_isInterrupted() {
   // Add a fast path to t.isInterrupted(clear_int):
-  //   (t == Thread.current() && (!TLS._osthread._interrupted || !clear_int))
+  //   (t == Thread.current() &&
+  //    (!TLS._osthread._interrupted || WINDOWS_ONLY(false) NOT_WINDOWS(!clear_int)))
   //   ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)
   // So, in the common case that the interrupt bit is false,
   // we avoid making a call into the VM.  Even if the interrupt bit
@@ -3237,6 +3238,7 @@
   // drop through to next case
   set_control( _gvn.transform(new (C) IfTrueNode(iff_bit)));
 
+#ifndef TARGET_OS_FAMILY_windows
   // (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.
   Node* clr_arg = argument(1);
   Node* cmp_arg = _gvn.transform(new (C) CmpINode(clr_arg, intcon(0)));
@@ -3250,6 +3252,10 @@
 
   // drop through to next case
   set_control( _gvn.transform(new (C) IfTrueNode(iff_arg)));
+#else
+  // To return true on Windows you must read the _interrupted field
+  // and check the the event state i.e. take the slow path.
+#endif // TARGET_OS_FAMILY_windows
 
   // (d) Otherwise, go to the slow path.
   slow_region->add_req(control());
--- a/hotspot/src/share/vm/opto/matcher.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/opto/matcher.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1922,6 +1922,105 @@
   return OptoReg::as_OptoReg(regs.first());
 }
 
+// This function identifies sub-graphs in which a 'load' node is
+// input to two different nodes, and such that it can be matched
+// with BMI instructions like blsi, blsr, etc.
+// Example : for b = -a[i] & a[i] can be matched to blsi r32, m32.
+// The graph is (AndL (SubL Con0 LoadL*) LoadL*), where LoadL*
+// refers to the same node.
+#ifdef X86
+// Match the generic fused operations pattern (op1 (op2 Con{ConType} mop) mop)
+// This is a temporary solution until we make DAGs expressible in ADL.
+template<typename ConType>
+class FusedPatternMatcher {
+  Node* _op1_node;
+  Node* _mop_node;
+  int _con_op;
+
+  static int match_next(Node* n, int next_op, int next_op_idx) {
+    if (n->in(1) == NULL || n->in(2) == NULL) {
+      return -1;
+    }
+
+    if (next_op_idx == -1) { // n is commutative, try rotations
+      if (n->in(1)->Opcode() == next_op) {
+        return 1;
+      } else if (n->in(2)->Opcode() == next_op) {
+        return 2;
+      }
+    } else {
+      assert(next_op_idx > 0 && next_op_idx <= 2, "Bad argument index");
+      if (n->in(next_op_idx)->Opcode() == next_op) {
+        return next_op_idx;
+      }
+    }
+    return -1;
+  }
+public:
+  FusedPatternMatcher(Node* op1_node, Node *mop_node, int con_op) :
+    _op1_node(op1_node), _mop_node(mop_node), _con_op(con_op) { }
+
+  bool match(int op1, int op1_op2_idx,  // op1 and the index of the op1->op2 edge, -1 if op1 is commutative
+             int op2, int op2_con_idx,  // op2 and the index of the op2->con edge, -1 if op2 is commutative
+             typename ConType::NativeType con_value) {
+    if (_op1_node->Opcode() != op1) {
+      return false;
+    }
+    if (_mop_node->outcnt() > 2) {
+      return false;
+    }
+    op1_op2_idx = match_next(_op1_node, op2, op1_op2_idx);
+    if (op1_op2_idx == -1) {
+      return false;
+    }
+    // Memory operation must be the other edge
+    int op1_mop_idx = (op1_op2_idx & 1) + 1;
+
+    // Check that the mop node is really what we want
+    if (_op1_node->in(op1_mop_idx) == _mop_node) {
+      Node *op2_node = _op1_node->in(op1_op2_idx);
+      if (op2_node->outcnt() > 1) {
+        return false;
+      }
+      assert(op2_node->Opcode() == op2, "Should be");
+      op2_con_idx = match_next(op2_node, _con_op, op2_con_idx);
+      if (op2_con_idx == -1) {
+        return false;
+      }
+      // Memory operation must be the other edge
+      int op2_mop_idx = (op2_con_idx & 1) + 1;
+      // Check that the memory operation is the same node
+      if (op2_node->in(op2_mop_idx) == _mop_node) {
+        // Now check the constant
+        const Type* con_type = op2_node->in(op2_con_idx)->bottom_type();
+        if (con_type != Type::TOP && ConType::as_self(con_type)->get_con() == con_value) {
+          return true;
+        }
+      }
+    }
+    return false;
+  }
+};
+
+
+bool Matcher::is_bmi_pattern(Node *n, Node *m) {
+  if (n != NULL && m != NULL) {
+    if (m->Opcode() == Op_LoadI) {
+      FusedPatternMatcher<TypeInt> bmii(n, m, Op_ConI);
+      return bmii.match(Op_AndI, -1, Op_SubI,  1,  0)  ||
+             bmii.match(Op_AndI, -1, Op_AddI, -1, -1)  ||
+             bmii.match(Op_XorI, -1, Op_AddI, -1, -1);
+    } else if (m->Opcode() == Op_LoadL) {
+      FusedPatternMatcher<TypeLong> bmil(n, m, Op_ConL);
+      return bmil.match(Op_AndL, -1, Op_SubL,  1,  0) ||
+             bmil.match(Op_AndL, -1, Op_AddL, -1, -1) ||
+             bmil.match(Op_XorL, -1, Op_AddL, -1, -1);
+    }
+  }
+  return false;
+}
+#endif // X86
+
 // A method-klass-holder may be passed in the inline_cache_reg
 // and then expanded into the inline_cache_reg and a method_oop register
 //   defined in ad_<arch>.cpp
@@ -2077,6 +2176,14 @@
           set_shared(m->in(AddPNode::Base)->in(1));
         }
 
+        // if 'n' and 'm' are part of a graph for BMI instruction, clone this node.
+#ifdef X86
+        if (UseBMI1Instructions && is_bmi_pattern(n, m)) {
+          mstack.push(m, Visit);
+          continue;
+        }
+#endif
+
         // Clone addressing expressions as they are "free" in memory access instructions
         if( mem_op && i == MemNode::Address && mop == Op_AddP ) {
           // Some inputs for address expression are not put on stack
--- a/hotspot/src/share/vm/opto/matcher.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/opto/matcher.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -79,6 +79,9 @@
 
   // Find shared Nodes, or Nodes that otherwise are Matcher roots
   void find_shared( Node *n );
+#ifdef X86
+  bool is_bmi_pattern(Node *n, Node *m);
+#endif
 
   // Debug and profile information for nodes in old space:
   GrowableArray<Node_Notes*>* _old_node_note_array;
--- a/hotspot/src/share/vm/opto/memnode.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/opto/memnode.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1593,35 +1593,33 @@
 
 // Try to constant-fold a stable array element.
 static const Type* fold_stable_ary_elem(const TypeAryPtr* ary, int off, BasicType loadbt) {
+  assert(ary->const_oop(), "array should be constant");
   assert(ary->is_stable(), "array should be stable");
 
-  if (ary->const_oop() != NULL) {
-    // Decode the results of GraphKit::array_element_address.
-    ciArray* aobj = ary->const_oop()->as_array();
-    ciConstant con = aobj->element_value_by_offset(off);
-
-    if (con.basic_type() != T_ILLEGAL && !con.is_null_or_zero()) {
-      const Type* con_type = Type::make_from_constant(con);
-      if (con_type != NULL) {
-        if (con_type->isa_aryptr()) {
-          // Join with the array element type, in case it is also stable.
-          int dim = ary->stable_dimension();
-          con_type = con_type->is_aryptr()->cast_to_stable(true, dim-1);
-        }
-        if (loadbt == T_NARROWOOP && con_type->isa_oopptr()) {
-          con_type = con_type->make_narrowoop();
-        }
+  // Decode the results of GraphKit::array_element_address.
+  ciArray* aobj = ary->const_oop()->as_array();
+  ciConstant con = aobj->element_value_by_offset(off);
+
+  if (con.basic_type() != T_ILLEGAL && !con.is_null_or_zero()) {
+    const Type* con_type = Type::make_from_constant(con);
+    if (con_type != NULL) {
+      if (con_type->isa_aryptr()) {
+        // Join with the array element type, in case it is also stable.
+        int dim = ary->stable_dimension();
+        con_type = con_type->is_aryptr()->cast_to_stable(true, dim-1);
+      }
+      if (loadbt == T_NARROWOOP && con_type->isa_oopptr()) {
+        con_type = con_type->make_narrowoop();
+      }
 #ifndef PRODUCT
-        if (TraceIterativeGVN) {
-          tty->print("FoldStableValues: array element [off=%d]: con_type=", off);
-          con_type->dump(); tty->cr();
-        }
+      if (TraceIterativeGVN) {
+        tty->print("FoldStableValues: array element [off=%d]: con_type=", off);
+        con_type->dump(); tty->cr();
+      }
 #endif //PRODUCT
-        return con_type;
-      }
+      return con_type;
     }
   }
-
   return NULL;
 }
 
@@ -1641,7 +1639,7 @@
   // Try to guess loaded type from pointer type
   if (tp->isa_aryptr()) {
     const TypeAryPtr* ary = tp->is_aryptr();
-    const Type *t = ary->elem();
+    const Type* t = ary->elem();
 
     // Determine whether the reference is beyond the header or not, by comparing
     // the offset against the offset of the start of the array's data.
@@ -1653,10 +1651,9 @@
     const bool off_beyond_header = ((uint)off >= (uint)min_base_off);
 
     // Try to constant-fold a stable array element.
-    if (FoldStableValues && ary->is_stable()) {
-      // Make sure the reference is not into the header
-      if (off_beyond_header && off != Type::OffsetBot) {
-        assert(adr->is_AddP() && adr->in(AddPNode::Offset)->is_Con(), "offset is a constant");
+    if (FoldStableValues && ary->is_stable() && ary->const_oop() != NULL) {
+      // Make sure the reference is not into the header and the offset is constant
+      if (off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) {
         const Type* con_type = fold_stable_ary_elem(ary, off, memory_type());
         if (con_type != NULL) {
           return con_type;
--- a/hotspot/src/share/vm/opto/multnode.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/opto/multnode.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +194,9 @@
     }
   }
 
-  ProjNode* other_proj = iff->proj_out(1-_con)->as_Proj();
+  ProjNode* other_proj = iff->proj_out(1-_con);
+  if (other_proj == NULL) // Should never happen, but make Parfait happy.
+      return false;
   if (other_proj->is_uncommon_trap_proj(reason)) {
     assert(reason == Deoptimization::Reason_none ||
            Compile::current()->is_predicate_opaq(iff->in(1)->in(1)), "should be on the list");
--- a/hotspot/src/share/vm/opto/parse.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/opto/parse.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -338,6 +338,8 @@
   GraphKit      _exits;         // Record all normal returns and throws here.
   bool          _wrote_final;   // Did we write a final field?
   bool          _wrote_volatile;     // Did we write a volatile field?
+  bool          _wrote_stable;       // Did we write a @Stable field?
+  bool          _wrote_fields;       // Did we write any field?
   bool          _count_invocations;  // update and test invocation counter
   bool          _method_data_update; // update method data oop
   Node*         _alloc_with_final;   // An allocation node with final field
@@ -383,6 +385,10 @@
   void      set_wrote_final(bool z)   { _wrote_final = z; }
   bool          wrote_volatile() const { return _wrote_volatile; }
   void      set_wrote_volatile(bool z) { _wrote_volatile = z; }
+  bool          wrote_stable() const  { return _wrote_stable; }
+  void      set_wrote_stable(bool z)  { _wrote_stable = z; }
+  bool         wrote_fields() const   { return _wrote_fields; }
+  void     set_wrote_fields(bool z)   { _wrote_fields = z; }
   bool          count_invocations() const  { return _count_invocations; }
   bool          method_data_update() const { return _method_data_update; }
   Node*    alloc_with_final() const   { return _alloc_with_final; }
--- a/hotspot/src/share/vm/opto/parse1.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/opto/parse1.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -391,6 +391,8 @@
   _depth = 1 + (caller->has_method() ? caller->depth() : 0);
   _wrote_final = false;
   _wrote_volatile = false;
+  _wrote_stable = false;
+  _wrote_fields = false;
   _alloc_with_final = NULL;
   _entry_bci = InvocationEntryBci;
   _tf = NULL;
@@ -908,26 +910,35 @@
   Node* iophi = _exits.i_o();
   _exits.set_i_o(gvn().transform(iophi));
 
-  // On PPC64, also add MemBarRelease for constructors which write
-  // volatile fields. As support_IRIW_for_not_multiple_copy_atomic_cpu
-  // is set on PPC64, no sync instruction is issued after volatile
-  // stores. We want to quarantee the same behaviour as on platforms
-  // with total store order, although this is not required by the Java
-  // memory model. So as with finals, we add a barrier here.
-  if (wrote_final() PPC64_ONLY(|| (wrote_volatile() && method()->is_initializer()))) {
-    // This method (which must be a constructor by the rules of Java)
-    // wrote a final.  The effects of all initializations must be
-    // committed to memory before any code after the constructor
-    // publishes the reference to the newly constructor object.
-    // Rather than wait for the publication, we simply block the
-    // writes here.  Rather than put a barrier on only those writes
-    // which are required to complete, we force all writes to complete.
-    //
-    // "All bets are off" unless the first publication occurs after a
-    // normal return from the constructor.  We do not attempt to detect
-    // such unusual early publications.  But no barrier is needed on
-    // exceptional returns, since they cannot publish normally.
-    //
+  // Figure out if we need to emit the trailing barrier. The barrier is only
+  // needed in the constructors, and only in three cases:
+  //
+  // 1. The constructor wrote a final. The effects of all initializations
+  //    must be committed to memory before any code after the constructor
+  //    publishes the reference to the newly constructed object. Rather
+  //    than wait for the publication, we simply block the writes here.
+  //    Rather than put a barrier on only those writes which are required
+  //    to complete, we force all writes to complete.
+  //
+  // 2. On PPC64, also add MemBarRelease for constructors which write
+  //    volatile fields. As support_IRIW_for_not_multiple_copy_atomic_cpu
+  //    is set on PPC64, no sync instruction is issued after volatile
+  //    stores. We want to guarantee the same behavior as on platforms
+  //    with total store order, although this is not required by the Java
+  //    memory model. So as with finals, we add a barrier here.
+  //
+  // 3. Experimental VM option is used to force the barrier if any field
+  //    was written out in the constructor.
+  //
+  // "All bets are off" unless the first publication occurs after a
+  // normal return from the constructor.  We do not attempt to detect
+  // such unusual early publications.  But no barrier is needed on
+  // exceptional returns, since they cannot publish normally.
+  //
+  if (method()->is_initializer() &&
+        (wrote_final() ||
+           PPC64_ONLY(wrote_volatile() ||)
+           (AlwaysSafeConstructors && wrote_fields()))) {
     _exits.insert_mem_bar(Op_MemBarRelease, alloc_with_final());
 #ifndef PRODUCT
     if (PrintOpto && (Verbose || WizardMode)) {
@@ -937,6 +948,19 @@
 #endif
   }
 
+  // Any method can write a @Stable field; insert memory barriers after
+  // those also. If there is a predecessor allocation node, bind the
+  // barrier there.
+  if (wrote_stable()) {
+    _exits.insert_mem_bar(Op_MemBarRelease, alloc_with_final());
+#ifndef PRODUCT
+    if (PrintOpto && (Verbose || WizardMode)) {
+      method()->print_name();
+      tty->print_cr(" writes @Stable and needs a memory barrier");
+    }
+#endif
+  }
+
   for (MergeMemStream mms(_exits.merged_memory()); mms.next_non_empty(); ) {
     // transform each slice of the original memphi:
     mms.set_memory(_gvn.transform(mms.memory()));
--- a/hotspot/src/share/vm/opto/parse3.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/opto/parse3.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -233,7 +233,8 @@
   // Build the load.
   //
   MemNode::MemOrd mo = is_vol ? MemNode::acquire : MemNode::unordered;
-  Node* ld = make_load(NULL, adr, type, bt, adr_type, mo, is_vol);
+  bool needs_atomic_access = is_vol || AlwaysAtomicAccesses;
+  Node* ld = make_load(NULL, adr, type, bt, adr_type, mo, needs_atomic_access);
 
   // Adjust Java stack
   if (type2size[bt] == 1)
@@ -314,7 +315,8 @@
     }
     store = store_oop_to_object(control(), obj, adr, adr_type, val, field_type, bt, mo);
   } else {
-    store = store_to_memory(control(), adr, val, bt, adr_type, mo, is_vol);
+    bool needs_atomic_access = is_vol || AlwaysAtomicAccesses;
+    store = store_to_memory(control(), adr, val, bt, adr_type, mo, needs_atomic_access);
   }
 
   // If reference is volatile, prevent following volatiles ops from
@@ -332,13 +334,23 @@
     }
   }
 
+  if (is_field) {
+    set_wrote_fields(true);
+  }
+
   // If the field is final, the rules of Java say we are in <init> or <clinit>.
   // Note the presence of writes to final non-static fields, so that we
   // can insert a memory barrier later on to keep the writes from floating
   // out of the constructor.
   // Any method can write a @Stable field; insert memory barriers after those also.
   if (is_field && (field->is_final() || field->is_stable())) {
-    set_wrote_final(true);
+    if (field->is_final()) {
+        set_wrote_final(true);
+    }
+    if (field->is_stable()) {
+        set_wrote_stable(true);
+    }
+
     // Preserve allocation ptr to create precedent edge to it in membar
     // generated on exit from constructor.
     if (C->eliminate_boxing() &&
--- a/hotspot/src/share/vm/prims/jvm.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/prims/jvm.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -4360,7 +4360,7 @@
 
 JVM_ENTRY(void, JVM_GetVersionInfo(JNIEnv* env, jvm_version_info* info, size_t info_size))
 {
-  memset(info, 0, sizeof(info_size));
+  memset(info, 0, info_size);
 
   info->jvm_version = Abstract_VM_Version::jvm_version();
   info->update_version = 0;          /* 0 in HotSpot Express VM */
--- a/hotspot/src/share/vm/prims/jvmtiEnv.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiEnv.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1464,7 +1464,19 @@
     // It's fine to update the thread state here because no JVMTI events
     // shall be posted for this PopFrame.
 
-    state->update_for_pop_top_frame();
+    // It is only safe to perform the direct operation on the current
+    // thread. All other usage needs to use a vm-safepoint-op for safety.
+    if (java_thread == JavaThread::current()) {
+      state->update_for_pop_top_frame();
+    } else {
+      VM_UpdateForPopTopFrame op(state);
+      VMThread::execute(&op);
+      jvmtiError err = op.result();
+      if (err != JVMTI_ERROR_NONE) {
+        return err;
+      }
+    }
+
     java_thread->set_popframe_condition(JavaThread::popframe_pending_bit);
     // Set pending step flag for this popframe and it is cleared when next
     // step event is posted.
@@ -1505,6 +1517,7 @@
 // depth - pre-checked as non-negative
 jvmtiError
 JvmtiEnv::NotifyFramePop(JavaThread* java_thread, jint depth) {
+  jvmtiError err = JVMTI_ERROR_NONE;
   ResourceMark rm;
   uint32_t debug_bits = 0;
 
@@ -1532,10 +1545,17 @@
 
   assert(vf->frame_pointer() != NULL, "frame pointer mustn't be NULL");
 
-  int frame_number = state->count_frames() - depth;
-  state->env_thread_state(this)->set_frame_pop(frame_number);
-
-  return JVMTI_ERROR_NONE;
+  // It is only safe to perform the direct operation on the current
+  // thread. All other usage needs to use a vm-safepoint-op for safety.
+  if (java_thread == JavaThread::current()) {
+    int frame_number = state->count_frames() - depth;
+    state->env_thread_state(this)->set_frame_pop(frame_number);
+  } else {
+    VM_SetFramePop op(this, state, depth);
+    VMThread::execute(&op);
+    err = op.result();
+  }
+  return err;
 } /* end NotifyFramePop */
 
 
--- a/hotspot/src/share/vm/prims/jvmtiEnvBase.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiEnvBase.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -29,6 +29,7 @@
 #include "prims/jvmtiEnvThreadState.hpp"
 #include "prims/jvmtiEventController.hpp"
 #include "prims/jvmtiThreadState.hpp"
+#include "prims/jvmtiThreadState.inline.hpp"
 #include "runtime/fieldDescriptor.hpp"
 #include "runtime/frame.hpp"
 #include "runtime/handles.inline.hpp"
@@ -334,6 +335,60 @@
   JvmtiEnv* next(JvmtiEnvBase* env) { return env->next_environment(); }
 };
 
+// VM operation to update for pop top frame.
+class VM_UpdateForPopTopFrame : public VM_Operation {
+private:
+  JvmtiThreadState* _state;
+  jvmtiError _result;
+
+public:
+  VM_UpdateForPopTopFrame(JvmtiThreadState* state) {
+    _state = state;
+    _result = JVMTI_ERROR_NONE;
+  }
+  VMOp_Type type() const { return VMOp_UpdateForPopTopFrame; }
+  jvmtiError result() { return _result; }
+  void doit() {
+    JavaThread* jt = _state->get_thread();
+    if (Threads::includes(jt) && !jt->is_exiting() && jt->threadObj() != NULL) {
+      _state->update_for_pop_top_frame();
+    } else {
+      _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
+    }
+  }
+};
+
+// VM operation to set frame pop.
+class VM_SetFramePop : public VM_Operation {
+private:
+  JvmtiEnv *_env;
+  JvmtiThreadState* _state;
+  jint _depth;
+  jvmtiError _result;
+
+public:
+  VM_SetFramePop(JvmtiEnv *env, JvmtiThreadState* state, jint depth) {
+    _env = env;
+    _state = state;
+    _depth = depth;
+    _result = JVMTI_ERROR_NONE;
+  }
+  // Nested operation must be allowed for the VM_EnterInterpOnlyMode that is
+  // called from the JvmtiEventControllerPrivate::recompute_thread_enabled.
+  bool allow_nested_vm_operations() const { return true; }
+  VMOp_Type type() const { return VMOp_SetFramePop; }
+  jvmtiError result() { return _result; }
+  void doit() {
+    JavaThread* jt = _state->get_thread();
+    if (Threads::includes(jt) && !jt->is_exiting() && jt->threadObj() != NULL) {
+      int frame_number = _state->count_frames() - _depth;
+      _state->env_thread_state((JvmtiEnvBase*)_env)->set_frame_pop(frame_number);
+    } else {
+      _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
+    }
+  }
+};
+
 
 // VM operation to get monitor information with stack depth.
 class VM_GetOwnedMonitorInfo : public VM_Operation {
--- a/hotspot/src/share/vm/prims/jvmtiEnvThreadState.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiEnvThreadState.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -190,12 +190,8 @@
 
 
 JvmtiFramePops* JvmtiEnvThreadState::get_frame_pops() {
-#ifdef ASSERT
-  uint32_t debug_bits = 0;
-#endif
-  assert(get_thread() == Thread::current() || JvmtiEnv::is_thread_fully_suspended(get_thread(), false, &debug_bits),
-         "frame pop data only accessible from same thread or while suspended");
-
+  assert(get_thread() == Thread::current() || SafepointSynchronize::is_at_safepoint(),
+         "frame pop data only accessible from same thread or at safepoint");
   if (_frame_pops == NULL) {
     _frame_pops = new JvmtiFramePops();
     assert(_frame_pops != NULL, "_frame_pops != NULL");
@@ -209,44 +205,32 @@
 }
 
 void JvmtiEnvThreadState::set_frame_pop(int frame_number) {
-#ifdef ASSERT
-  uint32_t debug_bits = 0;
-#endif
-  assert(get_thread() == Thread::current() || JvmtiEnv::is_thread_fully_suspended(get_thread(), false, &debug_bits),
-         "frame pop data only accessible from same thread or while suspended");
+  assert(get_thread() == Thread::current() || SafepointSynchronize::is_at_safepoint(),
+         "frame pop data only accessible from same thread or at safepoint");
   JvmtiFramePop fpop(frame_number);
   JvmtiEventController::set_frame_pop(this, fpop);
 }
 
 
 void JvmtiEnvThreadState::clear_frame_pop(int frame_number) {
-#ifdef ASSERT
-  uint32_t debug_bits = 0;
-#endif
-  assert(get_thread() == Thread::current() || JvmtiEnv::is_thread_fully_suspended(get_thread(), false, &debug_bits),
-         "frame pop data only accessible from same thread or while suspended");
+  assert(get_thread() == Thread::current() || SafepointSynchronize::is_at_safepoint(),
+         "frame pop data only accessible from same thread or at safepoint");
   JvmtiFramePop fpop(frame_number);
   JvmtiEventController::clear_frame_pop(this, fpop);
 }
 
 
 void JvmtiEnvThreadState::clear_to_frame_pop(int frame_number)  {
-#ifdef ASSERT
-  uint32_t debug_bits = 0;
-#endif
-  assert(get_thread() == Thread::current() || JvmtiEnv::is_thread_fully_suspended(get_thread(), false, &debug_bits),
-         "frame pop data only accessible from same thread or while suspended");
+  assert(get_thread() == Thread::current() || SafepointSynchronize::is_at_safepoint(),
+         "frame pop data only accessible from same thread or at safepoint");
   JvmtiFramePop fpop(frame_number);
   JvmtiEventController::clear_to_frame_pop(this, fpop);
 }
 
 
 bool JvmtiEnvThreadState::is_frame_pop(int cur_frame_number) {
-#ifdef ASSERT
-  uint32_t debug_bits = 0;
-#endif
-  assert(get_thread() == Thread::current() || JvmtiEnv::is_thread_fully_suspended(get_thread(), false, &debug_bits),
-         "frame pop data only accessible from same thread or while suspended");
+  assert(get_thread() == Thread::current() || SafepointSynchronize::is_at_safepoint(),
+         "frame pop data only accessible from same thread or at safepoint");
   if (!get_thread()->is_interp_only_mode() || _frame_pops == NULL) {
     return false;
   }
--- a/hotspot/src/share/vm/prims/jvmtiEventController.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiEventController.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -989,21 +989,21 @@
 
 void
 JvmtiEventController::set_frame_pop(JvmtiEnvThreadState *ets, JvmtiFramePop fpop) {
-  MutexLocker mu(JvmtiThreadState_lock);
+  MutexLockerEx mu(SafepointSynchronize::is_at_safepoint() ? NULL : JvmtiThreadState_lock);
   JvmtiEventControllerPrivate::set_frame_pop(ets, fpop);
 }
 
 
 void
 JvmtiEventController::clear_frame_pop(JvmtiEnvThreadState *ets, JvmtiFramePop fpop) {
-  MutexLocker mu(JvmtiThreadState_lock);
+  MutexLockerEx mu(SafepointSynchronize::is_at_safepoint() ? NULL : JvmtiThreadState_lock);
   JvmtiEventControllerPrivate::clear_frame_pop(ets, fpop);
 }
 
 
 void
 JvmtiEventController::clear_to_frame_pop(JvmtiEnvThreadState *ets, JvmtiFramePop fpop) {
-  MutexLocker mu(JvmtiThreadState_lock);
+  MutexLockerEx mu(SafepointSynchronize::is_at_safepoint() ? NULL : JvmtiThreadState_lock);
   JvmtiEventControllerPrivate::clear_to_frame_pop(ets, fpop);
 }
 
--- a/hotspot/src/share/vm/prims/jvmtiThreadState.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiThreadState.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -63,6 +63,7 @@
   _vm_object_alloc_event_collector = NULL;
   _the_class_for_redefinition_verification = NULL;
   _scratch_class_for_redefinition_verification = NULL;
+  _cur_stack_depth = UNKNOWN_STACK_DEPTH;
 
   // JVMTI ForceEarlyReturn support
   _pending_step_for_earlyret = false;
@@ -213,12 +214,9 @@
 
 // Helper routine used in several places
 int JvmtiThreadState::count_frames() {
-#ifdef ASSERT
-  uint32_t debug_bits = 0;
-#endif
-  assert(SafepointSynchronize::is_at_safepoint() ||
-         JvmtiEnv::is_thread_fully_suspended(get_thread(), false, &debug_bits),
-         "at safepoint or must be suspended");
+  guarantee(SafepointSynchronize::is_at_safepoint() ||
+    (JavaThread *)Thread::current() == get_thread(),
+    "must be current thread or at safepoint");
 
   if (!get_thread()->has_last_Java_frame()) return 0;  // no Java frames
 
@@ -243,15 +241,9 @@
 
 
 void JvmtiThreadState::invalidate_cur_stack_depth() {
-  Thread *cur = Thread::current();
-  uint32_t debug_bits = 0;
-
-  // The caller can be the VMThread at a safepoint, the current thread
-  // or the target thread must be suspended.
-  guarantee((cur->is_VM_thread() && SafepointSynchronize::is_at_safepoint()) ||
-    (JavaThread *)cur == get_thread() ||
-    JvmtiEnv::is_thread_fully_suspended(get_thread(), false, &debug_bits),
-    "sanity check");
+  guarantee(SafepointSynchronize::is_at_safepoint() ||
+    (JavaThread *)Thread::current() == get_thread(),
+    "must be current thread or at safepoint");
 
   _cur_stack_depth = UNKNOWN_STACK_DEPTH;
 }
@@ -280,10 +272,9 @@
 }
 
 int JvmtiThreadState::cur_stack_depth() {
-  uint32_t debug_bits = 0;
-  guarantee(JavaThread::current() == get_thread() ||
-    JvmtiEnv::is_thread_fully_suspended(get_thread(), false, &debug_bits),
-    "must be current thread or suspended");
+  guarantee(SafepointSynchronize::is_at_safepoint() ||
+    (JavaThread *)Thread::current() == get_thread(),
+    "must be current thread or at safepoint");
 
   if (!is_interp_only_mode() || _cur_stack_depth == UNKNOWN_STACK_DEPTH) {
     _cur_stack_depth = count_frames();
--- a/hotspot/src/share/vm/runtime/arguments.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/runtime/arguments.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1699,7 +1699,8 @@
       // HeapBaseMinAddress can be greater than default but not less than.
       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
-          if (PrintMiscellaneous && Verbose) {  // matches compressed oops printing flags
+          // matches compressed oops printing flags
+          if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
             jio_fprintf(defaultStream::error_stream(),
                         "HeapBaseMinAddress must be at least " UINTX_FORMAT
                         " (" UINTX_FORMAT "G) which is greater than value given "
@@ -2407,9 +2408,11 @@
 
   status &= verify_interval(NmethodSweepFraction, 1, ReservedCodeCacheSize/K, "NmethodSweepFraction");
   status &= verify_interval(NmethodSweepActivity, 0, 2000, "NmethodSweepActivity");
+  status &= verify_interval(CodeCacheMinBlockLength, 1, 100, "CodeCacheMinBlockLength");
+  status &= verify_interval(CodeCacheSegmentSize, 1, 1024, "CodeCacheSegmentSize");
 
   // TieredCompilation needs at least 2 compiler threads.
-  const int num_min_compiler_threads = (TieredCompilation) ? 2 : 1;
+  const int num_min_compiler_threads = (TieredCompilation && (TieredStopAtLevel >= CompLevel_full_optimization)) ? 2 : 1;
   status &=verify_min_value(CICompilerCount, num_min_compiler_threads, "CICompilerCount");
 
   return status;
--- a/hotspot/src/share/vm/runtime/globals.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/runtime/globals.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -535,6 +535,9 @@
   develop(bool, CleanChunkPoolAsync, falseInEmbedded,                       \
           "Clean the chunk pool asynchronously")                            \
                                                                             \
+  experimental(bool, AlwaysSafeConstructors, false,                         \
+          "Force safe construction, as if all fields are final.")           \
+                                                                            \
   /* Temporary: See 6948537 */                                              \
   experimental(bool, UseMemSetInBOT, true,                                  \
           "(Unstable) uses memset in BOT updates in GC code")               \
@@ -811,8 +814,8 @@
   product(bool, PrintOopAddress, false,                                     \
           "Always print the location of the oop")                           \
                                                                             \
-  notproduct(bool, VerifyCodeCacheOften, false,                             \
-          "Verify compiled-code cache often")                               \
+  notproduct(bool, VerifyCodeCache, false,                                  \
+          "Verify code cache on memory allocation/deallocation")            \
                                                                             \
   develop(bool, ZapDeadCompiledLocals, false,                               \
           "Zap dead locals in compiler frames")                             \
@@ -2984,7 +2987,8 @@
           "maximum number of nested recursive calls that are inlined")      \
                                                                             \
   develop(intx, MaxForceInlineLevel, 100,                                   \
-          "maximum number of nested @ForceInline calls that are inlined")   \
+          "maximum number of nested calls that are forced for inlining "    \
+          "(using CompilerOracle or marked w/ @ForceInline)")               \
                                                                             \
   product_pd(intx, InlineSmallCode,                                         \
           "Only inline already compiled methods if their code size is "     \
@@ -3292,8 +3296,8 @@
           "disable this feature")                                           \
                                                                             \
   /* code cache parameters */                                               \
-  /* ppc64 has large code-entry alignment. */                               \
-  develop(uintx, CodeCacheSegmentSize, 64 PPC64_ONLY(+64),                  \
+  /* ppc64/tiered compilation has large code-entry alignment. */            \
+  develop(uintx, CodeCacheSegmentSize, 64 PPC64_ONLY(+64) NOT_PPC64(TIERED_ONLY(+64)),\
           "Code cache segment size (in bytes) - smallest unit of "          \
           "allocation")                                                     \
                                                                             \
@@ -3795,8 +3799,8 @@
   experimental(bool, TrustFinalNonStaticFields, false,                      \
           "trust final non-static declarations for constant folding")       \
                                                                             \
-  experimental(bool, FoldStableValues, false,                               \
-          "Private flag to control optimizations for stable variables")     \
+  diagnostic(bool, FoldStableValues, true,                                  \
+          "Optimize loads from stable fields (marked w/ @Stable)")          \
                                                                             \
   develop(bool, TraceInvokeDynamic, false,                                  \
           "trace internal invoke dynamic operations")                       \
@@ -3864,6 +3868,9 @@
           "Allocation less than this value will be allocated "              \
           "using malloc. Larger allocations will use mmap.")                \
                                                                             \
+  experimental(bool, AlwaysAtomicAccesses, false,                           \
+          "Accesses to all variables should always be atomic")              \
+                                                                            \
   product(bool, EnableTracing, false,                                       \
           "Enable event-based tracing")                                     \
                                                                             \
--- a/hotspot/src/share/vm/runtime/thread.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/runtime/thread.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -910,7 +910,7 @@
               cur != VMOperationRequest_lock &&
               cur != VMOperationQueue_lock) ||
               cur->rank() == Mutex::special) {
-          warning("Thread holding lock at safepoint that vm can block on: %s", cur->name());
+          fatal(err_msg("Thread holding lock at safepoint that vm can block on: %s", cur->name()));
         }
       }
     }
--- a/hotspot/src/share/vm/runtime/timer.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/runtime/timer.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -194,7 +194,7 @@
         system_secs = system_time - _starting_system_time;
         real_secs = real_time - _starting_real_time;
 
-        _logfile->print(" [Times: user=%3.2f sys=%3.2f, real=%3.2f secs] ",
+        _logfile->print(" [Times: user=%3.2f sys=%3.2f real=%3.2f secs] ",
           user_secs, system_secs, real_secs);
 
       } else {
--- a/hotspot/src/share/vm/runtime/vmStructs.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/runtime/vmStructs.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -2336,6 +2336,12 @@
   /* ConstMethod anon-enum */                                             \
   /********************************/                                      \
                                                                           \
+  declare_constant(Method::_jfr_towrite)                                  \
+  declare_constant(Method::_caller_sensitive)                             \
+  declare_constant(Method::_force_inline)                                 \
+  declare_constant(Method::_dont_inline)                                  \
+  declare_constant(Method::_hidden)                                       \
+                                                                          \
   declare_constant(ConstMethod::_has_linenumber_table)                    \
   declare_constant(ConstMethod::_has_checked_exceptions)                  \
   declare_constant(ConstMethod::_has_localvariable_table)                 \
--- a/hotspot/src/share/vm/runtime/vm_operations.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/runtime/vm_operations.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,6 +74,8 @@
   template(PopulateDumpSharedSpace)               \
   template(JNIFunctionTableCopier)                \
   template(RedefineClasses)                       \
+  template(UpdateForPopTopFrame)                  \
+  template(SetFramePop)                           \
   template(GetOwnedMonitorInfo)                   \
   template(GetObjectMonitorUsage)                 \
   template(GetCurrentContendedMonitor)            \
--- a/hotspot/src/share/vm/shark/llvmHeaders.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/shark/llvmHeaders.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -36,21 +36,43 @@
 #endif
 
 #include <llvm/Analysis/Verifier.h>
+#include <llvm/ExecutionEngine/ExecutionEngine.h>
+
+// includes specific to each version
+#if SHARK_LLVM_VERSION <= 31
+#include <llvm/Support/IRBuilder.h>
+#include <llvm/Type.h>
 #include <llvm/Argument.h>
 #include <llvm/Constants.h>
 #include <llvm/DerivedTypes.h>
-#include <llvm/ExecutionEngine/ExecutionEngine.h>
 #include <llvm/Instructions.h>
 #include <llvm/LLVMContext.h>
 #include <llvm/Module.h>
-#if SHARK_LLVM_VERSION <= 31
-#include <llvm/Support/IRBuilder.h>
-#else
+#elif SHARK_LLVM_VERSION <= 32
 #include <llvm/IRBuilder.h>
+#include <llvm/Type.h>
+#include <llvm/Argument.h>
+#include <llvm/Constants.h>
+#include <llvm/DerivedTypes.h>
+#include <llvm/Instructions.h>
+#include <llvm/LLVMContext.h>
+#include <llvm/Module.h>
+#else // SHARK_LLVM_VERSION <= 34
+#include <llvm/IR/IRBuilder.h>
+#include <llvm/IR/Argument.h>
+#include <llvm/IR/Constants.h>
+#include <llvm/IR/DerivedTypes.h>
+#include <llvm/ExecutionEngine/ExecutionEngine.h>
+#include <llvm/IR/Instructions.h>
+#include <llvm/IR/LLVMContext.h>
+#include <llvm/IR/Module.h>
+#include <llvm/ADT/StringRef.h>
+#include <llvm/IR/Type.h>
 #endif
+
+// common includes
 #include <llvm/Support/Threading.h>
 #include <llvm/Support/TargetSelect.h>
-#include <llvm/Type.h>
 #include <llvm/ExecutionEngine/JITMemoryManager.h>
 #include <llvm/Support/CommandLine.h>
 #include <llvm/ExecutionEngine/MCJIT.h>
--- a/hotspot/src/share/vm/shark/sharkCompiler.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/shark/sharkCompiler.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -364,3 +364,7 @@
   *(dst++) = '\0';
   return buf;
 }
+
+void SharkCompiler::print_timers() {
+  // do nothing
+}
--- a/hotspot/src/share/vm/shark/sharkCompiler.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/shark/sharkCompiler.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -56,6 +56,9 @@
   // Compile a normal (bytecode) method and install it in the VM
   void compile_method(ciEnv* env, ciMethod* target, int entry_bci);
 
+  // Print compilation timers and statistics
+  void print_timers();
+
   // Generate a wrapper for a native (JNI) method
   nmethod* generate_native_wrapper(MacroAssembler* masm,
                                    methodHandle    target,
--- a/hotspot/src/share/vm/shark/sharkInliner.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/shark/sharkInliner.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -744,6 +744,10 @@
 }
 
 bool SharkInliner::attempt_inline(ciMethod *target, SharkState *state) {
+  if (!Inline) {
+    return false;
+  }
+
   if (SharkIntrinsics::is_intrinsic(target)) {
     SharkIntrinsics::inline_intrinsic(target, state);
     return true;
--- a/hotspot/src/share/vm/shark/sharkMemoryManager.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/shark/sharkMemoryManager.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -59,18 +59,6 @@
     entry->set_code_limit(FunctionEnd);
 }
 
-unsigned char* SharkMemoryManager::startExceptionTable(const Function* F,
-                                                       uintptr_t& ActualSize) {
-  return mm()->startExceptionTable(F, ActualSize);
-}
-
-void SharkMemoryManager::endExceptionTable(const Function* F,
-                                           unsigned char* TableStart,
-                                           unsigned char* TableEnd,
-                                           unsigned char* FrameRegister) {
-  mm()->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
-}
-
 void SharkMemoryManager::setMemoryWritable() {
   mm()->setMemoryWritable();
 }
@@ -79,10 +67,6 @@
   mm()->setMemoryExecutable();
 }
 
-void SharkMemoryManager::deallocateExceptionTable(void *ptr) {
-  mm()->deallocateExceptionTable(ptr);
-}
-
 void SharkMemoryManager::deallocateFunctionBody(void *ptr) {
   mm()->deallocateFunctionBody(ptr);
 }
@@ -96,6 +80,17 @@
   return mm()->getPointerToNamedFunction(Name, AbortOnFailure);
 }
 
+void SharkMemoryManager::setPoisonMemory(bool poison) {
+  mm()->setPoisonMemory(poison);
+}
+
+unsigned char *SharkMemoryManager::allocateSpace(intptr_t Size,
+                                                 unsigned int Alignment) {
+  return mm()->allocateSpace(Size, Alignment);
+}
+
+#if SHARK_LLVM_VERSION <= 32
+
 uint8_t* SharkMemoryManager::allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID) {
   return mm()->allocateCodeSection(Size, Alignment, SectionID);
 }
@@ -104,11 +99,34 @@
   return mm()->allocateDataSection(Size, Alignment, SectionID);
 }
 
-void SharkMemoryManager::setPoisonMemory(bool poison) {
-  mm()->setPoisonMemory(poison);
+void SharkMemoryManager::deallocateExceptionTable(void *ptr) {
+  mm()->deallocateExceptionTable(ptr);
+}
+
+unsigned char* SharkMemoryManager::startExceptionTable(const Function* F,
+                                                       uintptr_t& ActualSize) {
+  return mm()->startExceptionTable(F, ActualSize);
+}
+
+void SharkMemoryManager::endExceptionTable(const Function* F,
+                                           unsigned char* TableStart,
+                                           unsigned char* TableEnd,
+                                           unsigned char* FrameRegister) {
+  mm()->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
 }
 
-unsigned char *SharkMemoryManager::allocateSpace(intptr_t Size,
-                                                 unsigned int Alignment) {
-  return mm()->allocateSpace(Size, Alignment);
+#else
+
+uint8_t *SharkMemoryManager::allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName) {
+    return mm()->allocateCodeSection(Size, Alignment, SectionID, SectionName);
 }
+
+uint8_t* SharkMemoryManager::allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool IsReadOnly) {
+  return mm()->allocateDataSection(Size, Alignment, SectionID, SectionName, IsReadOnly);
+}
+
+bool SharkMemoryManager::finalizeMemory(std::string *ErrMsg) {
+    return mm()->finalizeMemory(ErrMsg);
+}
+
+#endif
--- a/hotspot/src/share/vm/shark/sharkMemoryManager.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/shark/sharkMemoryManager.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -69,23 +69,32 @@
   void endFunctionBody(const llvm::Function* F,
                        unsigned char* FunctionStart,
                        unsigned char* FunctionEnd);
-  unsigned char* startExceptionTable(const llvm::Function* F,
-                                     uintptr_t& ActualSize);
-  void endExceptionTable(const llvm::Function* F,
-                         unsigned char* TableStart,
-                         unsigned char* TableEnd,
-                         unsigned char* FrameRegister);
+
   void *getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure = true);
-  uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID);
-  uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID);
   void setPoisonMemory(bool);
   uint8_t* allocateGlobal(uintptr_t, unsigned int);
   void setMemoryWritable();
   void setMemoryExecutable();
-  void deallocateExceptionTable(void *ptr);
   void deallocateFunctionBody(void *ptr);
   unsigned char *allocateSpace(intptr_t Size,
                                unsigned int Alignment);
+
+#if SHARK_LLVM_VERSION <= 32
+uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID);
+uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID);
+unsigned char* startExceptionTable(const llvm::Function* F,
+                                   uintptr_t& ActualSize);
+void deallocateExceptionTable(void *ptr);
+void endExceptionTable(const llvm::Function* F,
+                       unsigned char* TableStart,
+                       unsigned char* TableEnd,
+                       unsigned char* FrameRegister);
+#else
+uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, llvm::StringRef SectionName);
+uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, llvm::StringRef SectionName, bool IsReadOnly);
+bool finalizeMemory(std::string *ErrMsg = 0);
+#endif
+
 };
 
 #endif // SHARE_VM_SHARK_SHARKMEMORYMANAGER_HPP
--- a/hotspot/src/share/vm/utilities/elfFile.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/utilities/elfFile.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -140,7 +140,7 @@
       }
     }
 
-#if defined(PPC64)
+#if defined(PPC64) && !defined(ABI_ELFv2)
     // Now read the .opd section wich contains the PPC64 function descriptor table.
     // The .opd section is only available on PPC64 (see for example:
     // http://refspecs.linuxfoundation.org/LSB_3.1.1/LSB-Core-PPC64/LSB-Core-PPC64/specialsections.html)
--- a/hotspot/src/share/vm/utilities/hashtable.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/utilities/hashtable.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -25,7 +25,6 @@
 #include "precompiled.hpp"
 #include "classfile/altHashing.hpp"
 #include "classfile/javaClasses.hpp"
-#include "code/dependencies.hpp"
 #include "memory/allocation.inline.hpp"
 #include "memory/filemap.hpp"
 #include "memory/resourceArea.hpp"
@@ -353,116 +352,6 @@
 #endif
 
 
-template<class T, class M> GenericHashtable<T, M>::GenericHashtable(int size, bool C_heap, MEMFLAGS memflag) {
-  assert(size > 0, " Invalid hashtable size");
-  _size    = size;
-  _C_heap  = C_heap;
-  _memflag = memflag;
-  // Perform subtype-specific resource allocation
-  _items = (C_heap) ?  NEW_C_HEAP_ARRAY(T*, size, memflag) : NEW_RESOURCE_ARRAY(T*, size);
-  memset(_items, 0, sizeof(T*) * size);
-
-  DEBUG_ONLY(_num_items = 0;)
-}
-
-template<class T, class M> GenericHashtable<T, M>::~GenericHashtable() {
-  if (on_C_heap()) {
-    // Check backing array
-    for (int i = 0; i < size(); i++) {
-      T* item = head(i);
-      // Delete all items in linked list
-      while (item != NULL) {
-        T* next_item = item->next();
-        delete item;
-        DEBUG_ONLY(_num_items--);
-        item = next_item;
-      }
-    }
-    FREE_C_HEAP_ARRAY(T*, _items, _memflag);
-    _items = NULL;
-    assert (_num_items == 0, "Not all memory released");
-  }
-}
-
-/**
- * Return a pointer to the item 'I' that is stored in the hashtable for
- * which match_item->equals(I) == true. If no such item is found, NULL
- * is returned.
- */
-template<class T, class F> T* GenericHashtable<T, F>::contains(T* match_item) {
-  if (match_item != NULL) {
-    int idx = index(match_item);
-    return contains_impl(match_item, idx);
-  }
-  return NULL;
-}
-
-/**
- * Add item to the hashtable. Return 'true' if the item was added
- * and false otherwise.
- */
-template<class T, class F> bool GenericHashtable<T, F>::add(T* item) {
-  if (item != NULL) {
-    int idx = index(item);
-    T* found_item = contains_impl(item, idx);
-    if (found_item == NULL) {
-      T* list_head = head(idx);
-      item->set_next(list_head);
-      item->set_prev(NULL);
-
-      if (list_head != NULL) {
-        list_head->set_prev(item);
-      }
-      set_head(item, idx);
-      DEBUG_ONLY(_num_items++);
-      return true;
-    }
-  }
-  return false;
-}
-
-/**
- * Removes an item 'I' from the hashtable, if present. 'I' is removed, if
- * match_item->equals(I) == true. Removing an item from the hashtable does
- * not free memory.
- */
-template<class T, class F> T* GenericHashtable<T, F>::remove(T* match_item) {
-  if (match_item != NULL) {
-    int idx = index(match_item);
-    T* found_item = contains_impl(match_item, idx);
-    if (found_item != NULL) {
-      // Remove item from linked list
-      T* prev = found_item->prev();
-      T* next = found_item->next();
-      if (prev != NULL) {
-        prev->set_next(next);
-      } else {
-        set_head(next, idx);
-      }
-      if (next != NULL) {
-        next->set_prev(prev);
-      }
-
-      DEBUG_ONLY(_num_items--);
-      return found_item;
-    }
-  }
-  return NULL;
-}
-
-
-template<class T, class F> T* GenericHashtable<T, F>::contains_impl(T* item, int idx) {
-  T* current_item = head(idx);
-  while (current_item != NULL) {
-    if (current_item->equals(item)) {
-      return current_item;
-    }
-    current_item = current_item->next();
-  }
-  return NULL;
-}
-
-
 // Explicitly instantiate these types
 template class Hashtable<ConstantPool*, mtClass>;
 template class Hashtable<Symbol*, mtSymbol>;
@@ -482,5 +371,3 @@
 template class BasicHashtable<mtSymbol>;
 template class BasicHashtable<mtCode>;
 template class BasicHashtable<mtInternal>;
-
-template class GenericHashtable<DependencySignature, ResourceObj>;
--- a/hotspot/src/share/vm/utilities/hashtable.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/utilities/hashtable.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -327,86 +327,4 @@
   }
 };
 
-
-/*
- * Usage of GenericHashtable:
- *
- * class X : public GenericHashtableEntry<X, ResourceObj> {
- *
- *   // Implement virtual functions in class X
- *   bool      equals(X* sig) const;
- *   uintptr_t hash()         const;
- * };
- *
- * void foo() {
- *   GenericHashtable<X, ResourceObj>* table = new GenericHashtable<X, ResourceObj>(11027, false);
- *
- *   X* elem = new X();
- *   table->add(elem);
- *   table->contains(elem);
- * }
- *
- * You can choose other allocation types as well. For example, to store the hashtable to a
- * particular region (CHeapObj<type>) simply replace ResourceObj with the desired type:
- *
- * class X : public GenericHashtableEntry<X, CHeapObj<mtCode> > { ... };
- *
- * To make the destructor (and remove) of the hashtable work:
- * 1) override the delete operator of X
- * 2) provide a destructor of the X
- *
- * You may also find it convenient to override the new operator.
- *
- * If you use this templates do not forget to add an explicit initialization
- * (at the end of hashtable.cpp).
- *
- *  template class GenericHashtable<X, ResourceObj>;
- */
-template <class T, class M> class GenericHashtableEntry : public M {
- private:
-  T* _next;
-  T* _prev;
- public:
-  // Must be implemented by subclass.
-  virtual uintptr_t key()            const = 0;
-  virtual bool      equals(T* other) const = 0;
-
-  T* next() const        { return _next; }
-  T* prev() const        { return _prev; }
-  void set_next(T* item) { _next = item; }
-  void set_prev(T* item) { _prev = item; }
-
-  // Constructor and destructor
-  GenericHashtableEntry() : _next(NULL), _prev(NULL) { };
-  virtual ~GenericHashtableEntry() {};
-};
-
-template <class T, class M> class GenericHashtable : public M {
- private:
-  T**      _items;
-  int      _size;
-  bool     _C_heap;
-  MEMFLAGS _memflag;
-
-  // Accessor methods
-  T*   head    (int idx) const    { return _items[idx]; }
-  void set_head(T* item, int idx) { _items[idx] = item; }
-  int  index   (T* item)          { assert(item != NULL, "missing null check"); return item->key() % size(); }
-
-  // Helper function
-  T* contains_impl(T* item, int idx);
-
-  DEBUG_ONLY(int _num_items;)
- public:
-  GenericHashtable(int size, bool C_heap = false, MEMFLAGS memflag = mtNone);
-  ~GenericHashtable();
-  T*   contains(T* match_item);
-  T*   remove  (T* match_item);
-  bool add     (T* item);
-
-
-  bool on_C_heap() const { return _C_heap; }
-  int  size()      const { return _size; }
-};
-
 #endif // SHARE_VM_UTILITIES_HASHTABLE_HPP
--- a/hotspot/src/share/vm/utilities/resourceHash.hpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/utilities/resourceHash.hpp	Wed Jul 05 19:33:51 2017 +0200
@@ -105,14 +105,20 @@
     }
   }
 
-  // Inserts or replaces a value in the table
-  void put(K const& key, V const& value) {
+ /**
+  * Inserts or replaces a value in the table.
+  * @return: true:  if a new item is added
+  *          false: if the item already existed and the value is updated
+  */
+  bool put(K const& key, V const& value) {
     unsigned hv = HASH(key);
     Node** ptr = lookup_node(hv, key);
     if (*ptr != NULL) {
       (*ptr)->_value = value;
+      return false;
     } else {
       *ptr = new Node(hv, key, value);
+      return true;
     }
   }
 
--- a/hotspot/src/share/vm/utilities/vmError.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/src/share/vm/utilities/vmError.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -592,13 +592,24 @@
              st->cr();
              // Compiled code may use EBP register on x86 so it looks like
              // non-walkable C frame. Use frame.sender() for java frames.
-             if (_thread && _thread->is_Java_thread() && fr.is_java_frame()) {
-               RegisterMap map((JavaThread*)_thread, false); // No update
-               fr = fr.sender(&map);
-               continue;
+             if (_thread && _thread->is_Java_thread()) {
+               // Catch very first native frame by using stack address.
+               // For JavaThread stack_base and stack_size should be set.
+               if (!_thread->on_local_stack((address)(fr.sender_sp() + 1))) {
+                 break;
+               }
+               if (fr.is_java_frame()) {
+                 RegisterMap map((JavaThread*)_thread, false); // No update
+                 fr = fr.sender(&map);
+               } else {
+                 fr = os::get_sender_for_C_frame(&fr);
+               }
+             } else {
+               // is_first_C_frame() does only simple checks for frame pointer,
+               // it will pass if java compiled code has a pointer in EBP.
+               if (os::is_first_C_frame(&fr)) break;
+               fr = os::get_sender_for_C_frame(&fr);
              }
-             if (os::is_first_C_frame(&fr)) break;
-             fr = os::get_sender_for_C_frame(&fr);
           }
 
           if (count > StackPrintLimit) {
--- a/hotspot/test/TEST.groups	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/TEST.groups	Wed Jul 05 19:33:51 2017 +0200
@@ -130,7 +130,9 @@
   gc/arguments/TestG1HeapRegionSize.java \
   gc/metaspace/TestMetaspaceMemoryPool.java \
   runtime/InternalApi/ThreadCpuTimesDeadlock.java \
-  serviceability/threads/TestFalseDeadLock.java
+  serviceability/threads/TestFalseDeadLock.java \
+  compiler/tiered/NonTieredLevelsTest.java \
+  compiler/tiered/TieredLevelsTest.java
 
 # Compact 2 adds full VM tests
 compact2 = \
--- a/hotspot/test/compiler/ciReplay/TestVM.sh	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/ciReplay/TestVM.sh	Wed Jul 05 19:33:51 2017 +0200
@@ -78,8 +78,8 @@
         positive_test `expr $stop_level + 50` "TIERED LEVEL $stop_level :: REPLAY" \
                 "-XX:TieredStopAtLevel=$stop_level"
         stop_level=`expr $stop_level + 1`
+        cleanup
     done
-    cleanup
 fi
 
 echo TEST PASSED
--- a/hotspot/test/compiler/ciReplay/common.sh	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/ciReplay/common.sh	Wed Jul 05 19:33:51 2017 +0200
@@ -99,14 +99,13 @@
 # $2 - non-tiered comp_level 
 nontiered_tests() {
     level=`grep "^compile " $replay_data | awk '{print $6}'`
-    # is level available in non-tiere
+    # is level available in non-tiered
     if [ "$level" -eq $2 ]
     then
         positive_test $1 "NON-TIERED :: AVAILABLE COMP_LEVEL" \
                 -XX:-TieredCompilation
     else
         negative_test `expr $1 + 1` "NON-TIERED :: UNAVAILABLE COMP_LEVEL" \
-        negative_test `expr $1 + 1` "NON-TIERED :: UNAVAILABLE COMP_LEVEL" \
                 -XX:-TieredCompilation
     fi
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/codegen/BMI1.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,301 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8031321
+ * @summary Support BMI1 instructions on x86/x64
+ * @run main/othervm -Xbatch -XX:-TieredCompilation -XX:CompileCommand=compileonly,BMITests.* BMI1
+ *
+ */
+
+class MemI {
+  public int x;
+  public MemI(int x) { this.x = x; }
+}
+
+class MemL {
+  public long x;
+  public MemL(long x) { this.x = x; }
+}
+
+class BMITests {
+  static int andnl(int src1, int src2) {
+    return ~src1 & src2;
+  }
+  static long andnq(long src1, long src2) {
+    return ~src1 & src2;
+  }
+  static int andnl(int src1, MemI src2) {
+    return ~src1 & src2.x;
+  }
+  static long andnq(long src1, MemL src2) {
+    return ~src1 & src2.x;
+  }
+  static int blsil(int src1) {
+    return src1 & -src1;
+  }
+  static long blsiq(long src1) {
+    return src1 & -src1;
+  }
+  static int blsil(MemI src1) {
+    return src1.x & -src1.x;
+  }
+  static long blsiq(MemL src1) {
+    return src1.x & -src1.x;
+  }
+  static int blsmskl(int src1) {
+    return (src1 - 1) ^ src1;
+  }
+  static long blsmskq(long src1) {
+    return (src1 - 1) ^ src1;
+  }
+  static int blsmskl(MemI src1) {
+    return (src1.x - 1) ^ src1.x;
+  }
+  static long blsmskq(MemL src1) {
+    return (src1.x - 1) ^ src1.x;
+  }
+  static int blsrl(int src1) {
+    return (src1 - 1) & src1;
+  }
+  static long blsrq(long src1) {
+    return (src1 - 1) & src1;
+  }
+  static int blsrl(MemI src1) {
+    return (src1.x - 1) & src1.x;
+  }
+  static long blsrq(MemL src1) {
+    return (src1.x - 1) & src1.x;
+  }
+  static int lzcntl(int src1) {
+    return Integer.numberOfLeadingZeros(src1);
+  }
+  static int lzcntq(long src1) {
+    return Long.numberOfLeadingZeros(src1);
+  }
+  static int tzcntl(int src1) {
+    return Integer.numberOfTrailingZeros(src1);
+  }
+  static int tzcntq(long src1) {
+    return Long.numberOfTrailingZeros(src1);
+  }
+}
+
+public class BMI1 {
+  private final static int ITERATIONS = 1000000;
+
+  public static void main(String[] args) {
+    int ix = 0x01234567;
+    int iy = 0x89abcdef;
+    MemI imy = new MemI(iy);
+    long lx = 0x0123456701234567L;
+    long ly = 0x89abcdef89abcdefL;
+    MemL lmy = new MemL(ly);
+
+    { // match(Set dst (AndI (XorI src1 minus_1) src2))
+      int z = BMITests.andnl(ix, iy);
+      for (int i = 0; i < ITERATIONS; i++) {
+        int ii = BMITests.andnl(ix, iy);
+        if (ii != z) {
+          throw new Error("andnl with register failed");
+        }
+      }
+    }
+    { // match(Set dst (AndL (XorL src1 minus_1) src2))
+      long z = BMITests.andnq(lx, ly);
+      for (int i = 0; i < ITERATIONS; i++) {
+        long ll = BMITests.andnq(lx, ly);
+        if (ll != z) {
+          throw new Error("andnq with register failed");
+        }
+      }
+    }
+    { // match(Set dst (AndI (XorI src1 minus_1) (LoadI src2)))
+      int z = BMITests.andnl(ix, imy);
+      for (int i = 0; i < ITERATIONS; i++) {
+        int ii = BMITests.andnl(ix, imy);
+        if (ii != z) {
+          throw new Error("andnl with memory failed");
+        }
+      }
+    }
+    { // match(Set dst (AndL (XorL src1 minus_1) (LoadL src2)))
+      long z = BMITests.andnq(lx, lmy);
+      for (int i = 0; i < ITERATIONS; i++) {
+        long ll = BMITests.andnq(lx, lmy);
+        if (ll != z) {
+          throw new Error("andnq with memory failed");
+        }
+      }
+    }
+    { // match(Set dst (AndI (SubI imm_zero src) src))
+      int z = BMITests.blsil(ix);
+      for (int i = 0; i < ITERATIONS; i++) {
+        int ii = BMITests.blsil(ix);
+        if (ii != z) {
+          throw new Error("blsil with register failed");
+        }
+      }
+    }
+    { // match(Set dst (AndL (SubL imm_zero src) src))
+      long z = BMITests.blsiq(lx);
+      for (int i = 0; i < ITERATIONS; i++) {
+        long ll = BMITests.blsiq(lx);
+        if (ll != z) {
+          throw new Error("blsiq with register failed");
+        }
+      }
+    }
+    { // match(Set dst (AndI (SubI imm_zero (LoadI src) ) (LoadI src) ))
+      int z = BMITests.blsil(imy);
+      for (int i = 0; i < ITERATIONS; i++) {
+        int ii = BMITests.blsil(imy);
+        if (ii != z) {
+          throw new Error("blsil with memory failed");
+        }
+      }
+    }
+    { // match(Set dst (AndL (SubL imm_zero (LoadL src) ) (LoadL src) ))
+      long z = BMITests.blsiq(lmy);
+      for (int i = 0; i < ITERATIONS; i++) {
+        long ll = BMITests.blsiq(lmy);
+        if (ll != z) {
+          throw new Error("blsiq with memory failed");
+        }
+      }
+    }
+
+    { // match(Set dst (XorI (AddI src minus_1) src))
+      int z = BMITests.blsmskl(ix);
+      for (int i = 0; i < ITERATIONS; i++) {
+        int ii = BMITests.blsmskl(ix);
+        if (ii != z) {
+          throw new Error("blsmskl with register failed");
+        }
+      }
+    }
+    { // match(Set dst (XorL (AddL src minus_1) src))
+      long z = BMITests.blsmskq(lx);
+      for (int i = 0; i < ITERATIONS; i++) {
+        long ll = BMITests.blsmskq(lx);
+        if (ll != z) {
+          throw new Error("blsmskq with register failed");
+        }
+      }
+    }
+    { // match(Set dst (XorI (AddI (LoadI src) minus_1) (LoadI src) ) )
+      int z = BMITests.blsmskl(imy);
+      for (int i = 0; i < ITERATIONS; i++) {
+        int ii = BMITests.blsmskl(imy);
+        if (ii != z) {
+          throw new Error("blsmskl with memory failed");
+        }
+      }
+    }
+    {  // match(Set dst (XorL (AddL (LoadL src) minus_1) (LoadL src) ) )
+      long z = BMITests.blsmskq(lmy);
+      for (int i = 0; i < ITERATIONS; i++) {
+        long ll = BMITests.blsmskq(lmy);
+        if (ll != z) {
+          throw new Error("blsmskq with memory failed");
+        }
+      }
+    }
+
+    { //  match(Set dst (AndI (AddI src minus_1) src) )
+      int z = BMITests.blsrl(ix);
+      for (int i = 0; i < ITERATIONS; i++) {
+        int ii = BMITests.blsrl(ix);
+        if (ii != z) {
+          throw new Error("blsrl with register failed");
+        }
+      }
+    }
+    { // match(Set dst (AndL (AddL src minus_1) src) )
+      long z = BMITests.blsrq(lx);
+      for (int i = 0; i < ITERATIONS; i++) {
+        long ll = BMITests.blsrq(lx);
+        if (ll != z) {
+          throw new Error("blsrq with register failed");
+        }
+      }
+    }
+    { // match(Set dst (AndI (AddI (LoadI src) minus_1) (LoadI src) ) )
+      int z = BMITests.blsrl(imy);
+      for (int i = 0; i < ITERATIONS; i++) {
+        int ii = BMITests.blsrl(imy);
+        if (ii != z) {
+          throw new Error("blsrl with memory failed");
+        }
+      }
+    }
+    { // match(Set dst (AndL (AddL (LoadL src) minus_1) (LoadL src)) )
+      long z = BMITests.blsrq(lmy);
+      for (int i = 0; i < ITERATIONS; i++) {
+        long ll = BMITests.blsrq(lmy);
+        if (ll != z) {
+          throw new Error("blsrq with memory failed");
+        }
+      }
+    }
+
+    {
+      int z = BMITests.lzcntl(ix);
+      for (int i = 0; i < ITERATIONS; i++) {
+        int ii = BMITests.lzcntl(ix);
+        if (ii != z) {
+          throw new Error("lzcntl failed");
+        }
+      }
+    }
+    {
+      int z = BMITests.lzcntq(lx);
+      for (int i = 0; i < ITERATIONS; i++) {
+        int ii = BMITests.lzcntq(lx);
+        if (ii != z) {
+          throw new Error("lzcntq failed");
+        }
+      }
+    }
+
+    {
+      int z = BMITests.tzcntl(ix);
+      for (int i = 0; i < ITERATIONS; i++) {
+        int ii = BMITests.tzcntl(ix);
+        if (ii != z) {
+          throw new Error("tzcntl failed");
+        }
+      }
+    }
+    {
+      int z = BMITests.tzcntq(lx);
+      for (int i = 0; i < ITERATIONS; i++) {
+        int ii = BMITests.tzcntq(lx);
+        if (ii != z) {
+          throw new Error("tzcntq failed");
+        }
+      }
+    }
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/inlining/InlineDefaultMethod1.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8036100
+ * @summary Default method returns true for a while, and then returns false
+ * @run main/othervm -Xcomp -XX:CompileOnly=InlineDefaultMethod1::test
+ *                   -XX:CompileOnly=I1::m -XX:CompileOnly=I2::m
+ *                   InlineDefaultMethod1
+ */
+interface I1 {
+    default public int m() { return 0; }
+}
+
+interface I2 extends I1 {
+    default public int m() { return 1; }
+}
+
+abstract class A implements I1 {
+}
+
+class B extends A implements I2 {
+}
+
+public class InlineDefaultMethod1 {
+    public static void test(A obj) {
+        int id = obj.m();
+        if (id != 1) {
+            throw new AssertionError("Called wrong method: 1 != "+id);
+        }
+    }
+
+    public static void main(String[] args) throws InterruptedException {
+        test(new B());
+        System.out.println("TEST PASSED");
+    }
+}
--- a/hotspot/test/compiler/membars/DekkerTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/membars/DekkerTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -25,9 +25,9 @@
  * @test
  * @bug 8007898
  * @summary Incorrect optimization of Memory Barriers in Matcher::post_store_load_barrier().
- * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:CICompilerCount=1 -XX:+StressGCM -XX:+StressLCM DekkerTest
- * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:CICompilerCount=1 -XX:+StressGCM -XX:+StressLCM DekkerTest
- * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:CICompilerCount=1 -XX:+StressGCM -XX:+StressLCM DekkerTest
+ * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:CICompilerCount=1 -XX:-TieredCompilation -XX:+StressGCM -XX:+StressLCM DekkerTest
+ * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:CICompilerCount=1 -XX:-TieredCompilation -XX:+StressGCM -XX:+StressLCM DekkerTest
+ * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:CICompilerCount=1 -XX:-TieredCompilation -XX:+StressGCM -XX:+StressLCM DekkerTest
  * @author Martin Doerr martin DOT doerr AT sap DOT com
  *
  * Run 3 times since the failure is intermittent.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/stable/TestStableBoolean.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,627 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 TestStableBoolean
+ * @summary tests on stable fields and arrays
+ * @library /testlibrary
+ * @compile -XDignore.symbol.file TestStableBoolean.java
+ * @run main ClassFileInstaller
+ *           java/lang/invoke/TestStableBoolean
+ *           java/lang/invoke/TestStableBoolean$BooleanStable
+ *           java/lang/invoke/TestStableBoolean$StaticBooleanStable
+ *           java/lang/invoke/TestStableBoolean$VolatileBooleanStable
+ *           java/lang/invoke/TestStableBoolean$BooleanArrayDim1
+ *           java/lang/invoke/TestStableBoolean$BooleanArrayDim2
+ *           java/lang/invoke/TestStableBoolean$BooleanArrayDim3
+ *           java/lang/invoke/TestStableBoolean$BooleanArrayDim4
+ *           java/lang/invoke/TestStableBoolean$ObjectArrayLowerDim0
+ *           java/lang/invoke/TestStableBoolean$ObjectArrayLowerDim1
+ *           java/lang/invoke/TestStableBoolean$NestedStableField
+ *           java/lang/invoke/TestStableBoolean$NestedStableField$A
+ *           java/lang/invoke/TestStableBoolean$NestedStableField1
+ *           java/lang/invoke/TestStableBoolean$NestedStableField1$A
+ *           java/lang/invoke/TestStableBoolean$NestedStableField2
+ *           java/lang/invoke/TestStableBoolean$NestedStableField2$A
+ *           java/lang/invoke/TestStableBoolean$NestedStableField3
+ *           java/lang/invoke/TestStableBoolean$NestedStableField3$A
+ *           java/lang/invoke/TestStableBoolean$DefaultValue
+ *           java/lang/invoke/TestStableBoolean$ObjectArrayLowerDim2
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableBoolean
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableBoolean
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableBoolean
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableBoolean
+ */
+package java.lang.invoke;
+
+import com.sun.management.HotSpotDiagnosticMXBean;
+import com.sun.management.VMOption;
+import sun.management.ManagementFactoryHelper;
+import java.lang.reflect.InvocationTargetException;
+
+public class TestStableBoolean {
+    public static void main(String[] args) throws Exception {
+        System.out.println("@Stable enabled: "+isStableEnabled);
+        System.out.println();
+
+        run(DefaultValue.class);
+        run(BooleanStable.class);
+        run(StaticBooleanStable.class);
+        run(VolatileBooleanStable.class);
+
+        // @Stable arrays: Dim 1-4
+        run(BooleanArrayDim1.class);
+        run(BooleanArrayDim2.class);
+        run(BooleanArrayDim3.class);
+        run(BooleanArrayDim4.class);
+
+        // @Stable Object field: dynamic arrays
+        run(ObjectArrayLowerDim0.class);
+        run(ObjectArrayLowerDim1.class);
+        run(ObjectArrayLowerDim2.class);
+
+        // Nested @Stable fields
+        run(NestedStableField.class);
+        run(NestedStableField1.class);
+        run(NestedStableField2.class);
+        run(NestedStableField3.class);
+
+        if (failed) {
+            throw new Error("TEST FAILED");
+        }
+    }
+
+    /* ==================================================== */
+
+    static class DefaultValue {
+        public @Stable boolean v;
+
+        public static final DefaultValue c = new DefaultValue();
+        public static boolean get() { return c.v; }
+        public static void test() throws Exception {
+                        boolean val1 = get();
+            c.v = true; boolean val2 = get();
+            assertEquals(val1, false);
+            assertEquals(val2, true);
+        }
+    }
+
+    /* ==================================================== */
+
+    static class BooleanStable {
+        public @Stable boolean v;
+
+        public static final BooleanStable c = new BooleanStable();
+        public static boolean get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = true; boolean val1 = get();
+            c.v = false; boolean val2 = get();
+            assertEquals(val1, true);
+            assertEquals(val2, (isStableEnabled ? true : false));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class StaticBooleanStable {
+        public static @Stable boolean v;
+
+        public static final StaticBooleanStable c = new StaticBooleanStable();
+        public static boolean get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = true; boolean val1 = get();
+            c.v = false; boolean val2 = get();
+            assertEquals(val1, true);
+            assertEquals(val2, (isStableEnabled ? true : false));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class VolatileBooleanStable {
+        public @Stable volatile boolean v;
+
+        public static final VolatileBooleanStable c = new VolatileBooleanStable();
+        public static boolean get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = true; boolean val1 = get();
+            c.v = false; boolean val2 = get();
+            assertEquals(val1, true);
+            assertEquals(val2, (isStableEnabled ? true : false));
+        }
+    }
+
+    /* ==================================================== */
+    // @Stable array == field && all components are stable
+
+    static class BooleanArrayDim1 {
+        public @Stable boolean[] v;
+
+        public static final BooleanArrayDim1 c = new BooleanArrayDim1();
+        public static boolean get() { return c.v[0]; }
+        public static boolean get1() { return c.v[10]; }
+        public static boolean[] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new boolean[1]; c.v[0] = true;  boolean val1 = get();
+                                      c.v[0] = false; boolean val2 = get();
+                assertEquals(val1, true);
+                assertEquals(val2, (isStableEnabled ? true : false));
+            }
+
+            {
+                c.v = new boolean[20]; c.v[10] = true;  boolean val1 = get1();
+                                       c.v[10] = false; boolean val2 = get1();
+                assertEquals(val1, true);
+                assertEquals(val2, (isStableEnabled ? true : false));
+            }
+
+            {
+                c.v = new boolean[1]; boolean[] val1 = get2();
+                c.v = new boolean[1]; boolean[] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class BooleanArrayDim2 {
+        public @Stable boolean[][] v;
+
+        public static final BooleanArrayDim2 c = new BooleanArrayDim2();
+        public static boolean get() { return c.v[0][0]; }
+        public static boolean[] get1() { return c.v[0]; }
+        public static boolean[][] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new boolean[1][1]; c.v[0][0] = true;  boolean val1 = get();
+                                         c.v[0][0] = false; boolean val2 = get();
+                assertEquals(val1, true);
+                assertEquals(val2, (isStableEnabled ? true : false));
+
+                c.v = new boolean[1][1]; c.v[0][0] = false; boolean val3 = get();
+                assertEquals(val3, (isStableEnabled ? true : false));
+
+                c.v[0] = new boolean[1]; c.v[0][0] = false; boolean val4 = get();
+                assertEquals(val4, (isStableEnabled ? true : false));
+            }
+
+            {
+                c.v = new boolean[1][1]; boolean[] val1 = get1();
+                c.v[0] = new boolean[1]; boolean[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new boolean[1][1]; boolean[][] val1 = get2();
+                c.v = new boolean[1][1]; boolean[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class BooleanArrayDim3 {
+        public @Stable boolean[][][] v;
+
+        public static final BooleanArrayDim3 c = new BooleanArrayDim3();
+        public static boolean get() { return c.v[0][0][0]; }
+        public static boolean[] get1() { return c.v[0][0]; }
+        public static boolean[][] get2() { return c.v[0]; }
+        public static boolean[][][] get3() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new boolean[1][1][1]; c.v[0][0][0] = true;  boolean val1 = get();
+                                            c.v[0][0][0] = false; boolean val2 = get();
+                assertEquals(val1, true);
+                assertEquals(val2, (isStableEnabled ? true : false));
+
+                c.v = new boolean[1][1][1]; c.v[0][0][0] = false; boolean val3 = get();
+                assertEquals(val3, (isStableEnabled ? true : false));
+
+                c.v[0] = new boolean[1][1]; c.v[0][0][0] = false; boolean val4 = get();
+                assertEquals(val4, (isStableEnabled ? true : false));
+
+                c.v[0][0] = new boolean[1]; c.v[0][0][0] = false; boolean val5 = get();
+                assertEquals(val5, (isStableEnabled ? true : false));
+            }
+
+            {
+                c.v = new boolean[1][1][1]; boolean[] val1 = get1();
+                c.v[0][0] = new boolean[1]; boolean[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new boolean[1][1][1]; boolean[][] val1 = get2();
+                c.v[0] = new boolean[1][1]; boolean[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new boolean[1][1][1]; boolean[][][] val1 = get3();
+                c.v = new boolean[1][1][1]; boolean[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class BooleanArrayDim4 {
+        public @Stable boolean[][][][] v;
+
+        public static final BooleanArrayDim4 c = new BooleanArrayDim4();
+        public static boolean get() { return c.v[0][0][0][0]; }
+        public static boolean[] get1() { return c.v[0][0][0]; }
+        public static boolean[][] get2() { return c.v[0][0]; }
+        public static boolean[][][] get3() { return c.v[0]; }
+        public static boolean[][][][] get4() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new boolean[1][1][1][1]; c.v[0][0][0][0] = true;  boolean val1 = get();
+                                               c.v[0][0][0][0] = false; boolean val2 = get();
+                assertEquals(val1, true);
+                assertEquals(val2, (isStableEnabled ? true : false));
+
+                c.v = new boolean[1][1][1][1]; c.v[0][0][0][0] = false; boolean val3 = get();
+                assertEquals(val3, (isStableEnabled ? true : false));
+
+                c.v[0] = new boolean[1][1][1]; c.v[0][0][0][0] = false; boolean val4 = get();
+                assertEquals(val4, (isStableEnabled ? true : false));
+
+                c.v[0][0] = new boolean[1][1]; c.v[0][0][0][0] = false; boolean val5 = get();
+                assertEquals(val5, (isStableEnabled ? true : false));
+
+                c.v[0][0][0] = new boolean[1]; c.v[0][0][0][0] = false; boolean val6 = get();
+                assertEquals(val6, (isStableEnabled ? true : false));
+            }
+
+            {
+                c.v = new boolean[1][1][1][1]; boolean[] val1 = get1();
+                c.v[0][0][0] = new boolean[1]; boolean[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new boolean[1][1][1][1]; boolean[][] val1 = get2();
+                c.v[0][0] = new boolean[1][1]; boolean[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new boolean[1][1][1][1]; boolean[][][] val1 = get3();
+                c.v[0] = new boolean[1][1][1]; boolean[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new boolean[1][1][1][1]; boolean[][][][] val1 = get4();
+                c.v = new boolean[1][1][1][1]; boolean[][][][] val2 = get4();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+        }
+    }
+
+    /* ==================================================== */
+    // Dynamic Dim is higher than static
+
+    static class ObjectArrayLowerDim0 {
+        public @Stable Object v;
+
+        public static final ObjectArrayLowerDim0 c = new ObjectArrayLowerDim0();
+        public static boolean get() { return ((boolean[])c.v)[0]; }
+        public static boolean[] get1() { return (boolean[])c.v; }
+        public static boolean[] get2() { return (boolean[])c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new boolean[1]; ((boolean[])c.v)[0] = true;  boolean val1 = get();
+                                      ((boolean[])c.v)[0] = false; boolean val2 = get();
+
+                assertEquals(val1, true);
+                assertEquals(val2, false);
+            }
+
+            {
+                c.v = new boolean[1]; boolean[] val1 = get1();
+                c.v = new boolean[1]; boolean[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim1 {
+        public @Stable Object[] v;
+
+        public static final ObjectArrayLowerDim1 c = new ObjectArrayLowerDim1();
+        public static boolean get() { return ((boolean[][])c.v)[0][0]; }
+        public static boolean[] get1() { return (boolean[])(c.v[0]); }
+        public static Object[] get2() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new boolean[1][1]; ((boolean[][])c.v)[0][0] = true;  boolean val1 = get();
+                                         ((boolean[][])c.v)[0][0] = false; boolean val2 = get();
+
+                assertEquals(val1, true);
+                assertEquals(val2, false);
+            }
+
+            {
+                c.v = new boolean[1][1]; c.v[0] = new boolean[0]; boolean[] val1 = get1();
+                                         c.v[0] = new boolean[0]; boolean[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new boolean[0][0]; Object[] val1 = get2();
+                c.v = new boolean[0][0]; Object[] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim2 {
+        public @Stable Object[][] v;
+
+        public static final ObjectArrayLowerDim2 c = new ObjectArrayLowerDim2();
+        public static boolean get() { return ((boolean[][][])c.v)[0][0][0]; }
+        public static boolean[] get1() { return (boolean[])(c.v[0][0]); }
+        public static boolean[][] get2() { return (boolean[][])(c.v[0]); }
+        public static Object[][] get3() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new boolean[1][1][1]; ((boolean[][][])c.v)[0][0][0] = true;  boolean val1 = get();
+                                            ((boolean[][][])c.v)[0][0][0] = false; boolean val2 = get();
+
+                assertEquals(val1, true);
+                assertEquals(val2, false);
+            }
+
+            {
+                c.v = new boolean[1][1][1]; c.v[0][0] = new boolean[0]; boolean[] val1 = get1();
+                                            c.v[0][0] = new boolean[0]; boolean[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new boolean[1][1][1]; c.v[0] = new boolean[0][0]; boolean[][] val1 = get2();
+                                            c.v[0] = new boolean[0][0]; boolean[][] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new boolean[0][0][0]; Object[][] val1 = get3();
+                c.v = new boolean[0][0][0]; Object[][] val2 = get3();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField {
+        static class A {
+            public @Stable boolean a;
+
+        }
+        public @Stable A v;
+
+        public static final NestedStableField c = new NestedStableField();
+        public static A get() { return c.v; }
+        public static boolean get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.a = true;  A val1 = get();
+                               c.v.a = false; A val2 = get();
+
+                assertEquals(val1.a, false);
+                assertEquals(val2.a, false);
+            }
+
+            {
+                c.v = new A(); c.v.a = true;  boolean val1 = get1();
+                               c.v.a = false; boolean val2 = get1();
+                c.v = new A(); c.v.a = false; boolean val3 = get1();
+
+                assertEquals(val1, true);
+                assertEquals(val2, (isStableEnabled ? true : false));
+                assertEquals(val3, (isStableEnabled ? true : false));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField1 {
+        static class A {
+            public @Stable boolean a;
+            public @Stable A next;
+        }
+        public @Stable A v;
+
+        public static final NestedStableField1 c = new NestedStableField1();
+        public static A get() { return c.v.next.next.next.next.next.next.next; }
+        public static boolean get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.next = new A(); c.v.next.next  = c.v;
+                               c.v.a = true;  c.v.next.a = true;  A val1 = get();
+                               c.v.a = false; c.v.next.a = false; A val2 = get();
+
+                assertEquals(val1.a, false);
+                assertEquals(val2.a, false);
+            }
+
+            {
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = true;  boolean val1 = get1();
+                               c.v.a = false; boolean val2 = get1();
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = false; boolean val3 = get1();
+
+                assertEquals(val1, true);
+                assertEquals(val2, (isStableEnabled ? true : false));
+                assertEquals(val3, (isStableEnabled ? true : false));
+            }
+        }
+    }
+   /* ==================================================== */
+
+    static class NestedStableField2 {
+        static class A {
+            public @Stable boolean a;
+            public @Stable A left;
+            public         A right;
+        }
+
+        public @Stable A v;
+
+        public static final NestedStableField2 c = new NestedStableField2();
+        public static boolean get() { return c.v.left.left.left.a; }
+        public static boolean get1() { return c.v.left.left.right.left.a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.left = c.v.right = c.v;
+                               c.v.a = true;  boolean val1 = get(); boolean val2 = get1();
+                               c.v.a = false; boolean val3 = get(); boolean val4 = get1();
+
+                assertEquals(val1, true);
+                assertEquals(val3, (isStableEnabled ? true : false));
+
+                assertEquals(val2, true);
+                assertEquals(val4, false);
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField3 {
+        static class A {
+            public @Stable boolean a;
+            public @Stable A[] left;
+            public         A[] right;
+        }
+
+        public @Stable A[] v;
+
+        public static final NestedStableField3 c = new NestedStableField3();
+        public static boolean get() { return c.v[0].left[1].left[0].left[1].a; }
+        public static boolean get1() { return c.v[1].left[0].left[1].right[0].left[1].a; }
+
+        public static void test() throws Exception {
+            {
+                A elem = new A();
+                c.v = new A[] { elem, elem }; c.v[0].left = c.v[0].right = c.v;
+                               elem.a = true;  boolean val1 = get(); boolean val2 = get1();
+                               elem.a = false; boolean val3 = get(); boolean val4 = get1();
+
+                assertEquals(val1, true);
+                assertEquals(val3, (isStableEnabled ? true : false));
+
+                assertEquals(val2, true);
+                assertEquals(val4, false);
+            }
+        }
+    }
+
+    /* ==================================================== */
+    // Auxiliary methods
+    static void assertEquals(boolean i, boolean j) { if (i != j)  throw new AssertionError(i + " != " + j); }
+    static void assertTrue(boolean b) { if (!b)  throw new AssertionError(); }
+
+    static boolean failed = false;
+
+    public static void run(Class<?> test) {
+        Throwable ex = null;
+        System.out.print(test.getName()+": ");
+        try {
+            test.getMethod("test").invoke(null);
+        } catch (InvocationTargetException e) {
+            ex = e.getCause();
+        } catch (Throwable e) {
+            ex = e;
+        } finally {
+            if (ex == null) {
+                System.out.println("PASSED");
+            } else {
+                failed = true;
+                System.out.println("FAILED");
+                ex.printStackTrace(System.out);
+            }
+        }
+    }
+
+    static final boolean isStableEnabled;
+    static {
+        HotSpotDiagnosticMXBean diagnostic
+                = ManagementFactoryHelper.getDiagnosticMXBean();
+        VMOption tmp;
+        try {
+            tmp = diagnostic.getVMOption("FoldStableValues");
+        } catch (IllegalArgumentException e) {
+            tmp = null;
+        }
+        isStableEnabled = (tmp == null ? false : Boolean.parseBoolean(tmp.getValue()));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/stable/TestStableByte.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,632 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 TestStableByte
+ * @summary tests on stable fields and arrays
+ * @library /testlibrary
+ * @compile -XDignore.symbol.file TestStableByte.java
+ * @run main ClassFileInstaller
+ *           java/lang/invoke/TestStableByte
+ *           java/lang/invoke/TestStableByte$ByteStable
+ *           java/lang/invoke/TestStableByte$StaticByteStable
+ *           java/lang/invoke/TestStableByte$VolatileByteStable
+ *           java/lang/invoke/TestStableByte$ByteArrayDim1
+ *           java/lang/invoke/TestStableByte$ByteArrayDim2
+ *           java/lang/invoke/TestStableByte$ByteArrayDim3
+ *           java/lang/invoke/TestStableByte$ByteArrayDim4
+ *           java/lang/invoke/TestStableByte$ObjectArrayLowerDim0
+ *           java/lang/invoke/TestStableByte$ObjectArrayLowerDim1
+ *           java/lang/invoke/TestStableByte$NestedStableField
+ *           java/lang/invoke/TestStableByte$NestedStableField$A
+ *           java/lang/invoke/TestStableByte$NestedStableField1
+ *           java/lang/invoke/TestStableByte$NestedStableField1$A
+ *           java/lang/invoke/TestStableByte$NestedStableField2
+ *           java/lang/invoke/TestStableByte$NestedStableField2$A
+ *           java/lang/invoke/TestStableByte$NestedStableField3
+ *           java/lang/invoke/TestStableByte$NestedStableField3$A
+ *           java/lang/invoke/TestStableByte$DefaultValue
+ *           java/lang/invoke/TestStableByte$ObjectArrayLowerDim2
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableByte
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableByte
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableByte
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableByte
+ */
+package java.lang.invoke;
+
+import com.sun.management.HotSpotDiagnosticMXBean;
+import com.sun.management.VMOption;
+import sun.management.ManagementFactoryHelper;
+import java.lang.reflect.InvocationTargetException;
+
+public class TestStableByte {
+    public static void main(String[] args) throws Exception {
+        System.out.println("@Stable enabled: "+isStableEnabled);
+        System.out.println();
+
+        run(DefaultValue.class);
+        run(ByteStable.class);
+        run(StaticByteStable.class);
+        run(VolatileByteStable.class);
+
+        // @Stable arrays: Dim 1-4
+        run(ByteArrayDim1.class);
+        run(ByteArrayDim2.class);
+        run(ByteArrayDim3.class);
+        run(ByteArrayDim4.class);
+
+        // @Stable Object field: dynamic arrays
+        run(ObjectArrayLowerDim0.class);
+        run(ObjectArrayLowerDim1.class);
+        run(ObjectArrayLowerDim2.class);
+
+        // Nested @Stable fields
+        run(NestedStableField.class);
+        run(NestedStableField1.class);
+        run(NestedStableField2.class);
+        run(NestedStableField3.class);
+
+        if (failed) {
+            throw new Error("TEST FAILED");
+        }
+    }
+
+    /* ==================================================== */
+
+    static class DefaultValue {
+        public @Stable byte v;
+
+        public static final DefaultValue c = new DefaultValue();
+        public static byte get() { return c.v; }
+        public static void test() throws Exception {
+                     byte val1 = get();
+            c.v = 1; byte val2 = get();
+            assertEquals(val1, 0);
+            assertEquals(val2, 1);
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ByteStable {
+        public @Stable byte v;
+
+        public static final ByteStable c = new ByteStable();
+        public static byte get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 5;   byte val1 = get();
+            c.v = 127; byte val2 = get();
+            assertEquals(val1, 5);
+            assertEquals(val2, (isStableEnabled ? 5 : 127));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class StaticByteStable {
+        public static @Stable byte v;
+
+        public static final StaticByteStable c = new StaticByteStable();
+        public static byte get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 5;   byte val1 = get();
+            c.v = 127; byte val2 = get();
+            assertEquals(val1, 5);
+            assertEquals(val2, (isStableEnabled ? 5 : 127));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class VolatileByteStable {
+        public @Stable volatile byte v;
+
+        public static final VolatileByteStable c = new VolatileByteStable();
+        public static byte get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 5;   byte val1 = get();
+            c.v = 127; byte val2 = get();
+            assertEquals(val1, 5);
+            assertEquals(val2, (isStableEnabled ? 5 : 127));
+        }
+    }
+
+    /* ==================================================== */
+    // @Stable array == field && all components are stable
+
+    static class ByteArrayDim1 {
+        public @Stable byte[] v;
+
+        public static final ByteArrayDim1 c = new ByteArrayDim1();
+        public static byte get() { return c.v[0]; }
+        public static byte get1() { return c.v[10]; }
+        public static byte[] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new byte[1]; c.v[0] = 1; byte val1 = get();
+                                   c.v[0] = 2; byte val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new byte[1]; c.v[0] = 3; byte val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+
+            {
+                c.v = new byte[20]; c.v[10] = 1; byte val1 = get1();
+                                    c.v[10] = 2; byte val2 = get1();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new byte[20]; c.v[10] = 3; byte val3 = get1();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+
+            {
+                c.v = new byte[1]; byte[] val1 = get2();
+                c.v = new byte[1]; byte[] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ByteArrayDim2 {
+        public @Stable byte[][] v;
+
+        public static final ByteArrayDim2 c = new ByteArrayDim2();
+        public static byte get() { return c.v[0][0]; }
+        public static byte[] get1() { return c.v[0]; }
+        public static byte[][] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new byte[1][1]; c.v[0][0] = 1; byte val1 = get();
+                                      c.v[0][0] = 2; byte val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new byte[1][1]; c.v[0][0] = 3; byte val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+
+                c.v[0] = new byte[1]; c.v[0][0] = 4; byte val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1 : 4));
+            }
+
+            {
+                c.v = new byte[1][1]; byte[] val1 = get1();
+                c.v[0] = new byte[1]; byte[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new byte[1][1]; byte[][] val1 = get2();
+                c.v = new byte[1][1]; byte[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ByteArrayDim3 {
+        public @Stable byte[][][] v;
+
+        public static final ByteArrayDim3 c = new ByteArrayDim3();
+        public static byte get() { return c.v[0][0][0]; }
+        public static byte[] get1() { return c.v[0][0]; }
+        public static byte[][] get2() { return c.v[0]; }
+        public static byte[][][] get3() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new byte[1][1][1]; c.v[0][0][0] = 1; byte val1 = get();
+                                         c.v[0][0][0] = 2; byte val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new byte[1][1][1]; c.v[0][0][0] = 3; byte val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+
+                c.v[0] = new byte[1][1]; c.v[0][0][0] = 4; byte val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1 : 4));
+
+                c.v[0][0] = new byte[1]; c.v[0][0][0] = 5; byte val5 = get();
+                assertEquals(val5, (isStableEnabled ? 1 : 5));
+            }
+
+            {
+                c.v = new byte[1][1][1]; byte[] val1 = get1();
+                c.v[0][0] = new byte[1]; byte[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new byte[1][1][1]; byte[][] val1 = get2();
+                c.v[0] = new byte[1][1]; byte[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new byte[1][1][1]; byte[][][] val1 = get3();
+                c.v = new byte[1][1][1]; byte[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ByteArrayDim4 {
+        public @Stable byte[][][][] v;
+
+        public static final ByteArrayDim4 c = new ByteArrayDim4();
+        public static byte get() { return c.v[0][0][0][0]; }
+        public static byte[] get1() { return c.v[0][0][0]; }
+        public static byte[][] get2() { return c.v[0][0]; }
+        public static byte[][][] get3() { return c.v[0]; }
+        public static byte[][][][] get4() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new byte[1][1][1][1]; c.v[0][0][0][0] = 1; byte val1 = get();
+                                            c.v[0][0][0][0] = 2; byte val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new byte[1][1][1][1]; c.v[0][0][0][0] = 3; byte val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+
+                c.v[0] = new byte[1][1][1]; c.v[0][0][0][0] = 4; byte val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1 : 4));
+
+                c.v[0][0] = new byte[1][1]; c.v[0][0][0][0] = 5; byte val5 = get();
+                assertEquals(val5, (isStableEnabled ? 1 : 5));
+
+                c.v[0][0][0] = new byte[1]; c.v[0][0][0][0] = 6; byte val6 = get();
+                assertEquals(val6, (isStableEnabled ? 1 : 6));
+            }
+
+            {
+                c.v = new byte[1][1][1][1]; byte[] val1 = get1();
+                c.v[0][0][0] = new byte[1]; byte[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new byte[1][1][1][1]; byte[][] val1 = get2();
+                c.v[0][0] = new byte[1][1]; byte[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new byte[1][1][1][1]; byte[][][] val1 = get3();
+                c.v[0] = new byte[1][1][1]; byte[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new byte[1][1][1][1]; byte[][][][] val1 = get4();
+                c.v = new byte[1][1][1][1]; byte[][][][] val2 = get4();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+        }
+    }
+
+    /* ==================================================== */
+    // Dynamic Dim is higher than static
+
+    static class ObjectArrayLowerDim0 {
+        public @Stable Object v;
+
+        public static final ObjectArrayLowerDim0 c = new ObjectArrayLowerDim0();
+        public static byte get() { return ((byte[])c.v)[0]; }
+        public static byte[] get1() { return (byte[])c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new byte[1]; ((byte[])c.v)[0] = 1; byte val1 = get();
+                                   ((byte[])c.v)[0] = 2; byte val2 = get();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, 2);
+            }
+
+            {
+                c.v = new byte[1]; byte[] val1 = get1();
+                c.v = new byte[1]; byte[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim1 {
+        public @Stable Object[] v;
+
+        public static final ObjectArrayLowerDim1 c = new ObjectArrayLowerDim1();
+        public static byte get() { return ((byte[][])c.v)[0][0]; }
+        public static byte[] get1() { return (byte[])(c.v[0]); }
+        public static Object[] get2() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new byte[1][1]; ((byte[][])c.v)[0][0] = 1; byte val1 = get();
+                                      ((byte[][])c.v)[0][0] = 2; byte val2 = get();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, 2);
+            }
+
+            {
+                c.v = new byte[1][1]; c.v[0] = new byte[0]; byte[] val1 = get1();
+                                     c.v[0] = new byte[0]; byte[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new byte[0][0]; Object[] val1 = get2();
+                c.v = new byte[0][0]; Object[] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim2 {
+        public @Stable Object[][] v;
+
+        public static final ObjectArrayLowerDim2 c = new ObjectArrayLowerDim2();
+        public static byte get() { return ((byte[][][])c.v)[0][0][0]; }
+        public static byte[] get1() { return (byte[])(c.v[0][0]); }
+        public static byte[][] get2() { return (byte[][])(c.v[0]); }
+        public static Object[][] get3() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new byte[1][1][1]; ((byte[][][])c.v)[0][0][0] = 1;  byte val1 = get();
+                                         ((byte[][][])c.v)[0][0][0] = 2; byte val2 = get();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, 2);
+            }
+
+            {
+                c.v = new byte[1][1][1]; c.v[0][0] = new byte[0]; byte[] val1 = get1();
+                                         c.v[0][0] = new byte[0]; byte[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new byte[1][1][1]; c.v[0] = new byte[0][0]; byte[][] val1 = get2();
+                                         c.v[0] = new byte[0][0]; byte[][] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new byte[0][0][0]; Object[][] val1 = get3();
+                c.v = new byte[0][0][0]; Object[][] val2 = get3();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField {
+        static class A {
+            public @Stable byte a;
+
+        }
+        public @Stable A v;
+
+        public static final NestedStableField c = new NestedStableField();
+        public static A get() { return c.v; }
+        public static byte get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.a = 1; A val1 = get();
+                               c.v.a = 2; A val2 = get();
+
+                assertEquals(val1.a, 2);
+                assertEquals(val2.a, 2);
+            }
+
+            {
+                c.v = new A(); c.v.a = 1; byte val1 = get1();
+                               c.v.a = 2; byte val2 = get1();
+                c.v = new A(); c.v.a = 3; byte val3 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField1 {
+        static class A {
+            public @Stable byte a;
+            public @Stable A next;
+        }
+        public @Stable A v;
+
+        public static final NestedStableField1 c = new NestedStableField1();
+        public static A get() { return c.v.next.next.next.next.next.next.next; }
+        public static byte get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.next = new A();   c.v.next.next  = c.v;
+                               c.v.a = 1; c.v.next.a = 1; A val1 = get();
+                               c.v.a = 2; c.v.next.a = 2; A val2 = get();
+
+                assertEquals(val1.a, 2);
+                assertEquals(val2.a, 2);
+            }
+
+            {
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 1; byte val1 = get1();
+                               c.v.a = 2; byte val2 = get1();
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 3; byte val3 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+        }
+    }
+   /* ==================================================== */
+
+    static class NestedStableField2 {
+        static class A {
+            public @Stable byte a;
+            public @Stable A left;
+            public         A right;
+        }
+
+        public @Stable A v;
+
+        public static final NestedStableField2 c = new NestedStableField2();
+        public static byte get() { return c.v.left.left.left.a; }
+        public static byte get1() { return c.v.left.left.right.left.a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.left = c.v.right = c.v;
+                               c.v.a = 1; byte val1 = get(); byte val2 = get1();
+                               c.v.a = 2; byte val3 = get(); byte val4 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val3, (isStableEnabled ? 1 : 2));
+
+                assertEquals(val2, 1);
+                assertEquals(val4, 2);
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField3 {
+        static class A {
+            public @Stable byte a;
+            public @Stable A[] left;
+            public         A[] right;
+        }
+
+        public @Stable A[] v;
+
+        public static final NestedStableField3 c = new NestedStableField3();
+        public static byte get() { return c.v[0].left[1].left[0].left[1].a; }
+        public static byte get1() { return c.v[1].left[0].left[1].right[0].left[1].a; }
+
+        public static void test() throws Exception {
+            {
+                A elem = new A();
+                c.v = new A[] { elem, elem }; c.v[0].left = c.v[0].right = c.v;
+                               elem.a = 1; byte val1 = get(); byte val2 = get1();
+                               elem.a = 2; byte val3 = get(); byte val4 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val3, (isStableEnabled ? 1 : 2));
+
+                assertEquals(val2, 1);
+                assertEquals(val4, 2);
+            }
+        }
+    }
+
+    /* ==================================================== */
+    // Auxiliary methods
+    static void assertEquals(int i, int j) { if (i != j)  throw new AssertionError(i + " != " + j); }
+    static void assertTrue(boolean b) { if (!b)  throw new AssertionError(); }
+
+    static boolean failed = false;
+
+    public static void run(Class<?> test) {
+        Throwable ex = null;
+        System.out.print(test.getName()+": ");
+        try {
+            test.getMethod("test").invoke(null);
+        } catch (InvocationTargetException e) {
+            ex = e.getCause();
+        } catch (Throwable e) {
+            ex = e;
+        } finally {
+            if (ex == null) {
+                System.out.println("PASSED");
+            } else {
+                failed = true;
+                System.out.println("FAILED");
+                ex.printStackTrace(System.out);
+            }
+        }
+    }
+
+    static final boolean isStableEnabled;
+    static {
+        HotSpotDiagnosticMXBean diagnostic
+                = ManagementFactoryHelper.getDiagnosticMXBean();
+        VMOption tmp;
+        try {
+            tmp = diagnostic.getVMOption("FoldStableValues");
+        } catch (IllegalArgumentException e) {
+            tmp = null;
+        }
+        isStableEnabled = (tmp == null ? false : Boolean.parseBoolean(tmp.getValue()));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/stable/TestStableChar.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,631 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 TestStableChar
+ * @summary tests on stable fields and arrays
+ * @library /testlibrary
+ * @compile -XDignore.symbol.file TestStableChar.java
+ * @run main ClassFileInstaller
+ *           java/lang/invoke/TestStableChar
+ *           java/lang/invoke/TestStableChar$CharStable
+ *           java/lang/invoke/TestStableChar$StaticCharStable
+ *           java/lang/invoke/TestStableChar$VolatileCharStable
+ *           java/lang/invoke/TestStableChar$CharArrayDim1
+ *           java/lang/invoke/TestStableChar$CharArrayDim2
+ *           java/lang/invoke/TestStableChar$CharArrayDim3
+ *           java/lang/invoke/TestStableChar$CharArrayDim4
+ *           java/lang/invoke/TestStableChar$ObjectArrayLowerDim0
+ *           java/lang/invoke/TestStableChar$ObjectArrayLowerDim1
+ *           java/lang/invoke/TestStableChar$NestedStableField
+ *           java/lang/invoke/TestStableChar$NestedStableField$A
+ *           java/lang/invoke/TestStableChar$NestedStableField1
+ *           java/lang/invoke/TestStableChar$NestedStableField1$A
+ *           java/lang/invoke/TestStableChar$NestedStableField2
+ *           java/lang/invoke/TestStableChar$NestedStableField2$A
+ *           java/lang/invoke/TestStableChar$NestedStableField3
+ *           java/lang/invoke/TestStableChar$NestedStableField3$A
+ *           java/lang/invoke/TestStableChar$DefaultValue
+ *           java/lang/invoke/TestStableChar$ObjectArrayLowerDim2
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableChar
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableChar
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableChar
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableChar
+ */
+package java.lang.invoke;
+
+import com.sun.management.HotSpotDiagnosticMXBean;
+import com.sun.management.VMOption;
+import sun.management.ManagementFactoryHelper;
+import java.lang.reflect.InvocationTargetException;
+
+public class TestStableChar {
+    public static void main(String[] args) throws Exception {
+        System.out.println("@Stable enabled: "+isStableEnabled);
+        System.out.println();
+
+        run(DefaultValue.class);
+        run(CharStable.class);
+        run(StaticCharStable.class);
+        run(VolatileCharStable.class);
+
+        // @Stable arrays: Dim 1-4
+        run(CharArrayDim1.class);
+        run(CharArrayDim2.class);
+        run(CharArrayDim3.class);
+        run(CharArrayDim4.class);
+
+        // @Stable Object field: dynamic arrays
+        run(ObjectArrayLowerDim0.class);
+        run(ObjectArrayLowerDim1.class);
+        run(ObjectArrayLowerDim2.class);
+
+        // Nested @Stable fields
+        run(NestedStableField.class);
+        run(NestedStableField1.class);
+        run(NestedStableField2.class);
+        run(NestedStableField3.class);
+
+        if (failed) {
+            throw new Error("TEST FAILED");
+        }
+    }
+
+    /* ==================================================== */
+
+    static class DefaultValue {
+        public @Stable char v;
+
+        public static final DefaultValue c = new DefaultValue();
+        public static char get() { return c.v; }
+        public static void test() throws Exception {
+                       char val1 = get();
+            c.v = 'a'; char val2 = get();
+            assertEquals(val1, 0);
+            assertEquals(val2, 'a');
+        }
+    }
+
+    /* ==================================================== */
+
+    static class CharStable {
+        public @Stable char v;
+
+        public static final CharStable c = new CharStable();
+        public static char get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 'a'; char val1 = get();
+            c.v = 'b'; char val2 = get();
+            assertEquals(val1, 'a');
+            assertEquals(val2, (isStableEnabled ? 'a' : 'b'));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class StaticCharStable {
+        public @Stable char v;
+
+        public static final StaticCharStable c = new StaticCharStable();
+        public static char get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 'a'; char val1 = get();
+            c.v = 'b'; char val2 = get();
+            assertEquals(val1, 'a');
+            assertEquals(val2, (isStableEnabled ? 'a' : 'b'));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class VolatileCharStable {
+        public @Stable volatile char v;
+
+        public static final VolatileCharStable c = new VolatileCharStable();
+        public static char get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 'a'; char val1 = get();
+            c.v = 'b'; char val2 = get();
+            assertEquals(val1, 'a');
+            assertEquals(val2, (isStableEnabled ? 'a' : 'b'));
+        }
+    }
+
+    /* ==================================================== */
+    // @Stable array == field && all components are stable
+
+    static class CharArrayDim1 {
+        public @Stable char[] v;
+
+        public static final CharArrayDim1 c = new CharArrayDim1();
+        public static char get() { return c.v[0]; }
+        public static char get1() { return c.v[10]; }
+        public static char[] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new char[1]; c.v[0] = 'a'; char val1 = get();
+                                   c.v[0] = 'b'; char val2 = get();
+                assertEquals(val1, 'a');
+                assertEquals(val2, (isStableEnabled ? 'a' : 'b'));
+
+                c.v = new char[1]; c.v[0] = 'c'; char val3 = get();
+                assertEquals(val3, (isStableEnabled ? 'a' : 'c'));
+            }
+
+            {
+                c.v = new char[20]; c.v[10] = 'a'; char val1 = get1();
+                                    c.v[10] = 'b'; char val2 = get1();
+                assertEquals(val1, 'a');
+                assertEquals(val2, (isStableEnabled ? 'a' : 'b'));
+
+                c.v = new char[20]; c.v[10] = 'c'; char val3 = get1();
+                assertEquals(val3, (isStableEnabled ? 'a' : 'c'));
+            }
+
+            {
+                c.v = new char[1]; char[] val1 = get2();
+                c.v = new char[1]; char[] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class CharArrayDim2 {
+        public @Stable char[][] v;
+
+        public static final CharArrayDim2 c = new CharArrayDim2();
+        public static char get() { return c.v[0][0]; }
+        public static char[] get1() { return c.v[0]; }
+        public static char[][] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new char[1][1]; c.v[0][0] = 'a'; char val1 = get();
+                                      c.v[0][0] = 'b'; char val2 = get();
+                assertEquals(val1, 'a');
+                assertEquals(val2, (isStableEnabled ? 'a' : 'b'));
+
+                c.v = new char[1][1]; c.v[0][0] = 'c'; char val3 = get();
+                assertEquals(val3, (isStableEnabled ? 'a' : 'c'));
+
+                c.v[0] = new char[1]; c.v[0][0] = 'd'; char val4 = get();
+                assertEquals(val4, (isStableEnabled ? 'a' : 'd'));
+            }
+
+            {
+                c.v = new char[1][1]; char[] val1 = get1();
+                c.v[0] = new char[1]; char[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new char[1][1]; char[][] val1 = get2();
+                c.v = new char[1][1]; char[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class CharArrayDim3 {
+        public @Stable char[][][] v;
+
+        public static final CharArrayDim3 c = new CharArrayDim3();
+        public static char get() { return c.v[0][0][0]; }
+        public static char[] get1() { return c.v[0][0]; }
+        public static char[][] get2() { return c.v[0]; }
+        public static char[][][] get3() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new char[1][1][1]; c.v[0][0][0] = 'a'; char val1 = get();
+                                         c.v[0][0][0] = 'b'; char val2 = get();
+                assertEquals(val1, 'a');
+                assertEquals(val2, (isStableEnabled ? 'a' : 'b'));
+
+                c.v = new char[1][1][1]; c.v[0][0][0] = 'c'; char val3 = get();
+                assertEquals(val3, (isStableEnabled ? 'a' : 'c'));
+
+                c.v[0] = new char[1][1]; c.v[0][0][0] = 'd'; char val4 = get();
+                assertEquals(val4, (isStableEnabled ? 'a' : 'd'));
+
+                c.v[0][0] = new char[1]; c.v[0][0][0] = 'e'; char val5 = get();
+                assertEquals(val5, (isStableEnabled ? 'a' : 'e'));
+            }
+
+            {
+                c.v = new char[1][1][1]; char[] val1 = get1();
+                c.v[0][0] = new char[1]; char[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new char[1][1][1]; char[][] val1 = get2();
+                c.v[0] = new char[1][1]; char[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new char[1][1][1]; char[][][] val1 = get3();
+                c.v = new char[1][1][1]; char[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class CharArrayDim4 {
+        public @Stable char[][][][] v;
+
+        public static final CharArrayDim4 c = new CharArrayDim4();
+        public static char get() { return c.v[0][0][0][0]; }
+        public static char[] get1() { return c.v[0][0][0]; }
+        public static char[][] get2() { return c.v[0][0]; }
+        public static char[][][] get3() { return c.v[0]; }
+        public static char[][][][] get4() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new char[1][1][1][1]; c.v[0][0][0][0] = 'a'; char val1 = get();
+                                            c.v[0][0][0][0] = 'b'; char val2 = get();
+                assertEquals(val1, 'a');
+                assertEquals(val2, (isStableEnabled ? 'a' : 'b'));
+
+                c.v = new char[1][1][1][1]; c.v[0][0][0][0] = 'c'; char val3 = get();
+                assertEquals(val3, (isStableEnabled ? 'a' : 'c'));
+
+                c.v[0] = new char[1][1][1]; c.v[0][0][0][0] = 'd'; char val4 = get();
+                assertEquals(val4, (isStableEnabled ? 'a' : 'd'));
+
+                c.v[0][0] = new char[1][1]; c.v[0][0][0][0] = 'e'; char val5 = get();
+                assertEquals(val5, (isStableEnabled ? 'a' : 'e'));
+
+                c.v[0][0][0] = new char[1]; c.v[0][0][0][0] = 'f'; char val6 = get();
+                assertEquals(val6, (isStableEnabled ? 'a' : 'f'));
+            }
+
+            {
+                c.v = new char[1][1][1][1]; char[] val1 = get1();
+                c.v[0][0][0] = new char[1]; char[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new char[1][1][1][1]; char[][] val1 = get2();
+                c.v[0][0] = new char[1][1]; char[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new char[1][1][1][1]; char[][][] val1 = get3();
+                c.v[0] = new char[1][1][1]; char[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new char[1][1][1][1]; char[][][][] val1 = get4();
+                c.v = new char[1][1][1][1]; char[][][][] val2 = get4();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+        }
+    }
+
+    /* ==================================================== */
+    // Dynamic Dim is higher than static
+    static class ObjectArrayLowerDim0 {
+        public @Stable Object v;
+
+        public static final ObjectArrayLowerDim0 c = new ObjectArrayLowerDim0();
+        public static char get() { return ((char[])c.v)[0]; }
+        public static char[] get1() { return (char[])c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new char[1]; ((char[])c.v)[0] = 'a'; char val1 = get();
+                                   ((char[])c.v)[0] = 'b'; char val2 = get();
+
+                assertEquals(val1, 'a');
+                assertEquals(val2, 'b');
+            }
+
+            {
+                c.v = new char[1]; char[] val1 = get1();
+                c.v = new char[1]; char[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim1 {
+        public @Stable Object[] v;
+
+        public static final ObjectArrayLowerDim1 c = new ObjectArrayLowerDim1();
+        public static char get() { return ((char[][])c.v)[0][0]; }
+        public static char[] get1() { return (char[])(c.v[0]); }
+        public static Object[] get2() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new char[1][1]; ((char[][])c.v)[0][0] = 'a'; char val1 = get();
+                                      ((char[][])c.v)[0][0] = 'b'; char val2 = get();
+
+                assertEquals(val1, 'a');
+                assertEquals(val2, 'b');
+            }
+
+            {
+                c.v = new char[1][1]; c.v[0] = new char[0]; char[] val1 = get1();
+                                      c.v[0] = new char[0]; char[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new char[0][0]; Object[] val1 = get2();
+                c.v = new char[0][0]; Object[] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim2 {
+        public @Stable Object[][] v;
+
+        public static final ObjectArrayLowerDim2 c = new ObjectArrayLowerDim2();
+        public static char get() { return ((char[][][])c.v)[0][0][0]; }
+        public static char[] get1() { return (char[])(c.v[0][0]); }
+        public static char[][] get2() { return (char[][])(c.v[0]); }
+        public static Object[][] get3() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new char[1][1][1]; ((char[][][])c.v)[0][0][0] = 'a';  char val1 = get();
+                                         ((char[][][])c.v)[0][0][0] = 'b'; char val2 = get();
+
+                assertEquals(val1, 'a');
+                assertEquals(val2, 'b');
+            }
+
+            {
+                c.v = new char[1][1][1]; c.v[0][0] = new char[0]; char[] val1 = get1();
+                                         c.v[0][0] = new char[0]; char[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new char[1][1][1]; c.v[0] = new char[0][0]; char[][] val1 = get2();
+                                         c.v[0] = new char[0][0]; char[][] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new char[0][0][0]; Object[][] val1 = get3();
+                c.v = new char[0][0][0]; Object[][] val2 = get3();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField {
+        static class A {
+            public @Stable char a;
+
+        }
+        public @Stable A v;
+
+        public static final NestedStableField c = new NestedStableField();
+        public static A get() { return c.v; }
+        public static char get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.a = 'a'; A val1 = get();
+                               c.v.a = 'b'; A val2 = get();
+
+                assertEquals(val1.a, 'b');
+                assertEquals(val2.a, 'b');
+            }
+
+            {
+                c.v = new A(); c.v.a = 'a'; char val1 = get1();
+                               c.v.a = 'b'; char val2 = get1();
+                c.v = new A(); c.v.a = 'c'; char val3 = get1();
+
+                assertEquals(val1, 'a');
+                assertEquals(val2, (isStableEnabled ? 'a' : 'b'));
+                assertEquals(val3, (isStableEnabled ? 'a' : 'c'));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField1 {
+        static class A {
+            public @Stable char a;
+            public @Stable A next;
+        }
+        public @Stable A v;
+
+        public static final NestedStableField1 c = new NestedStableField1();
+        public static A get() { return c.v.next.next.next.next.next.next.next; }
+        public static char get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.next = new A(); c.v.next.next  = c.v;
+                               c.v.a = 'a'; c.v.next.a = 'a'; A val1 = get();
+                               c.v.a = 'b'; c.v.next.a = 'b'; A val2 = get();
+
+                assertEquals(val1.a, 'b');
+                assertEquals(val2.a, 'b');
+            }
+
+            {
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 'a'; char val1 = get1();
+                               c.v.a = 'b'; char val2 = get1();
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 'c'; char val3 = get1();
+
+                assertEquals(val1, 'a');
+                assertEquals(val2, (isStableEnabled ? 'a' : 'b'));
+                assertEquals(val3, (isStableEnabled ? 'a' : 'c'));
+            }
+        }
+    }
+   /* ==================================================== */
+
+    static class NestedStableField2 {
+        static class A {
+            public @Stable char a;
+            public @Stable A left;
+            public         A right;
+        }
+
+        public @Stable A v;
+
+        public static final NestedStableField2 c = new NestedStableField2();
+        public static char get() { return c.v.left.left.left.a; }
+        public static char get1() { return c.v.left.left.right.left.a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.left = c.v.right = c.v;
+                               c.v.a = 'a'; char val1 = get(); char val2 = get1();
+                               c.v.a = 'b'; char val3 = get(); char val4 = get1();
+
+                assertEquals(val1, 'a');
+                assertEquals(val3, (isStableEnabled ? 'a' : 'b'));
+
+                assertEquals(val2, 'a');
+                assertEquals(val4, 'b');
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField3 {
+        static class A {
+            public @Stable char a;
+            public @Stable A[] left;
+            public         A[] right;
+        }
+
+        public @Stable A[] v;
+
+        public static final NestedStableField3 c = new NestedStableField3();
+        public static char get() { return c.v[0].left[1].left[0].left[1].a; }
+        public static char get1() { return c.v[1].left[0].left[1].right[0].left[1].a; }
+
+        public static void test() throws Exception {
+            {
+                A elem = new A();
+                c.v = new A[] { elem, elem }; c.v[0].left = c.v[0].right = c.v;
+                               elem.a = 'a'; char val1 = get(); char val2 = get1();
+                               elem.a = 'b'; char val3 = get(); char val4 = get1();
+
+                assertEquals(val1, 'a');
+                assertEquals(val3, (isStableEnabled ? 'a' : 'b'));
+
+                assertEquals(val2, 'a');
+                assertEquals(val4, 'b');
+            }
+        }
+    }
+
+    /* ==================================================== */
+    // Auxiliary methods
+    static void assertEquals(int i, int j) { if (i != j)  throw new AssertionError(i + " != " + j); }
+    static void assertTrue(boolean b) { if (!b)  throw new AssertionError(); }
+
+    static boolean failed = false;
+
+    public static void run(Class<?> test) {
+        Throwable ex = null;
+        System.out.print(test.getName()+": ");
+        try {
+            test.getMethod("test").invoke(null);
+        } catch (InvocationTargetException e) {
+            ex = e.getCause();
+        } catch (Throwable e) {
+            ex = e;
+        } finally {
+            if (ex == null) {
+                System.out.println("PASSED");
+            } else {
+                failed = true;
+                System.out.println("FAILED");
+                ex.printStackTrace(System.out);
+            }
+        }
+    }
+
+    static final boolean isStableEnabled;
+    static {
+        HotSpotDiagnosticMXBean diagnostic
+                = ManagementFactoryHelper.getDiagnosticMXBean();
+        VMOption tmp;
+        try {
+            tmp = diagnostic.getVMOption("FoldStableValues");
+        } catch (IllegalArgumentException e) {
+            tmp = null;
+        }
+        isStableEnabled = (tmp == null ? false : Boolean.parseBoolean(tmp.getValue()));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/stable/TestStableDouble.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,632 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 TestStableDouble
+ * @summary tests on stable fields and arrays
+ * @library /testlibrary
+ * @compile -XDignore.symbol.file TestStableDouble.java
+ * @run main ClassFileInstaller
+ *           java/lang/invoke/TestStableDouble
+ *           java/lang/invoke/TestStableDouble$DoubleStable
+ *           java/lang/invoke/TestStableDouble$StaticDoubleStable
+ *           java/lang/invoke/TestStableDouble$VolatileDoubleStable
+ *           java/lang/invoke/TestStableDouble$DoubleArrayDim1
+ *           java/lang/invoke/TestStableDouble$DoubleArrayDim2
+ *           java/lang/invoke/TestStableDouble$DoubleArrayDim3
+ *           java/lang/invoke/TestStableDouble$DoubleArrayDim4
+ *           java/lang/invoke/TestStableDouble$ObjectArrayLowerDim0
+ *           java/lang/invoke/TestStableDouble$ObjectArrayLowerDim1
+ *           java/lang/invoke/TestStableDouble$NestedStableField
+ *           java/lang/invoke/TestStableDouble$NestedStableField$A
+ *           java/lang/invoke/TestStableDouble$NestedStableField1
+ *           java/lang/invoke/TestStableDouble$NestedStableField1$A
+ *           java/lang/invoke/TestStableDouble$NestedStableField2
+ *           java/lang/invoke/TestStableDouble$NestedStableField2$A
+ *           java/lang/invoke/TestStableDouble$NestedStableField3
+ *           java/lang/invoke/TestStableDouble$NestedStableField3$A
+ *           java/lang/invoke/TestStableDouble$DefaultValue
+ *           java/lang/invoke/TestStableDouble$ObjectArrayLowerDim2
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableDouble
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableDouble
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableDouble
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableDouble
+ */
+package java.lang.invoke;
+
+import com.sun.management.HotSpotDiagnosticMXBean;
+import com.sun.management.VMOption;
+import sun.management.ManagementFactoryHelper;
+import java.lang.reflect.InvocationTargetException;
+
+public class TestStableDouble {
+    public static void main(String[] args) throws Exception {
+        System.out.println("@Stable enabled: "+isStableEnabled);
+        System.out.println();
+
+        run(DefaultValue.class);
+        run(DoubleStable.class);
+        run(StaticDoubleStable.class);
+        run(VolatileDoubleStable.class);
+
+        // @Stable arrays: Dim 1-4
+        run(DoubleArrayDim1.class);
+        run(DoubleArrayDim2.class);
+        run(DoubleArrayDim3.class);
+        run(DoubleArrayDim4.class);
+
+        // @Stable Object field: dynamic arrays
+        run(ObjectArrayLowerDim0.class);
+        run(ObjectArrayLowerDim1.class);
+        run(ObjectArrayLowerDim2.class);
+
+        // Nested @Stable fields
+        run(NestedStableField.class);
+        run(NestedStableField1.class);
+        run(NestedStableField2.class);
+        run(NestedStableField3.class);
+
+        if (failed) {
+            throw new Error("TEST FAILED");
+        }
+    }
+
+    /* ==================================================== */
+
+    static class DefaultValue {
+        public @Stable double v;
+
+        public static final DefaultValue c = new DefaultValue();
+        public static double get() { return c.v; }
+        public static void test() throws Exception {
+                       double val1 = get();
+            c.v = 1.0; double val2 = get();
+            assertEquals(val1, 0);
+            assertEquals(val2, 1.0);
+        }
+    }
+
+    /* ==================================================== */
+
+    static class DoubleStable {
+        public @Stable double v;
+
+        public static final DoubleStable c = new DoubleStable();
+        public static double get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 1.0; double val1 = get();
+            c.v = Double.MAX_VALUE; double val2 = get();
+            assertEquals(val1, 1.0);
+            assertEquals(val2, (isStableEnabled ? 1.0 : Double.MAX_VALUE));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class StaticDoubleStable {
+        public static @Stable double v;
+
+        public static final StaticDoubleStable c = new StaticDoubleStable();
+        public static double get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 1.0; double val1 = get();
+            c.v = Double.MAX_VALUE; double val2 = get();
+            assertEquals(val1, 1.0);
+            assertEquals(val2, (isStableEnabled ? 1.0 : Double.MAX_VALUE));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class VolatileDoubleStable {
+        public @Stable double v;
+
+        public static final VolatileDoubleStable c = new VolatileDoubleStable();
+        public static double get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 1.0; double val1 = get();
+            c.v = Double.MAX_VALUE; double val2 = get();
+            assertEquals(val1, 1.0);
+            assertEquals(val2, (isStableEnabled ? 1.0 : Double.MAX_VALUE));
+        }
+    }
+
+    /* ==================================================== */
+    // @Stable array == field && all components are stable
+
+    static class DoubleArrayDim1 {
+        public @Stable double[] v;
+
+        public static final DoubleArrayDim1 c = new DoubleArrayDim1();
+        public static double get() { return c.v[0]; }
+        public static double get1() { return c.v[10]; }
+        public static double[] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new double[1]; c.v[0] = 1.0; double val1 = get();
+                                     c.v[0] = 2.0; double val2 = get();
+                assertEquals(val1, 1.0);
+                assertEquals(val2, (isStableEnabled ? 1.0 : 2.0));
+
+                c.v = new double[1]; c.v[0] = 3.0; double val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1.0 : 3.0));
+            }
+
+            {
+                c.v = new double[20]; c.v[10] = 1.0; double val1 = get1();
+                                      c.v[10] = 2.0; double val2 = get1();
+                assertEquals(val1, 1.0);
+                assertEquals(val2, (isStableEnabled ? 1.0 : 2.0));
+
+                c.v = new double[20]; c.v[10] = 3.0; double val3 = get1();
+                assertEquals(val3, (isStableEnabled ? 1.0 : 3.0));
+            }
+
+            {
+                c.v = new double[1]; double[] val1 = get2();
+                c.v = new double[1]; double[] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class DoubleArrayDim2 {
+        public @Stable double[][] v;
+
+        public static final DoubleArrayDim2 c = new DoubleArrayDim2();
+        public static double get() { return c.v[0][0]; }
+        public static double[] get1() { return c.v[0]; }
+        public static double[][] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new double[1][1]; c.v[0][0] = 1.0; double val1 = get();
+                                        c.v[0][0] = 2.0; double val2 = get();
+                assertEquals(val1, 1.0);
+                assertEquals(val2, (isStableEnabled ? 1.0 : 2.0));
+
+                c.v = new double[1][1]; c.v[0][0] = 3.0; double val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1.0 : 3.0));
+
+                c.v[0] = new double[1]; c.v[0][0] = 4.0; double val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1.0 : 4.0));
+            }
+
+            {
+                c.v = new double[1][1]; double[] val1 = get1();
+                c.v[0] = new double[1]; double[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new double[1][1]; double[][] val1 = get2();
+                c.v = new double[1][1]; double[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class DoubleArrayDim3 {
+        public @Stable double[][][] v;
+
+        public static final DoubleArrayDim3 c = new DoubleArrayDim3();
+        public static double get() { return c.v[0][0][0]; }
+        public static double[] get1() { return c.v[0][0]; }
+        public static double[][] get2() { return c.v[0]; }
+        public static double[][][] get3() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new double[1][1][1]; c.v[0][0][0] = 1.0; double val1 = get();
+                                           c.v[0][0][0] = 2.0; double val2 = get();
+                assertEquals(val1, 1.0);
+                assertEquals(val2, (isStableEnabled ? 1.0 : 2.0));
+
+                c.v = new double[1][1][1]; c.v[0][0][0] = 3.0; double val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1.0 : 3.0));
+
+                c.v[0] = new double[1][1]; c.v[0][0][0] = 4.0; double val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1.0 : 4.0));
+
+                c.v[0][0] = new double[1]; c.v[0][0][0] = 5.0; double val5 = get();
+                assertEquals(val5, (isStableEnabled ? 1.0 : 5.0));
+            }
+
+            {
+                c.v = new double[1][1][1]; double[] val1 = get1();
+                c.v[0][0] = new double[1]; double[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new double[1][1][1]; double[][] val1 = get2();
+                c.v[0] = new double[1][1]; double[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new double[1][1][1]; double[][][] val1 = get3();
+                c.v = new double[1][1][1]; double[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class DoubleArrayDim4 {
+        public @Stable double[][][][] v;
+
+        public static final DoubleArrayDim4 c = new DoubleArrayDim4();
+        public static double get() { return c.v[0][0][0][0]; }
+        public static double[] get1() { return c.v[0][0][0]; }
+        public static double[][] get2() { return c.v[0][0]; }
+        public static double[][][] get3() { return c.v[0]; }
+        public static double[][][][] get4() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new double[1][1][1][1]; c.v[0][0][0][0] = 1.0; double val1 = get();
+                                              c.v[0][0][0][0] = 2.0; double val2 = get();
+                assertEquals(val1, 1.0);
+                assertEquals(val2, (isStableEnabled ? 1.0 : 2.0));
+
+                c.v = new double[1][1][1][1]; c.v[0][0][0][0] = 3.0; double val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1.0 : 3.0));
+
+                c.v[0] = new double[1][1][1]; c.v[0][0][0][0] = 4.0; double val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1.0 : 4.0));
+
+                c.v[0][0] = new double[1][1]; c.v[0][0][0][0] = 5.0; double val5 = get();
+                assertEquals(val5, (isStableEnabled ? 1.0 : 5.0));
+
+                c.v[0][0][0] = new double[1]; c.v[0][0][0][0] = 6.0; double val6 = get();
+                assertEquals(val6, (isStableEnabled ? 1.0 : 6.0));
+            }
+
+            {
+                c.v = new double[1][1][1][1]; double[] val1 = get1();
+                c.v[0][0][0] = new double[1]; double[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new double[1][1][1][1]; double[][] val1 = get2();
+                c.v[0][0] = new double[1][1]; double[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new double[1][1][1][1]; double[][][] val1 = get3();
+                c.v[0] = new double[1][1][1]; double[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new double[1][1][1][1]; double[][][][] val1 = get4();
+                c.v = new double[1][1][1][1]; double[][][][] val2 = get4();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+        }
+    }
+
+    /* ==================================================== */
+    // Dynamic Dim is higher than static
+
+    static class ObjectArrayLowerDim0 {
+        public @Stable Object v;
+
+        public static final ObjectArrayLowerDim0 c = new ObjectArrayLowerDim0();
+        public static double get() { return ((double[])c.v)[0]; }
+        public static double[] get1() { return (double[])c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new double[1]; ((double[])c.v)[0] = 1.0; double val1 = get();
+                                     ((double[])c.v)[0] = 2.0; double val2 = get();
+
+                assertEquals(val1, 1.0);
+                assertEquals(val2, 2.0);
+            }
+
+            {
+                c.v = new double[1]; double[] val1 = get1();
+                c.v = new double[1]; double[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim1 {
+        public @Stable Object[] v;
+
+        public static final ObjectArrayLowerDim1 c = new ObjectArrayLowerDim1();
+        public static double get() { return ((double[][])c.v)[0][0]; }
+        public static double[] get1() { return (double[])(c.v[0]); }
+        public static Object[] get2() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new double[1][1]; ((double[][])c.v)[0][0] = 1.0; double val1 = get();
+                                        ((double[][])c.v)[0][0] = 2.0; double val2 = get();
+
+                assertEquals(val1, 1.0);
+                assertEquals(val2, 2.0);
+            }
+
+            {
+                c.v = new double[1][1]; c.v[0] = new double[0]; double[] val1 = get1();
+                                        c.v[0] = new double[0]; double[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new double[0][0]; Object[] val1 = get2();
+                c.v = new double[0][0]; Object[] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim2 {
+        public @Stable Object[][] v;
+
+        public static final ObjectArrayLowerDim2 c = new ObjectArrayLowerDim2();
+        public static double get() { return ((double[][][])c.v)[0][0][0]; }
+        public static double[] get1() { return (double[])(c.v[0][0]); }
+        public static double[][] get2() { return (double[][])(c.v[0]); }
+        public static Object[][] get3() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new double[1][1][1]; ((double[][][])c.v)[0][0][0] = 1.0; double val1 = get();
+                                           ((double[][][])c.v)[0][0][0] = 2.0; double val2 = get();
+
+                assertEquals(val1, 1.0);
+                assertEquals(val2, 2.0);
+            }
+
+            {
+                c.v = new double[1][1][1]; c.v[0][0] = new double[0]; double[] val1 = get1();
+                                           c.v[0][0] = new double[0]; double[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new double[1][1][1]; c.v[0] = new double[0][0]; double[][] val1 = get2();
+                                           c.v[0] = new double[0][0]; double[][] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new double[0][0][0]; Object[][] val1 = get3();
+                c.v = new double[0][0][0]; Object[][] val2 = get3();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField {
+        static class A {
+            public @Stable double a;
+
+        }
+        public @Stable A v;
+
+        public static final NestedStableField c = new NestedStableField();
+        public static A get() { return c.v; }
+        public static double get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.a = 1.0; A val1 = get();
+                               c.v.a = 2.0; A val2 = get();
+
+                assertEquals(val1.a, 2.0);
+                assertEquals(val2.a, 2.0);
+            }
+
+            {
+                c.v = new A(); c.v.a = 1.0; double val1 = get1();
+                               c.v.a = 2.0; double val2 = get1();
+                c.v = new A(); c.v.a = 3.0; double val3 = get1();
+
+                assertEquals(val1, 1.0);
+                assertEquals(val2, (isStableEnabled ? 1.0 : 2.0));
+                assertEquals(val3, (isStableEnabled ? 1.0 : 3.0));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField1 {
+        static class A {
+            public @Stable double a;
+            public @Stable A next;
+        }
+        public @Stable A v;
+
+        public static final NestedStableField1 c = new NestedStableField1();
+        public static A get() { return c.v.next.next.next.next.next.next.next; }
+        public static double get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.next = new A();   c.v.next.next  = c.v;
+                               c.v.a = 1.0; c.v.next.a = 1.0; A val1 = get();
+                               c.v.a = 2.0; c.v.next.a = 2.0; A val2 = get();
+
+                assertEquals(val1.a, 2.0);
+                assertEquals(val2.a, 2.0);
+            }
+
+            {
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 1.0; double val1 = get1();
+                               c.v.a = 2.0; double val2 = get1();
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 3.0; double val3 = get1();
+
+                assertEquals(val1, 1.0);
+                assertEquals(val2, (isStableEnabled ? 1.0 : 2.0));
+                assertEquals(val3, (isStableEnabled ? 1.0 : 3.0));
+            }
+        }
+    }
+   /* ==================================================== */
+
+    static class NestedStableField2 {
+        static class A {
+            public @Stable double a;
+            public @Stable A left;
+            public         A right;
+        }
+
+        public @Stable A v;
+
+        public static final NestedStableField2 c = new NestedStableField2();
+        public static double get() { return c.v.left.left.left.a; }
+        public static double get1() { return c.v.left.left.right.left.a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.left = c.v.right = c.v;
+                               c.v.a = 1.0; double val1 = get(); double val2 = get1();
+                               c.v.a = 2.0; double val3 = get(); double val4 = get1();
+
+                assertEquals(val1, 1.0);
+                assertEquals(val3, (isStableEnabled ? 1.0 : 2.0));
+
+                assertEquals(val2, 1.0);
+                assertEquals(val4, 2.0);
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField3 {
+        static class A {
+            public @Stable double a;
+            public @Stable A[] left;
+            public         A[] right;
+        }
+
+        public @Stable A[] v;
+
+        public static final NestedStableField3 c = new NestedStableField3();
+        public static double get() { return c.v[0].left[1].left[0].left[1].a; }
+        public static double get1() { return c.v[1].left[0].left[1].right[0].left[1].a; }
+
+        public static void test() throws Exception {
+            {
+                A elem = new A();
+                c.v = new A[] { elem, elem }; c.v[0].left = c.v[0].right = c.v;
+                               elem.a = 1.0; double val1 = get(); double val2 = get1();
+                               elem.a = 2.0; double val3 = get(); double val4 = get1();
+
+                assertEquals(val1, 1.0);
+                assertEquals(val3, (isStableEnabled ? 1.0 : 2.0));
+
+                assertEquals(val2, 1.0);
+                assertEquals(val4, 2.0);
+            }
+        }
+    }
+
+    /* ==================================================== */
+    // Auxiliary methods
+    static void assertEquals(double i, double j) { if (i != j)  throw new AssertionError(i + " != " + j); }
+    static void assertTrue(boolean b) { if (!b)  throw new AssertionError(); }
+
+    static boolean failed = false;
+
+    public static void run(Class<?> test) {
+        Throwable ex = null;
+        System.out.print(test.getName()+": ");
+        try {
+            test.getMethod("test").invoke(null);
+        } catch (InvocationTargetException e) {
+            ex = e.getCause();
+        } catch (Throwable e) {
+            ex = e;
+        } finally {
+            if (ex == null) {
+                System.out.println("PASSED");
+            } else {
+                failed = true;
+                System.out.println("FAILED");
+                ex.printStackTrace(System.out);
+            }
+        }
+    }
+
+    static final boolean isStableEnabled;
+    static {
+        HotSpotDiagnosticMXBean diagnostic
+                = ManagementFactoryHelper.getDiagnosticMXBean();
+        VMOption tmp;
+        try {
+            tmp = diagnostic.getVMOption("FoldStableValues");
+        } catch (IllegalArgumentException e) {
+            tmp = null;
+        }
+        isStableEnabled = (tmp == null ? false : Boolean.parseBoolean(tmp.getValue()));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/stable/TestStableFloat.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,632 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 TestStableFloat
+ * @summary tests on stable fields and arrays
+ * @library /testlibrary
+ * @compile -XDignore.symbol.file TestStableFloat.java
+ * @run main ClassFileInstaller
+ *           java/lang/invoke/TestStableFloat
+ *           java/lang/invoke/TestStableFloat$FloatStable
+ *           java/lang/invoke/TestStableFloat$StaticFloatStable
+ *           java/lang/invoke/TestStableFloat$VolatileFloatStable
+ *           java/lang/invoke/TestStableFloat$FloatArrayDim1
+ *           java/lang/invoke/TestStableFloat$FloatArrayDim2
+ *           java/lang/invoke/TestStableFloat$FloatArrayDim3
+ *           java/lang/invoke/TestStableFloat$FloatArrayDim4
+ *           java/lang/invoke/TestStableFloat$ObjectArrayLowerDim0
+ *           java/lang/invoke/TestStableFloat$ObjectArrayLowerDim1
+ *           java/lang/invoke/TestStableFloat$NestedStableField
+ *           java/lang/invoke/TestStableFloat$NestedStableField$A
+ *           java/lang/invoke/TestStableFloat$NestedStableField1
+ *           java/lang/invoke/TestStableFloat$NestedStableField1$A
+ *           java/lang/invoke/TestStableFloat$NestedStableField2
+ *           java/lang/invoke/TestStableFloat$NestedStableField2$A
+ *           java/lang/invoke/TestStableFloat$NestedStableField3
+ *           java/lang/invoke/TestStableFloat$NestedStableField3$A
+ *           java/lang/invoke/TestStableFloat$DefaultValue
+ *           java/lang/invoke/TestStableFloat$ObjectArrayLowerDim2
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableFloat
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableFloat
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableFloat
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableFloat
+ */
+package java.lang.invoke;
+
+import com.sun.management.HotSpotDiagnosticMXBean;
+import com.sun.management.VMOption;
+import sun.management.ManagementFactoryHelper;
+import java.lang.reflect.InvocationTargetException;
+
+public class TestStableFloat {
+    public static void main(String[] args) throws Exception {
+        System.out.println("@Stable enabled: "+isStableEnabled);
+        System.out.println();
+
+        run(DefaultValue.class);
+        run(FloatStable.class);
+        run(StaticFloatStable.class);
+        run(VolatileFloatStable.class);
+
+        // @Stable arrays: Dim 1-4
+        run(FloatArrayDim1.class);
+        run(FloatArrayDim2.class);
+        run(FloatArrayDim3.class);
+        run(FloatArrayDim4.class);
+
+        // @Stable Object field: dynamic arrays
+        run(ObjectArrayLowerDim0.class);
+        run(ObjectArrayLowerDim1.class);
+        run(ObjectArrayLowerDim2.class);
+
+        // Nested @Stable fields
+        run(NestedStableField.class);
+        run(NestedStableField1.class);
+        run(NestedStableField2.class);
+        run(NestedStableField3.class);
+
+        if (failed) {
+            throw new Error("TEST FAILED");
+        }
+    }
+
+    /* ==================================================== */
+
+    static class DefaultValue {
+        public @Stable float v;
+
+        public static final DefaultValue c = new DefaultValue();
+        public static float get() { return c.v; }
+        public static void test() throws Exception {
+                        float val1 = get();
+            c.v = 1.0F; float val2 = get();
+            assertEquals(val1, 0F);
+            assertEquals(val2, 1.0F);
+        }
+    }
+
+    /* ==================================================== */
+
+    static class FloatStable {
+        public @Stable float v;
+
+        public static final FloatStable c = new FloatStable();
+        public static float get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 1.0F; float val1 = get();
+            c.v = 2.0F; float val2 = get();
+            assertEquals(val1, 1.0F);
+            assertEquals(val2, (isStableEnabled ? 1.0F : 2.0F));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class StaticFloatStable {
+        public static @Stable float v;
+
+        public static final StaticFloatStable c = new StaticFloatStable();
+        public static float get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 1.0F; float val1 = get();
+            c.v = 2.0F; float val2 = get();
+            assertEquals(val1, 1.0F);
+            assertEquals(val2, (isStableEnabled ? 1.0F : 2.0F));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class VolatileFloatStable {
+        public @Stable volatile float v;
+
+        public static final VolatileFloatStable c = new VolatileFloatStable();
+        public static float get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 1.0F; float val1 = get();
+            c.v = 2.0F; float val2 = get();
+            assertEquals(val1, 1.0F);
+            assertEquals(val2, (isStableEnabled ? 1.0F : 2.0F));
+        }
+    }
+
+    /* ==================================================== */
+    // @Stable array == field && all components are stable
+
+    static class FloatArrayDim1 {
+        public @Stable float[] v;
+
+        public static final FloatArrayDim1 c = new FloatArrayDim1();
+        public static float get() { return c.v[0]; }
+        public static float get1() { return c.v[10]; }
+        public static float[] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new float[1]; c.v[0] = 1.0F; float val1 = get();
+                                    c.v[0] = 2.0F; float val2 = get();
+                assertEquals(val1, 1.0F);
+                assertEquals(val2, (isStableEnabled ? 1.0F : 2.0F));
+
+                c.v = new float[1]; c.v[0] = 3.0F; float val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1.0F : 3.0F));
+            }
+
+            {
+                c.v = new float[20]; c.v[10] = 1.0F; float val1 = get1();
+                                     c.v[10] = 2.0F; float val2 = get1();
+                assertEquals(val1, 1.0F);
+                assertEquals(val2, (isStableEnabled ? 1.0F : 2.0F));
+
+                c.v = new float[20]; c.v[10] = 3.0F; float val3 = get1();
+                assertEquals(val3, (isStableEnabled ? 1.0F : 3.0F));
+            }
+
+            {
+                c.v = new float[1]; float[] val1 = get2();
+                c.v = new float[1]; float[] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class FloatArrayDim2 {
+        public @Stable float[][] v;
+
+        public static final FloatArrayDim2 c = new FloatArrayDim2();
+        public static float get() { return c.v[0][0]; }
+        public static float[] get1() { return c.v[0]; }
+        public static float[][] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new float[1][1]; c.v[0][0] = 1.0F; float val1 = get();
+                                       c.v[0][0] = 2.0F; float val2 = get();
+                assertEquals(val1, 1.0F);
+                assertEquals(val2, (isStableEnabled ? 1.0F : 2.0F));
+
+                c.v = new float[1][1]; c.v[0][0] = 3.0F; float val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1.0F : 3.0F));
+
+                c.v[0] = new float[1]; c.v[0][0] = 4.0F; float val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1.0F : 4.0F));
+            }
+
+            {
+                c.v = new float[1][1]; float[] val1 = get1();
+                c.v[0] = new float[1]; float[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new float[1][1]; float[][] val1 = get2();
+                c.v = new float[1][1]; float[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class FloatArrayDim3 {
+        public @Stable float[][][] v;
+
+        public static final FloatArrayDim3 c = new FloatArrayDim3();
+        public static float get() { return c.v[0][0][0]; }
+        public static float[] get1() { return c.v[0][0]; }
+        public static float[][] get2() { return c.v[0]; }
+        public static float[][][] get3() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new float[1][1][1]; c.v[0][0][0] = 1.0F; float val1 = get();
+                                          c.v[0][0][0] = 2.0F; float val2 = get();
+                assertEquals(val1, 1.0F);
+                assertEquals(val2, (isStableEnabled ? 1.0F : 2.0F));
+
+                c.v = new float[1][1][1]; c.v[0][0][0] = 3.0F; float val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1.0F : 3.0F));
+
+                c.v[0] = new float[1][1]; c.v[0][0][0] = 4.0F; float val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1.0F : 4.0F));
+
+                c.v[0][0] = new float[1]; c.v[0][0][0] = 5.0F; float val5 = get();
+                assertEquals(val5, (isStableEnabled ? 1.0F : 5.0F));
+            }
+
+            {
+                c.v = new float[1][1][1]; float[] val1 = get1();
+                c.v[0][0] = new float[1]; float[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new float[1][1][1]; float[][] val1 = get2();
+                c.v[0] = new float[1][1]; float[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new float[1][1][1]; float[][][] val1 = get3();
+                c.v = new float[1][1][1]; float[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class FloatArrayDim4 {
+        public @Stable float[][][][] v;
+
+        public static final FloatArrayDim4 c = new FloatArrayDim4();
+        public static float get() { return c.v[0][0][0][0]; }
+        public static float[] get1() { return c.v[0][0][0]; }
+        public static float[][] get2() { return c.v[0][0]; }
+        public static float[][][] get3() { return c.v[0]; }
+        public static float[][][][] get4() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new float[1][1][1][1]; c.v[0][0][0][0] = 1.0F; float val1 = get();
+                                             c.v[0][0][0][0] = 2.0F; float val2 = get();
+                assertEquals(val1, 1.0F);
+                assertEquals(val2, (isStableEnabled ? 1.0F : 2.0F));
+
+                c.v = new float[1][1][1][1]; c.v[0][0][0][0] = 3.0F; float val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1.0F : 3.0F));
+
+                c.v[0] = new float[1][1][1]; c.v[0][0][0][0] = 4.0F; float val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1.0F : 4.0F));
+
+                c.v[0][0] = new float[1][1]; c.v[0][0][0][0] = 5.0F; float val5 = get();
+                assertEquals(val5, (isStableEnabled ? 1.0F : 5.0F));
+
+                c.v[0][0][0] = new float[1]; c.v[0][0][0][0] = 6.0F; float val6 = get();
+                assertEquals(val6, (isStableEnabled ? 1.0F : 6.0F));
+            }
+
+            {
+                c.v = new float[1][1][1][1]; float[] val1 = get1();
+                c.v[0][0][0] = new float[1]; float[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new float[1][1][1][1]; float[][] val1 = get2();
+                c.v[0][0] = new float[1][1]; float[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new float[1][1][1][1]; float[][][] val1 = get3();
+                c.v[0] = new float[1][1][1]; float[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new float[1][1][1][1]; float[][][][] val1 = get4();
+                c.v = new float[1][1][1][1]; float[][][][] val2 = get4();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+        }
+    }
+
+    /* ==================================================== */
+    // Dynamic Dim is higher than static
+
+    static class ObjectArrayLowerDim0 {
+        public @Stable Object v;
+
+        public static final ObjectArrayLowerDim0 c = new ObjectArrayLowerDim0();
+        public static float get() { return ((float[])c.v)[0]; }
+        public static float[] get1() { return (float[])c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new float[1]; ((float[])c.v)[0] = 1.0F; float val1 = get();
+                                    ((float[])c.v)[0] = 2.0F; float val2 = get();
+
+                assertEquals(val1, 1.0F);
+                assertEquals(val2, 2.0F);
+            }
+
+            {
+                c.v = new float[1]; float[] val1 = get1();
+                c.v = new float[1]; float[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim1 {
+        public @Stable Object[] v;
+
+        public static final ObjectArrayLowerDim1 c = new ObjectArrayLowerDim1();
+        public static float get() { return ((float[][])c.v)[0][0]; }
+        public static float[] get1() { return (float[])(c.v[0]); }
+        public static Object[] get2() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new float[1][1]; ((float[][])c.v)[0][0] = 1.0F; float val1 = get();
+                                       ((float[][])c.v)[0][0] = 2.0F; float val2 = get();
+
+                assertEquals(val1, 1.0F);
+                assertEquals(val2, 2.0F);
+            }
+
+            {
+                c.v = new float[1][1]; c.v[0] = new float[0]; float[] val1 = get1();
+                                       c.v[0] = new float[0]; float[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new float[0][0]; Object[] val1 = get2();
+                c.v = new float[0][0]; Object[] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim2 {
+        public @Stable Object[][] v;
+
+        public static final ObjectArrayLowerDim2 c = new ObjectArrayLowerDim2();
+        public static float get() { return ((float[][][])c.v)[0][0][0]; }
+        public static float[] get1() { return (float[])(c.v[0][0]); }
+        public static float[][] get2() { return (float[][])(c.v[0]); }
+        public static Object[][] get3() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new float[1][1][1]; ((float[][][])c.v)[0][0][0] = 1.0F; float val1 = get();
+                                          ((float[][][])c.v)[0][0][0] = 2.0F; float val2 = get();
+
+                assertEquals(val1, 1.0F);
+                assertEquals(val2, 2.0F);
+            }
+
+            {
+                c.v = new float[1][1][1]; c.v[0][0] = new float[0]; float[] val1 = get1();
+                                          c.v[0][0] = new float[0]; float[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new float[1][1][1]; c.v[0] = new float[0][0]; float[][] val1 = get2();
+                                          c.v[0] = new float[0][0]; float[][] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new float[0][0][0]; Object[][] val1 = get3();
+                c.v = new float[0][0][0]; Object[][] val2 = get3();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField {
+        static class A {
+            public @Stable float a;
+
+        }
+        public @Stable A v;
+
+        public static final NestedStableField c = new NestedStableField();
+        public static A get() { return c.v; }
+        public static float get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.a = 1.0F; A val1 = get();
+                               c.v.a = 2.0F; A val2 = get();
+
+                assertEquals(val1.a, 2.0F);
+                assertEquals(val2.a, 2.0F);
+            }
+
+            {
+                c.v = new A(); c.v.a = 1.0F; float val1 = get1();
+                               c.v.a = 2.0F; float val2 = get1();
+                c.v = new A(); c.v.a = 3.0F; float val3 = get1();
+
+                assertEquals(val1, 1.0F);
+                assertEquals(val2, (isStableEnabled ? 1.0F : 2.0F));
+                assertEquals(val3, (isStableEnabled ? 1.0F : 3.0F));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField1 {
+        static class A {
+            public @Stable float a;
+            public @Stable A next;
+        }
+        public @Stable A v;
+
+        public static final NestedStableField1 c = new NestedStableField1();
+        public static A get() { return c.v.next.next.next.next.next.next.next; }
+        public static float get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.next = new A();   c.v.next.next  = c.v;
+                               c.v.a = 1.0F; c.v.next.a = 1.0F; A val1 = get();
+                               c.v.a = 2.0F; c.v.next.a = 2.0F; A val2 = get();
+
+                assertEquals(val1.a, 2.0F);
+                assertEquals(val2.a, 2.0F);
+            }
+
+            {
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 1.0F; float val1 = get1();
+                               c.v.a = 2.0F; float val2 = get1();
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 3.0F; float val3 = get1();
+
+                assertEquals(val1, 1.0F);
+                assertEquals(val2, (isStableEnabled ? 1.0F : 2.0F));
+                assertEquals(val3, (isStableEnabled ? 1.0F : 3.0F));
+            }
+        }
+    }
+   /* ==================================================== */
+
+    static class NestedStableField2 {
+        static class A {
+            public @Stable float a;
+            public @Stable A left;
+            public         A right;
+        }
+
+        public @Stable A v;
+
+        public static final NestedStableField2 c = new NestedStableField2();
+        public static float get() { return c.v.left.left.left.a; }
+        public static float get1() { return c.v.left.left.right.left.a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.left = c.v.right = c.v;
+                               c.v.a = 1.0F; float val1 = get(); float val2 = get1();
+                               c.v.a = 2.0F; float val3 = get(); float val4 = get1();
+
+                assertEquals(val1, 1.0F);
+                assertEquals(val3, (isStableEnabled ? 1.0F : 2.0F));
+
+                assertEquals(val2, 1.0F);
+                assertEquals(val4, 2.0F);
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField3 {
+        static class A {
+            public @Stable float a;
+            public @Stable A[] left;
+            public         A[] right;
+        }
+
+        public @Stable A[] v;
+
+        public static final NestedStableField3 c = new NestedStableField3();
+        public static float get() { return c.v[0].left[1].left[0].left[1].a; }
+        public static float get1() { return c.v[1].left[0].left[1].right[0].left[1].a; }
+
+        public static void test() throws Exception {
+            {
+                A elem = new A();
+                c.v = new A[] { elem, elem }; c.v[0].left = c.v[0].right = c.v;
+                               elem.a = 1.0F; float val1 = get(); float val2 = get1();
+                               elem.a = 2.0F; float val3 = get(); float val4 = get1();
+
+                assertEquals(val1, 1.0F);
+                assertEquals(val3, (isStableEnabled ? 1.0F : 2.0F));
+
+                assertEquals(val2, 1.0F);
+                assertEquals(val4, 2.0F);
+            }
+        }
+    }
+
+    /* ==================================================== */
+    // Auxiliary methods
+    static void assertEquals(float i, float j) { if (i != j)  throw new AssertionError(i + " != " + j); }
+    static void assertTrue(boolean b) { if (!b)  throw new AssertionError(); }
+
+    static boolean failed = false;
+
+    public static void run(Class<?> test) {
+        Throwable ex = null;
+        System.out.print(test.getName()+": ");
+        try {
+            test.getMethod("test").invoke(null);
+        } catch (InvocationTargetException e) {
+            ex = e.getCause();
+        } catch (Throwable e) {
+            ex = e;
+        } finally {
+            if (ex == null) {
+                System.out.println("PASSED");
+            } else {
+                failed = true;
+                System.out.println("FAILED");
+                ex.printStackTrace(System.out);
+            }
+        }
+    }
+
+    static final boolean isStableEnabled;
+    static {
+        HotSpotDiagnosticMXBean diagnostic
+                = ManagementFactoryHelper.getDiagnosticMXBean();
+        VMOption tmp;
+        try {
+            tmp = diagnostic.getVMOption("FoldStableValues");
+        } catch (IllegalArgumentException e) {
+            tmp = null;
+        }
+        isStableEnabled = (tmp == null ? false : Boolean.parseBoolean(tmp.getValue()));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/stable/TestStableInt.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,632 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 TestStableInt
+ * @summary tests on stable fields and arrays
+ * @library /testlibrary
+ * @compile -XDignore.symbol.file TestStableInt.java
+ * @run main ClassFileInstaller
+ *           java/lang/invoke/TestStableInt
+ *           java/lang/invoke/TestStableInt$IntStable
+ *           java/lang/invoke/TestStableInt$StaticIntStable
+ *           java/lang/invoke/TestStableInt$VolatileIntStable
+ *           java/lang/invoke/TestStableInt$IntArrayDim1
+ *           java/lang/invoke/TestStableInt$IntArrayDim2
+ *           java/lang/invoke/TestStableInt$IntArrayDim3
+ *           java/lang/invoke/TestStableInt$IntArrayDim4
+ *           java/lang/invoke/TestStableInt$ObjectArrayLowerDim0
+ *           java/lang/invoke/TestStableInt$ObjectArrayLowerDim1
+ *           java/lang/invoke/TestStableInt$NestedStableField
+ *           java/lang/invoke/TestStableInt$NestedStableField$A
+ *           java/lang/invoke/TestStableInt$NestedStableField1
+ *           java/lang/invoke/TestStableInt$NestedStableField1$A
+ *           java/lang/invoke/TestStableInt$NestedStableField2
+ *           java/lang/invoke/TestStableInt$NestedStableField2$A
+ *           java/lang/invoke/TestStableInt$NestedStableField3
+ *           java/lang/invoke/TestStableInt$NestedStableField3$A
+ *           java/lang/invoke/TestStableInt$DefaultValue
+ *           java/lang/invoke/TestStableInt$ObjectArrayLowerDim2
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableInt
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableInt
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableInt
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableInt
+ */
+package java.lang.invoke;
+
+import com.sun.management.HotSpotDiagnosticMXBean;
+import com.sun.management.VMOption;
+import sun.management.ManagementFactoryHelper;
+import java.lang.reflect.InvocationTargetException;
+
+public class TestStableInt {
+    public static void main(String[] args) throws Exception {
+        System.out.println("@Stable enabled: "+isStableEnabled);
+        System.out.println();
+
+        run(DefaultValue.class);
+        run(IntStable.class);
+        run(StaticIntStable.class);
+        run(VolatileIntStable.class);
+
+        // @Stable arrays: Dim 1-4
+        run(IntArrayDim1.class);
+        run(IntArrayDim2.class);
+        run(IntArrayDim3.class);
+        run(IntArrayDim4.class);
+
+        // @Stable Object field: dynamic arrays
+        run(ObjectArrayLowerDim0.class);
+        run(ObjectArrayLowerDim1.class);
+        run(ObjectArrayLowerDim2.class);
+
+        // Nested @Stable fields
+        run(NestedStableField.class);
+        run(NestedStableField1.class);
+        run(NestedStableField2.class);
+        run(NestedStableField3.class);
+
+        if (failed) {
+            throw new Error("TEST FAILED");
+        }
+    }
+
+    /* ==================================================== */
+
+    static class DefaultValue {
+        public @Stable int v;
+
+        public static final DefaultValue c = new DefaultValue();
+        public static int get() { return c.v; }
+        public static void test() throws Exception {
+                        int val1 = get();
+            c.v = 1; int val2 = get();
+            assertEquals(val1, 0);
+            assertEquals(val2, 1);
+        }
+    }
+
+    /* ==================================================== */
+
+    static class IntStable {
+        public @Stable int v;
+
+        public static final IntStable c = new IntStable();
+        public static int get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 1; int val1 = get();
+            c.v = 2; int val2 = get();
+            assertEquals(val1, 1);
+            assertEquals(val2, (isStableEnabled ? 1 : 2));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class StaticIntStable {
+        public static @Stable int v;
+
+        public static final StaticIntStable c = new StaticIntStable();
+        public static int get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 1; int val1 = get();
+            c.v = 2; int val2 = get();
+            assertEquals(val1, 1);
+            assertEquals(val2, (isStableEnabled ? 1 : 2));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class VolatileIntStable {
+        public @Stable volatile int v;
+
+        public static final VolatileIntStable c = new VolatileIntStable();
+        public static int get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 1; int val1 = get();
+            c.v = 2; int val2 = get();
+            assertEquals(val1, 1);
+            assertEquals(val2, (isStableEnabled ? 1 : 2));
+        }
+    }
+
+    /* ==================================================== */
+    // @Stable array == field && all components are stable
+
+    static class IntArrayDim1 {
+        public @Stable int[] v;
+
+        public static final IntArrayDim1 c = new IntArrayDim1();
+        public static int get() { return c.v[0]; }
+        public static int get1() { return c.v[10]; }
+        public static int[] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new int[1]; c.v[0] = 1; int val1 = get();
+                                  c.v[0] = 2; int val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new int[1]; c.v[0] = 3; int val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+
+            {
+                c.v = new int[20]; c.v[10] = 1; int val1 = get1();
+                                   c.v[10] = 2; int val2 = get1();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new int[20]; c.v[10] = 3; int val3 = get1();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+
+            {
+                c.v = new int[1]; int[] val1 = get2();
+                c.v = new int[1]; int[] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class IntArrayDim2 {
+        public @Stable int[][] v;
+
+        public static final IntArrayDim2 c = new IntArrayDim2();
+        public static int get() { return c.v[0][0]; }
+        public static int[] get1() { return c.v[0]; }
+        public static int[][] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new int[1][1]; c.v[0][0] = 1; int val1 = get();
+                                     c.v[0][0] = 2; int val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new int[1][1]; c.v[0][0] = 3; int val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+
+                c.v[0] = new int[1]; c.v[0][0] = 4; int val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1 : 4));
+            }
+
+            {
+                c.v = new int[1][1]; int[] val1 = get1();
+                c.v[0] = new int[1]; int[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new int[1][1]; int[][] val1 = get2();
+                c.v = new int[1][1]; int[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class IntArrayDim3 {
+        public @Stable int[][][] v;
+
+        public static final IntArrayDim3 c = new IntArrayDim3();
+        public static int get() { return c.v[0][0][0]; }
+        public static int[] get1() { return c.v[0][0]; }
+        public static int[][] get2() { return c.v[0]; }
+        public static int[][][] get3() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new int[1][1][1]; c.v[0][0][0] = 1; int val1 = get();
+                                        c.v[0][0][0] = 2; int val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new int[1][1][1]; c.v[0][0][0] = 3; int val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+
+                c.v[0] = new int[1][1]; c.v[0][0][0] = 4; int val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1 : 4));
+
+                c.v[0][0] = new int[1]; c.v[0][0][0] = 5; int val5 = get();
+                assertEquals(val5, (isStableEnabled ? 1 : 5));
+            }
+
+            {
+                c.v = new int[1][1][1]; int[] val1 = get1();
+                c.v[0][0] = new int[1]; int[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new int[1][1][1]; int[][] val1 = get2();
+                c.v[0] = new int[1][1]; int[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new int[1][1][1]; int[][][] val1 = get3();
+                c.v = new int[1][1][1]; int[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class IntArrayDim4 {
+        public @Stable int[][][][] v;
+
+        public static final IntArrayDim4 c = new IntArrayDim4();
+        public static int get() { return c.v[0][0][0][0]; }
+        public static int[] get1() { return c.v[0][0][0]; }
+        public static int[][] get2() { return c.v[0][0]; }
+        public static int[][][] get3() { return c.v[0]; }
+        public static int[][][][] get4() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new int[1][1][1][1]; c.v[0][0][0][0] = 1; int val1 = get();
+                                           c.v[0][0][0][0] = 2; int val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new int[1][1][1][1]; c.v[0][0][0][0] = 3; int val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+
+                c.v[0] = new int[1][1][1]; c.v[0][0][0][0] = 4; int val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1 : 4));
+
+                c.v[0][0] = new int[1][1]; c.v[0][0][0][0] = 5; int val5 = get();
+                assertEquals(val5, (isStableEnabled ? 1 : 5));
+
+                c.v[0][0][0] = new int[1]; c.v[0][0][0][0] = 6; int val6 = get();
+                assertEquals(val6, (isStableEnabled ? 1 : 6));
+            }
+
+            {
+                c.v = new int[1][1][1][1]; int[] val1 = get1();
+                c.v[0][0][0] = new int[1]; int[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new int[1][1][1][1]; int[][] val1 = get2();
+                c.v[0][0] = new int[1][1]; int[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new int[1][1][1][1]; int[][][] val1 = get3();
+                c.v[0] = new int[1][1][1]; int[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new int[1][1][1][1]; int[][][][] val1 = get4();
+                c.v = new int[1][1][1][1]; int[][][][] val2 = get4();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+        }
+    }
+
+    /* ==================================================== */
+    // Dynamic Dim is higher than static
+
+    static class ObjectArrayLowerDim0 {
+        public @Stable Object v;
+
+        public static final ObjectArrayLowerDim0 c = new ObjectArrayLowerDim0();
+        public static int get() { return ((int[])c.v)[0]; }
+        public static int[] get1() { return (int[])c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new int[1]; ((int[])c.v)[0] = 1; int val1 = get();
+                                  ((int[])c.v)[0] = 2; int val2 = get();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, 2);
+            }
+
+            {
+                c.v = new int[1]; int[] val1 = get1();
+                c.v = new int[1]; int[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim1 {
+        public @Stable Object[] v;
+
+        public static final ObjectArrayLowerDim1 c = new ObjectArrayLowerDim1();
+        public static int get() { return ((int[][])c.v)[0][0]; }
+        public static int[] get1() { return (int[])(c.v[0]); }
+        public static Object[] get2() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new int[1][1]; ((int[][])c.v)[0][0] = 1; int val1 = get();
+                                     ((int[][])c.v)[0][0] = 2; int val2 = get();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, 2);
+            }
+
+            {
+                c.v = new int[1][1]; c.v[0] = new int[0]; int[] val1 = get1();
+                                     c.v[0] = new int[0]; int[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new int[0][0]; Object[] val1 = get2();
+                c.v = new int[0][0]; Object[] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim2 {
+        public @Stable Object[][] v;
+
+        public static final ObjectArrayLowerDim2 c = new ObjectArrayLowerDim2();
+        public static int get() { return ((int[][][])c.v)[0][0][0]; }
+        public static int[] get1() { return (int[])(c.v[0][0]); }
+        public static int[][] get2() { return (int[][])(c.v[0]); }
+        public static Object[][] get3() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new int[1][1][1]; ((int[][][])c.v)[0][0][0] = 1; int val1 = get();
+                                        ((int[][][])c.v)[0][0][0] = 2; int val2 = get();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, 2);
+            }
+
+            {
+                c.v = new int[1][1][1]; c.v[0][0] = new int[0]; int[] val1 = get1();
+                                        c.v[0][0] = new int[0]; int[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new int[1][1][1]; c.v[0] = new int[0][0]; int[][] val1 = get2();
+                                        c.v[0] = new int[0][0]; int[][] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new int[0][0][0]; Object[][] val1 = get3();
+                c.v = new int[0][0][0]; Object[][] val2 = get3();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField {
+        static class A {
+            public @Stable int a;
+
+        }
+        public @Stable A v;
+
+        public static final NestedStableField c = new NestedStableField();
+        public static A get() { return c.v; }
+        public static int get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.a = 1; A val1 = get();
+                               c.v.a = 2; A val2 = get();
+
+                assertEquals(val1.a, 2);
+                assertEquals(val2.a, 2);
+            }
+
+            {
+                c.v = new A(); c.v.a = 1; int val1 = get1();
+                               c.v.a = 2; int val2 = get1();
+                c.v = new A(); c.v.a = 3; int val3 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField1 {
+        static class A {
+            public @Stable int a;
+            public @Stable A next;
+        }
+        public @Stable A v;
+
+        public static final NestedStableField1 c = new NestedStableField1();
+        public static A get() { return c.v.next.next.next.next.next.next.next; }
+        public static int get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.next = new A();   c.v.next.next  = c.v;
+                               c.v.a = 1; c.v.next.a = 1; A val1 = get();
+                               c.v.a = 2; c.v.next.a = 2; A val2 = get();
+
+                assertEquals(val1.a, 2);
+                assertEquals(val2.a, 2);
+            }
+
+            {
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 1; int val1 = get1();
+                               c.v.a = 2; int val2 = get1();
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 3; int val3 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+        }
+    }
+   /* ==================================================== */
+
+    static class NestedStableField2 {
+        static class A {
+            public @Stable int a;
+            public @Stable A left;
+            public         A right;
+        }
+
+        public @Stable A v;
+
+        public static final NestedStableField2 c = new NestedStableField2();
+        public static int get() { return c.v.left.left.left.a; }
+        public static int get1() { return c.v.left.left.right.left.a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.left = c.v.right = c.v;
+                               c.v.a = 1; int val1 = get(); int val2 = get1();
+                               c.v.a = 2; int val3 = get(); int val4 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val3, (isStableEnabled ? 1 : 2));
+
+                assertEquals(val2, 1);
+                assertEquals(val4, 2);
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField3 {
+        static class A {
+            public @Stable int a;
+            public @Stable A[] left;
+            public         A[] right;
+        }
+
+        public @Stable A[] v;
+
+        public static final NestedStableField3 c = new NestedStableField3();
+        public static int get() { return c.v[0].left[1].left[0].left[1].a; }
+        public static int get1() { return c.v[1].left[0].left[1].right[0].left[1].a; }
+
+        public static void test() throws Exception {
+            {
+                A elem = new A();
+                c.v = new A[] { elem, elem }; c.v[0].left = c.v[0].right = c.v;
+                               elem.a = 1; int val1 = get(); int val2 = get1();
+                               elem.a = 2; int val3 = get(); int val4 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val3, (isStableEnabled ? 1 : 2));
+
+                assertEquals(val2, 1);
+                assertEquals(val4, 2);
+            }
+        }
+    }
+
+    /* ==================================================== */
+    // Auxiliary methods
+    static void assertEquals(int i, int j) { if (i != j)  throw new AssertionError(i + " != " + j); }
+    static void assertTrue(boolean b) { if (!b)  throw new AssertionError(); }
+
+    static boolean failed = false;
+
+    public static void run(Class<?> test) {
+        Throwable ex = null;
+        System.out.print(test.getName()+": ");
+        try {
+            test.getMethod("test").invoke(null);
+        } catch (InvocationTargetException e) {
+            ex = e.getCause();
+        } catch (Throwable e) {
+            ex = e;
+        } finally {
+            if (ex == null) {
+                System.out.println("PASSED");
+            } else {
+                failed = true;
+                System.out.println("FAILED");
+                ex.printStackTrace(System.out);
+            }
+        }
+    }
+
+    static final boolean isStableEnabled;
+    static {
+        HotSpotDiagnosticMXBean diagnostic
+                = ManagementFactoryHelper.getDiagnosticMXBean();
+        VMOption tmp;
+        try {
+            tmp = diagnostic.getVMOption("FoldStableValues");
+        } catch (IllegalArgumentException e) {
+            tmp = null;
+        }
+        isStableEnabled = (tmp == null ? false : Boolean.parseBoolean(tmp.getValue()));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/stable/TestStableLong.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,632 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 TestStableLong
+ * @summary tests on stable fields and arrays
+ * @library /testlibrary
+ * @compile -XDignore.symbol.file TestStableLong.java
+ * @run main ClassFileInstaller
+ *           java/lang/invoke/TestStableLong
+ *           java/lang/invoke/TestStableLong$LongStable
+ *           java/lang/invoke/TestStableLong$StaticLongStable
+ *           java/lang/invoke/TestStableLong$VolatileLongStable
+ *           java/lang/invoke/TestStableLong$LongArrayDim1
+ *           java/lang/invoke/TestStableLong$LongArrayDim2
+ *           java/lang/invoke/TestStableLong$LongArrayDim3
+ *           java/lang/invoke/TestStableLong$LongArrayDim4
+ *           java/lang/invoke/TestStableLong$ObjectArrayLowerDim0
+ *           java/lang/invoke/TestStableLong$ObjectArrayLowerDim1
+ *           java/lang/invoke/TestStableLong$NestedStableField
+ *           java/lang/invoke/TestStableLong$NestedStableField$A
+ *           java/lang/invoke/TestStableLong$NestedStableField1
+ *           java/lang/invoke/TestStableLong$NestedStableField1$A
+ *           java/lang/invoke/TestStableLong$NestedStableField2
+ *           java/lang/invoke/TestStableLong$NestedStableField2$A
+ *           java/lang/invoke/TestStableLong$NestedStableField3
+ *           java/lang/invoke/TestStableLong$NestedStableField3$A
+ *           java/lang/invoke/TestStableLong$DefaultValue
+ *           java/lang/invoke/TestStableLong$ObjectArrayLowerDim2
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableLong
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableLong
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableLong
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableLong
+ */
+package java.lang.invoke;
+
+import com.sun.management.HotSpotDiagnosticMXBean;
+import com.sun.management.VMOption;
+import sun.management.ManagementFactoryHelper;
+import java.lang.reflect.InvocationTargetException;
+
+public class TestStableLong {
+    public static void main(String[] args) throws Exception {
+        System.out.println("@Stable enabled: "+isStableEnabled);
+        System.out.println();
+
+        run(DefaultValue.class);
+        run(LongStable.class);
+        run(StaticLongStable.class);
+        run(VolatileLongStable.class);
+
+        // @Stable arrays: Dim 1-4
+        run(LongArrayDim1.class);
+        run(LongArrayDim2.class);
+        run(LongArrayDim3.class);
+        run(LongArrayDim4.class);
+
+        // @Stable Object field: dynamic arrays
+        run(ObjectArrayLowerDim0.class);
+        run(ObjectArrayLowerDim1.class);
+        run(ObjectArrayLowerDim2.class);
+
+        // Nested @Stable fields
+        run(NestedStableField.class);
+        run(NestedStableField1.class);
+        run(NestedStableField2.class);
+        run(NestedStableField3.class);
+
+        if (failed) {
+            throw new Error("TEST FAILED");
+        }
+    }
+
+    /* ==================================================== */
+
+    static class DefaultValue {
+        public @Stable long v;
+
+        public static final DefaultValue c = new DefaultValue();
+        public static long get() { return c.v; }
+        public static void test() throws Exception {
+                      long val1 = get();
+            c.v = 1L; long val2 = get();
+            assertEquals(val1, 0);
+            assertEquals(val2, 1L);
+        }
+    }
+
+    /* ==================================================== */
+
+    static class LongStable {
+        public @Stable long v;
+
+        public static final LongStable c = new LongStable();
+        public static long get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 5;              long val1 = get();
+            c.v = Long.MAX_VALUE; long val2 = get();
+            assertEquals(val1, 5);
+            assertEquals(val2, (isStableEnabled ? 5 : Long.MAX_VALUE));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class StaticLongStable {
+        public static @Stable long v;
+
+        public static final StaticLongStable c = new StaticLongStable();
+        public static long get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 5;              long val1 = get();
+            c.v = Long.MAX_VALUE; long val2 = get();
+            assertEquals(val1, 5);
+            assertEquals(val2, (isStableEnabled ? 5 : Long.MAX_VALUE));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class VolatileLongStable {
+        public @Stable volatile long v;
+
+        public static final VolatileLongStable c = new VolatileLongStable();
+        public static long get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 5;              long val1 = get();
+            c.v = Long.MAX_VALUE; long val2 = get();
+            assertEquals(val1, 5);
+            assertEquals(val2, (isStableEnabled ? 5 : Long.MAX_VALUE));
+        }
+    }
+
+    /* ==================================================== */
+    // @Stable array == field && all components are stable
+
+    static class LongArrayDim1 {
+        public @Stable long[] v;
+
+        public static final LongArrayDim1 c = new LongArrayDim1();
+        public static long get() { return c.v[0]; }
+        public static long get1() { return c.v[10]; }
+        public static long[] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new long[1]; c.v[0] = 1; long val1 = get();
+                                   c.v[0] = 2; long val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new long[1]; c.v[0] = 3; long val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+
+            {
+                c.v = new long[20]; c.v[10] = 1; long val1 = get1();
+                                    c.v[10] = 2; long val2 = get1();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new long[20]; c.v[10] = 3; long val3 = get1();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+
+            {
+                c.v = new long[1]; long[] val1 = get2();
+                c.v = new long[1]; long[] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class LongArrayDim2 {
+        public @Stable long[][] v;
+
+        public static final LongArrayDim2 c = new LongArrayDim2();
+        public static long get() { return c.v[0][0]; }
+        public static long[] get1() { return c.v[0]; }
+        public static long[][] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new long[1][1]; c.v[0][0] = 1; long val1 = get();
+                                      c.v[0][0] = 2; long val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new long[1][1]; c.v[0][0] = 3; long val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+
+                c.v[0] = new long[1]; c.v[0][0] = 4; long val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1 : 4));
+            }
+
+            {
+                c.v = new long[1][1]; long[] val1 = get1();
+                c.v[0] = new long[1]; long[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new long[1][1]; long[][] val1 = get2();
+                c.v = new long[1][1]; long[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class LongArrayDim3 {
+        public @Stable long[][][] v;
+
+        public static final LongArrayDim3 c = new LongArrayDim3();
+        public static long get() { return c.v[0][0][0]; }
+        public static long[] get1() { return c.v[0][0]; }
+        public static long[][] get2() { return c.v[0]; }
+        public static long[][][] get3() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new long[1][1][1]; c.v[0][0][0] = 1; long val1 = get();
+                                         c.v[0][0][0] = 2; long val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new long[1][1][1]; c.v[0][0][0] = 3; long val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+
+                c.v[0] = new long[1][1]; c.v[0][0][0] = 4; long val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1 : 4));
+
+                c.v[0][0] = new long[1]; c.v[0][0][0] = 5; long val5 = get();
+                assertEquals(val5, (isStableEnabled ? 1 : 5));
+            }
+
+            {
+                c.v = new long[1][1][1]; long[] val1 = get1();
+                c.v[0][0] = new long[1]; long[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new long[1][1][1]; long[][] val1 = get2();
+                c.v[0] = new long[1][1]; long[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new long[1][1][1]; long[][][] val1 = get3();
+                c.v = new long[1][1][1]; long[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class LongArrayDim4 {
+        public @Stable long[][][][] v;
+
+        public static final LongArrayDim4 c = new LongArrayDim4();
+        public static long get() { return c.v[0][0][0][0]; }
+        public static long[] get1() { return c.v[0][0][0]; }
+        public static long[][] get2() { return c.v[0][0]; }
+        public static long[][][] get3() { return c.v[0]; }
+        public static long[][][][] get4() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new long[1][1][1][1]; c.v[0][0][0][0] = 1; long val1 = get();
+                                            c.v[0][0][0][0] = 2; long val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new long[1][1][1][1]; c.v[0][0][0][0] = 3; long val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+
+                c.v[0] = new long[1][1][1]; c.v[0][0][0][0] = 4; long val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1 : 4));
+
+                c.v[0][0] = new long[1][1]; c.v[0][0][0][0] = 5; long val5 = get();
+                assertEquals(val5, (isStableEnabled ? 1 : 5));
+
+                c.v[0][0][0] = new long[1]; c.v[0][0][0][0] = 6; long val6 = get();
+                assertEquals(val6, (isStableEnabled ? 1 : 6));
+            }
+
+            {
+                c.v = new long[1][1][1][1]; long[] val1 = get1();
+                c.v[0][0][0] = new long[1]; long[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new long[1][1][1][1]; long[][] val1 = get2();
+                c.v[0][0] = new long[1][1]; long[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new long[1][1][1][1]; long[][][] val1 = get3();
+                c.v[0] = new long[1][1][1]; long[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new long[1][1][1][1]; long[][][][] val1 = get4();
+                c.v = new long[1][1][1][1]; long[][][][] val2 = get4();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+        }
+    }
+
+    /* ==================================================== */
+    // Dynamic Dim is higher than static
+
+    static class ObjectArrayLowerDim0 {
+        public @Stable Object v;
+
+        public static final ObjectArrayLowerDim0 c = new ObjectArrayLowerDim0();
+        public static long get() { return ((long[])c.v)[0]; }
+        public static long[] get1() { return (long[])c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new long[1]; ((long[])c.v)[0] = 1; long val1 = get();
+                                   ((long[])c.v)[0] = 2; long val2 = get();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, 2);
+            }
+
+            {
+                c.v = new long[1]; long[] val1 = get1();
+                c.v = new long[1]; long[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim1 {
+        public @Stable Object[] v;
+
+        public static final ObjectArrayLowerDim1 c = new ObjectArrayLowerDim1();
+        public static long get() { return ((long[][])c.v)[0][0]; }
+        public static long[] get1() { return (long[])(c.v[0]); }
+        public static Object[] get2() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new long[1][1]; ((long[][])c.v)[0][0] = 1; long val1 = get();
+                                      ((long[][])c.v)[0][0] = 2; long val2 = get();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, 2);
+            }
+
+            {
+                c.v = new long[1][1]; c.v[0] = new long[0]; long[] val1 = get1();
+                                     c.v[0] = new long[0]; long[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new long[0][0]; Object[] val1 = get2();
+                c.v = new long[0][0]; Object[] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim2 {
+        public @Stable Object[][] v;
+
+        public static final ObjectArrayLowerDim2 c = new ObjectArrayLowerDim2();
+        public static long get() { return ((long[][][])c.v)[0][0][0]; }
+        public static long[] get1() { return (long[])(c.v[0][0]); }
+        public static long[][] get2() { return (long[][])(c.v[0]); }
+        public static Object[][] get3() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new long[1][1][1]; ((long[][][])c.v)[0][0][0] = 1L; long val1 = get();
+                                         ((long[][][])c.v)[0][0][0] = 2L; long val2 = get();
+
+                assertEquals(val1, 1L);
+                assertEquals(val2, 2L);
+            }
+
+            {
+                c.v = new long[1][1][1]; c.v[0][0] = new long[0]; long[] val1 = get1();
+                                         c.v[0][0] = new long[0]; long[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new long[1][1][1]; c.v[0] = new long[0][0]; long[][] val1 = get2();
+                                         c.v[0] = new long[0][0]; long[][] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new long[0][0][0]; Object[][] val1 = get3();
+                c.v = new long[0][0][0]; Object[][] val2 = get3();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField {
+        static class A {
+            public @Stable long a;
+
+        }
+        public @Stable A v;
+
+        public static final NestedStableField c = new NestedStableField();
+        public static A get() { return c.v; }
+        public static long get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.a = 1; A val1 = get();
+                               c.v.a = 2; A val2 = get();
+
+                assertEquals(val1.a, 2);
+                assertEquals(val2.a, 2);
+            }
+
+            {
+                c.v = new A(); c.v.a = 1; long val1 = get1();
+                               c.v.a = 2; long val2 = get1();
+                c.v = new A(); c.v.a = 3; long val3 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField1 {
+        static class A {
+            public @Stable long a;
+            public @Stable A next;
+        }
+        public @Stable A v;
+
+        public static final NestedStableField1 c = new NestedStableField1();
+        public static A get() { return c.v.next.next.next.next.next.next.next; }
+        public static long get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.next = new A();   c.v.next.next  = c.v;
+                               c.v.a = 1; c.v.next.a = 1; A val1 = get();
+                               c.v.a = 2; c.v.next.a = 2; A val2 = get();
+
+                assertEquals(val1.a, 2);
+                assertEquals(val2.a, 2);
+            }
+
+            {
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 1; long val1 = get1();
+                               c.v.a = 2; long val2 = get1();
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 3; long val3 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+        }
+    }
+   /* ==================================================== */
+
+    static class NestedStableField2 {
+        static class A {
+            public @Stable long a;
+            public @Stable A left;
+            public         A right;
+        }
+
+        public @Stable A v;
+
+        public static final NestedStableField2 c = new NestedStableField2();
+        public static long get() { return c.v.left.left.left.a; }
+        public static long get1() { return c.v.left.left.right.left.a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.left = c.v.right = c.v;
+                               c.v.a = 1; long val1 = get(); long val2 = get1();
+                               c.v.a = 2; long val3 = get(); long val4 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val3, (isStableEnabled ? 1 : 2));
+
+                assertEquals(val2, 1);
+                assertEquals(val4, 2);
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField3 {
+        static class A {
+            public @Stable long a;
+            public @Stable A[] left;
+            public         A[] right;
+        }
+
+        public @Stable A[] v;
+
+        public static final NestedStableField3 c = new NestedStableField3();
+        public static long get() { return c.v[0].left[1].left[0].left[1].a; }
+        public static long get1() { return c.v[1].left[0].left[1].right[0].left[1].a; }
+
+        public static void test() throws Exception {
+            {
+                A elem = new A();
+                c.v = new A[] { elem, elem }; c.v[0].left = c.v[0].right = c.v;
+                               elem.a = 1; long val1 = get(); long val2 = get1();
+                               elem.a = 2; long val3 = get(); long val4 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val3, (isStableEnabled ? 1 : 2));
+
+                assertEquals(val2, 1);
+                assertEquals(val4, 2);
+            }
+        }
+    }
+
+    /* ==================================================== */
+    // Auxiliary methods
+    static void assertEquals(long i, long j) { if (i != j)  throw new AssertionError(i + " != " + j); }
+    static void assertTrue(boolean b) { if (!b)  throw new AssertionError(); }
+
+    static boolean failed = false;
+
+    public static void run(Class<?> test) {
+        Throwable ex = null;
+        System.out.print(test.getName()+": ");
+        try {
+            test.getMethod("test").invoke(null);
+        } catch (InvocationTargetException e) {
+            ex = e.getCause();
+        } catch (Throwable e) {
+            ex = e;
+        } finally {
+            if (ex == null) {
+                System.out.println("PASSED");
+            } else {
+                failed = true;
+                System.out.println("FAILED");
+                ex.printStackTrace(System.out);
+            }
+        }
+    }
+
+    static final boolean isStableEnabled;
+    static {
+        HotSpotDiagnosticMXBean diagnostic
+                = ManagementFactoryHelper.getDiagnosticMXBean();
+        VMOption tmp;
+        try {
+            tmp = diagnostic.getVMOption("FoldStableValues");
+        } catch (IllegalArgumentException e) {
+            tmp = null;
+        }
+        isStableEnabled = (tmp == null ? false : Boolean.parseBoolean(tmp.getValue()));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/stable/TestStableObject.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,635 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 TestStableObject
+ * @summary tests on stable fields and arrays
+ * @library /testlibrary
+ * @compile -XDignore.symbol.file TestStableObject.java
+ * @run main ClassFileInstaller
+ *           java/lang/invoke/TestStableObject
+ *           java/lang/invoke/TestStableObject$ObjectStable
+ *           java/lang/invoke/TestStableObject$StaticObjectStable
+ *           java/lang/invoke/TestStableObject$VolatileObjectStable
+ *           java/lang/invoke/TestStableObject$ObjectArrayDim1
+ *           java/lang/invoke/TestStableObject$ObjectArrayDim2
+ *           java/lang/invoke/TestStableObject$ObjectArrayDim3
+ *           java/lang/invoke/TestStableObject$ObjectArrayDim4
+ *           java/lang/invoke/TestStableObject$ObjectArrayLowerDim0
+ *           java/lang/invoke/TestStableObject$ObjectArrayLowerDim1
+ *           java/lang/invoke/TestStableObject$NestedStableField
+ *           java/lang/invoke/TestStableObject$NestedStableField$A
+ *           java/lang/invoke/TestStableObject$NestedStableField1
+ *           java/lang/invoke/TestStableObject$NestedStableField1$A
+ *           java/lang/invoke/TestStableObject$NestedStableField2
+ *           java/lang/invoke/TestStableObject$NestedStableField2$A
+ *           java/lang/invoke/TestStableObject$NestedStableField3
+ *           java/lang/invoke/TestStableObject$NestedStableField3$A
+ *           java/lang/invoke/TestStableObject$Values
+ *           java/lang/invoke/TestStableObject$DefaultValue
+ *           java/lang/invoke/TestStableObject$ObjectArrayLowerDim2
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableObject
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableObject
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableObject
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableObject
+ */
+package java.lang.invoke;
+
+import com.sun.management.HotSpotDiagnosticMXBean;
+import com.sun.management.VMOption;
+import sun.management.ManagementFactoryHelper;
+import java.lang.reflect.InvocationTargetException;
+
+public class TestStableObject {
+    public static void main(String[] args) throws Exception {
+        System.out.println("@Stable enabled: "+isStableEnabled);
+        System.out.println();
+
+        run(DefaultValue.class);
+        run(ObjectStable.class);
+        run(StaticObjectStable.class);
+        run(VolatileObjectStable.class);
+
+        // @Stable arrays: Dim 1-4
+        run(ObjectArrayDim1.class);
+        run(ObjectArrayDim2.class);
+        run(ObjectArrayDim3.class);
+        run(ObjectArrayDim4.class);
+
+        // @Stable Object field: dynamic arrays
+        run(ObjectArrayLowerDim0.class);
+        run(ObjectArrayLowerDim1.class);
+        run(ObjectArrayLowerDim2.class);
+
+        // Nested @Stable fields
+        run(NestedStableField.class);
+        run(NestedStableField1.class);
+        run(NestedStableField2.class);
+        run(NestedStableField3.class);
+
+        if (failed) {
+            throw new Error("TEST FAILED");
+        }
+    }
+
+    /* ==================================================== */
+
+    enum Values {A, B, C, D, E, F}
+
+    static class DefaultValue {
+        public @Stable Object v;
+
+        public static final DefaultValue c = new DefaultValue();
+        public static Object get() { return c.v; }
+        public static void test() throws Exception {
+                            Object val1 = get();
+            c.v = Values.A; Object val2 = get();
+            assertEquals(val1, null);
+            assertEquals(val2, Values.A);
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectStable {
+        public @Stable Values v;
+
+        public static final ObjectStable c = new ObjectStable ();
+        public static Values get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = Values.A; Values val1 = get();
+            c.v = Values.B; Values val2 = get();
+            assertEquals(val1, Values.A);
+            assertEquals(val2, (isStableEnabled ? Values.A : Values.B));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class StaticObjectStable {
+        public static @Stable Values v;
+
+        public static final ObjectStable c = new ObjectStable ();
+        public static Values get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = Values.A; Values val1 = get();
+            c.v = Values.B; Values val2 = get();
+            assertEquals(val1, Values.A);
+            assertEquals(val2, (isStableEnabled ? Values.A : Values.B));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class VolatileObjectStable {
+        public @Stable volatile Values v;
+
+        public static final VolatileObjectStable c = new VolatileObjectStable ();
+        public static Values get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = Values.A; Values val1 = get();
+            c.v = Values.B; Values val2 = get();
+            assertEquals(val1, Values.A);
+            assertEquals(val2, (isStableEnabled ? Values.A : Values.B));
+        }
+    }
+
+    /* ==================================================== */
+    // @Stable array == field && all components are stable
+
+    static class ObjectArrayDim1 {
+        public @Stable Object[] v;
+
+        public static final ObjectArrayDim1 c = new ObjectArrayDim1();
+        public static Object get() { return c.v[0]; }
+        public static Object get1() { return c.v[10]; }
+        public static Object[] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new Object[1]; c.v[0] = Values.A; Object val1 = get();
+                                     c.v[0] = Values.B; Object val2 = get();
+                assertEquals(val1, Values.A);
+                assertEquals(val2, (isStableEnabled ? Values.A : Values.B));
+
+                c.v = new Object[1]; c.v[0] = Values.C; Object val3 = get();
+                assertEquals(val3, (isStableEnabled ? Values.A : Values.C));
+            }
+
+            {
+                c.v = new Object[20]; c.v[10] = Values.A; Object val1 = get1();
+                                      c.v[10] = Values.B; Object val2 = get1();
+                assertEquals(val1, Values.A);
+                assertEquals(val2, (isStableEnabled ? Values.A : Values.B));
+
+                c.v = new Object[20]; c.v[10] = Values.C; Object val3 = get1();
+                assertEquals(val3, (isStableEnabled ? Values.A : Values.C));
+            }
+
+            {
+                c.v = new Object[1]; Object[] val1 = get2();
+                c.v = new Object[1]; Object[] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayDim2 {
+        public @Stable Object[][] v;
+
+        public static final ObjectArrayDim2 c = new ObjectArrayDim2();
+        public static Object get() { return c.v[0][0]; }
+        public static Object[] get1() { return c.v[0]; }
+        public static Object[][] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new Object[1][1]; c.v[0][0] = Values.A; Object val1 = get();
+                                        c.v[0][0] = Values.B; Object val2 = get();
+                assertEquals(val1, Values.A);
+                assertEquals(val2, (isStableEnabled ? Values.A : Values.B));
+
+                c.v = new Object[1][1]; c.v[0][0] = Values.C; Object val3 = get();
+                assertEquals(val3, (isStableEnabled ? Values.A : Values.C));
+
+                c.v[0] = new Object[1]; c.v[0][0] = Values.D; Object val4 = get();
+                assertEquals(val4, (isStableEnabled ? Values.A : Values.D));
+            }
+
+            {
+                c.v = new Object[1][1]; Object[] val1 = get1();
+                c.v[0] = new Object[1]; Object[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new Object[1][1]; Object[][] val1 = get2();
+                c.v = new Object[1][1]; Object[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayDim3 {
+        public @Stable Object[][][] v;
+
+        public static final ObjectArrayDim3 c = new ObjectArrayDim3();
+        public static Object get() { return c.v[0][0][0]; }
+        public static Object[] get1() { return c.v[0][0]; }
+        public static Object[][] get2() { return c.v[0]; }
+        public static Object[][][] get3() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new Object[1][1][1]; c.v[0][0][0] = Values.A; Object val1 = get();
+                                           c.v[0][0][0] = Values.B; Object val2 = get();
+                assertEquals(val1, Values.A);
+                assertEquals(val2, (isStableEnabled ? Values.A : Values.B));
+
+                c.v = new Object[1][1][1]; c.v[0][0][0] = Values.C; Object val3 = get();
+                assertEquals(val3, (isStableEnabled ? Values.A : Values.C));
+
+                c.v[0] = new Object[1][1]; c.v[0][0][0] = Values.D; Object val4 = get();
+                assertEquals(val4, (isStableEnabled ? Values.A : Values.D));
+
+                c.v[0][0] = new Object[1]; c.v[0][0][0] = Values.E; Object val5 = get();
+                assertEquals(val5, (isStableEnabled ? Values.A : Values.E));
+            }
+
+            {
+                c.v = new Object[1][1][1]; Object[] val1 = get1();
+                c.v[0][0] = new Object[1]; Object[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new Object[1][1][1]; Object[][] val1 = get2();
+                c.v[0] = new Object[1][1]; Object[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new Object[1][1][1]; Object[][][] val1 = get3();
+                c.v = new Object[1][1][1]; Object[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayDim4 {
+        public @Stable Object[][][][] v;
+
+        public static final ObjectArrayDim4 c = new ObjectArrayDim4();
+        public static Object get() { return c.v[0][0][0][0]; }
+        public static Object[] get1() { return c.v[0][0][0]; }
+        public static Object[][] get2() { return c.v[0][0]; }
+        public static Object[][][] get3() { return c.v[0]; }
+        public static Object[][][][] get4() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new Object[1][1][1][1]; c.v[0][0][0][0] = Values.A; Object val1 = get();
+                                              c.v[0][0][0][0] = Values.B; Object val2 = get();
+                assertEquals(val1, Values.A);
+                assertEquals(val2, (isStableEnabled ? Values.A : Values.B));
+
+                c.v = new Object[1][1][1][1]; c.v[0][0][0][0] = Values.C; Object val3 = get();
+                assertEquals(val3, (isStableEnabled ? Values.A : Values.C));
+
+                c.v[0] = new Object[1][1][1]; c.v[0][0][0][0] = Values.D; Object val4 = get();
+                assertEquals(val4, (isStableEnabled ? Values.A : Values.D));
+
+                c.v[0][0] = new Object[1][1]; c.v[0][0][0][0] = Values.E; Object val5 = get();
+                assertEquals(val5, (isStableEnabled ? Values.A : Values.E));
+
+                c.v[0][0][0] = new Object[1]; c.v[0][0][0][0] = Values.F; Object val6 = get();
+                assertEquals(val6, (isStableEnabled ? Values.A : Values.F));
+            }
+
+            {
+                c.v = new Object[1][1][1][1]; Object[] val1 = get1();
+                c.v[0][0][0] = new Object[1]; Object[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new Object[1][1][1][1]; Object[][] val1 = get2();
+                c.v[0][0] = new Object[1][1]; Object[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new Object[1][1][1][1]; Object[][][] val1 = get3();
+                c.v[0] = new Object[1][1][1]; Object[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new Object[1][1][1][1]; Object[][][][] val1 = get4();
+                c.v = new Object[1][1][1][1]; Object[][][][] val2 = get4();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+        }
+    }
+
+    /* ==================================================== */
+    // Dynamic Dim is higher than static
+
+    static class ObjectArrayLowerDim0 {
+        public @Stable Object v;
+
+        public static final ObjectArrayLowerDim0 c = new ObjectArrayLowerDim0();
+        public static Object get() { return ((Object[])c.v)[0]; }
+        public static Object[] get1() { return (Object[])c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new Object[1]; ((Object[])c.v)[0] = Values.A; Object val1 = get();
+                                     ((Object[])c.v)[0] = Values.B; Object val2 = get();
+
+                assertEquals(val1, Values.A);
+                assertEquals(val2, Values.B);
+            }
+
+            {
+                c.v = new Object[1]; Object[] val1 = get1();
+                c.v = new Object[1]; Object[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim1 {
+        public @Stable Object[] v;
+
+        public static final ObjectArrayLowerDim1 c = new ObjectArrayLowerDim1();
+        public static Object get() { return ((Object[][])c.v)[0][0]; }
+        public static Object[] get1() { return (Object[])(c.v[0]); }
+        public static Object[] get2() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new Object[1][1]; ((Object[][])c.v)[0][0] = Values.A; Object val1 = get();
+                                        ((Object[][])c.v)[0][0] = Values.B; Object val2 = get();
+
+                assertEquals(val1, Values.A);
+                assertEquals(val2, Values.B);
+            }
+
+            {
+                c.v = new Object[1][1]; c.v[0] = new Object[0]; Object[] val1 = get1();
+                                     c.v[0] = new Object[0]; Object[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new Object[0][0]; Object[] val1 = get2();
+                c.v = new Object[0][0]; Object[] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim2 {
+        public @Stable Object[][] v;
+
+        public static final ObjectArrayLowerDim2 c = new ObjectArrayLowerDim2();
+        public static Object get() { return ((Object[][][])c.v)[0][0][0]; }
+        public static Object[] get1() { return (Object[])(c.v[0][0]); }
+        public static Object[][] get2() { return (Object[][])(c.v[0]); }
+        public static Object[][] get3() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new Object[1][1][1]; ((Object[][][])c.v)[0][0][0] = Values.A; Object val1 = get();
+                                           ((Object[][][])c.v)[0][0][0] = Values.B; Object val2 = get();
+
+                assertEquals(val1, Values.A);
+                assertEquals(val2, Values.B);
+            }
+
+            {
+                c.v = new Object[1][1][1]; c.v[0][0] = new Object[0]; Object[] val1 = get1();
+                                           c.v[0][0] = new Object[0]; Object[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new Object[1][1][1]; c.v[0] = new Object[0][0]; Object[][] val1 = get2();
+                                           c.v[0] = new Object[0][0]; Object[][] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new Object[0][0][0]; Object[][] val1 = get3();
+                c.v = new Object[0][0][0]; Object[][] val2 = get3();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField {
+        static class A {
+            public @Stable Object a;
+
+        }
+        public @Stable A v;
+
+        public static final NestedStableField c = new NestedStableField();
+        public static A get() { return c.v; }
+        public static Object get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.a = Values.A; A val1 = get();
+                               c.v.a = Values.B; A val2 = get();
+
+                assertEquals(val1.a, Values.B);
+                assertEquals(val2.a, Values.B);
+            }
+
+            {
+                c.v = new A(); c.v.a = Values.A; Object val1 = get1();
+                               c.v.a = Values.B; Object val2 = get1();
+                c.v = new A(); c.v.a = Values.C; Object val3 = get1();
+
+                assertEquals(val1, Values.A);
+                assertEquals(val2, (isStableEnabled ? Values.A : Values.B));
+                assertEquals(val3, (isStableEnabled ? Values.A : Values.C));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField1 {
+        static class A {
+            public @Stable Object a;
+            public @Stable A next;
+        }
+        public @Stable A v;
+
+        public static final NestedStableField1 c = new NestedStableField1();
+        public static A get() { return c.v.next.next.next.next.next.next.next; }
+        public static Object get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.next = new A();   c.v.next.next  = c.v;
+                               c.v.a = Values.A; c.v.next.a = Values.A; A val1 = get();
+                               c.v.a = Values.B; c.v.next.a = Values.B; A val2 = get();
+
+                assertEquals(val1.a, Values.B);
+                assertEquals(val2.a, Values.B);
+            }
+
+            {
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = Values.A; Object val1 = get1();
+                               c.v.a = Values.B; Object val2 = get1();
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = Values.C; Object val3 = get1();
+
+                assertEquals(val1, Values.A);
+                assertEquals(val2, (isStableEnabled ? Values.A : Values.B));
+                assertEquals(val3, (isStableEnabled ? Values.A : Values.C));
+            }
+        }
+    }
+   /* ==================================================== */
+
+    static class NestedStableField2 {
+        static class A {
+            public @Stable Object a;
+            public @Stable A left;
+            public         A right;
+        }
+
+        public @Stable A v;
+
+        public static final NestedStableField2 c = new NestedStableField2();
+        public static Object get() { return c.v.left.left.left.a; }
+        public static Object get1() { return c.v.left.left.right.left.a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.left = c.v.right = c.v;
+                               c.v.a = Values.A; Object val1 = get(); Object val2 = get1();
+                               c.v.a = Values.B; Object val3 = get(); Object val4 = get1();
+
+                assertEquals(val1, Values.A);
+                assertEquals(val3, (isStableEnabled ? Values.A : Values.B));
+
+                assertEquals(val2, Values.A);
+                assertEquals(val4, Values.B);
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField3 {
+        static class A {
+            public @Stable Object a;
+            public @Stable A[] left;
+            public         A[] right;
+        }
+
+        public @Stable A[] v;
+
+        public static final NestedStableField3 c = new NestedStableField3();
+        public static Object get() { return c.v[0].left[1].left[0].left[1].a; }
+        public static Object get1() { return c.v[1].left[0].left[1].right[0].left[1].a; }
+
+        public static void test() throws Exception {
+            {
+                A elem = new A();
+                c.v = new A[] { elem, elem }; c.v[0].left = c.v[0].right = c.v;
+                               elem.a = Values.A; Object val1 = get(); Object val2 = get1();
+                               elem.a = Values.B; Object val3 = get(); Object val4 = get1();
+
+                assertEquals(val1, Values.A);
+                assertEquals(val3, (isStableEnabled ? Values.A : Values.B));
+
+                assertEquals(val2, Values.A);
+                assertEquals(val4, Values.B);
+            }
+        }
+    }
+
+    /* ==================================================== */
+    // Auxiliary methods
+    static void assertEquals(Object i, Object j) { if (i != j)  throw new AssertionError(i + " != " + j); }
+    static void assertTrue(boolean b) { if (!b)  throw new AssertionError(); }
+
+    static boolean failed = false;
+
+    public static void run(Class<?> test) {
+        Throwable ex = null;
+        System.out.print(test.getName()+": ");
+        try {
+            test.getMethod("test").invoke(null);
+        } catch (InvocationTargetException e) {
+            ex = e.getCause();
+        } catch (Throwable e) {
+            ex = e;
+        } finally {
+            if (ex == null) {
+                System.out.println("PASSED");
+            } else {
+                failed = true;
+                System.out.println("FAILED");
+                ex.printStackTrace(System.out);
+            }
+        }
+    }
+
+    static final boolean isStableEnabled;
+    static {
+        HotSpotDiagnosticMXBean diagnostic
+                = ManagementFactoryHelper.getDiagnosticMXBean();
+        VMOption tmp;
+        try {
+            tmp = diagnostic.getVMOption("FoldStableValues");
+        } catch (IllegalArgumentException e) {
+            tmp = null;
+        }
+        isStableEnabled = (tmp == null ? false : Boolean.parseBoolean(tmp.getValue()));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/stable/TestStableShort.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,632 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 TestStableShort
+ * @summary tests on stable fields and arrays
+ * @library /testlibrary
+ * @compile -XDignore.symbol.file TestStableShort.java
+ * @run main ClassFileInstaller
+ *           java/lang/invoke/TestStableShort
+ *           java/lang/invoke/TestStableShort$ShortStable
+ *           java/lang/invoke/TestStableShort$StaticShortStable
+ *           java/lang/invoke/TestStableShort$VolatileShortStable
+ *           java/lang/invoke/TestStableShort$ShortArrayDim1
+ *           java/lang/invoke/TestStableShort$ShortArrayDim2
+ *           java/lang/invoke/TestStableShort$ShortArrayDim3
+ *           java/lang/invoke/TestStableShort$ShortArrayDim4
+ *           java/lang/invoke/TestStableShort$ObjectArrayLowerDim0
+ *           java/lang/invoke/TestStableShort$ObjectArrayLowerDim1
+ *           java/lang/invoke/TestStableShort$NestedStableField
+ *           java/lang/invoke/TestStableShort$NestedStableField$A
+ *           java/lang/invoke/TestStableShort$NestedStableField1
+ *           java/lang/invoke/TestStableShort$NestedStableField1$A
+ *           java/lang/invoke/TestStableShort$NestedStableField2
+ *           java/lang/invoke/TestStableShort$NestedStableField2$A
+ *           java/lang/invoke/TestStableShort$NestedStableField3
+ *           java/lang/invoke/TestStableShort$NestedStableField3$A
+ *           java/lang/invoke/TestStableShort$DefaultValue
+ *           java/lang/invoke/TestStableShort$ObjectArrayLowerDim2
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableShort
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:+FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableShort
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:+UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableShort
+ *
+ * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:-FoldStableValues -XX:-UseCompressedOop
+ *                   -server -XX:-TieredCompilation -Xcomp
+ *                   -XX:CompileOnly=::get,::get1,::get2,::get3,::get4
+ *                   java.lang.invoke.TestStableShort
+ */
+package java.lang.invoke;
+
+import com.sun.management.HotSpotDiagnosticMXBean;
+import com.sun.management.VMOption;
+import sun.management.ManagementFactoryHelper;
+import java.lang.reflect.InvocationTargetException;
+
+public class TestStableShort {
+    public static void main(String[] args) throws Exception {
+        System.out.println("@Stable enabled: "+isStableEnabled);
+        System.out.println();
+
+        run(DefaultValue.class);
+        run(ShortStable.class);
+        run(StaticShortStable.class);
+        run(VolatileShortStable.class);
+
+        // @Stable arrays: Dim 1-4
+        run(ShortArrayDim1.class);
+        run(ShortArrayDim2.class);
+        run(ShortArrayDim3.class);
+        run(ShortArrayDim4.class);
+
+        // @Stable Object field: dynamic arrays
+        run(ObjectArrayLowerDim0.class);
+        run(ObjectArrayLowerDim1.class);
+        run(ObjectArrayLowerDim2.class);
+
+        // Nested @Stable fields
+        run(NestedStableField.class);
+        run(NestedStableField1.class);
+        run(NestedStableField2.class);
+        run(NestedStableField3.class);
+
+        if (failed) {
+            throw new Error("TEST FAILED");
+        }
+    }
+
+    /* ==================================================== */
+
+    static class DefaultValue {
+        public @Stable short v;
+
+        public static final DefaultValue c = new DefaultValue();
+        public static short get() { return c.v; }
+        public static void test() throws Exception {
+                     short val1 = get();
+            c.v = 1; short val2 = get();
+            assertEquals(val1, 0);
+            assertEquals(val2, 1);
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ShortStable {
+        public @Stable short v;
+
+        public static final ShortStable c = new ShortStable();
+        public static short get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 1;     short val1 = get();
+            c.v = 32767; short val2 = get();
+            assertEquals(val1, 1);
+            assertEquals(val2, (isStableEnabled ? 1 : 32767));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class StaticShortStable {
+        public static @Stable short v;
+
+        public static final StaticShortStable c = new StaticShortStable();
+        public static short get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 1;     short val1 = get();
+            c.v = 32767; short val2 = get();
+            assertEquals(val1, 1);
+            assertEquals(val2, (isStableEnabled ? 1 : 32767));
+        }
+    }
+
+    /* ==================================================== */
+
+    static class VolatileShortStable {
+        public @Stable volatile short v;
+
+        public static final VolatileShortStable c = new VolatileShortStable();
+        public static short get() { return c.v; }
+        public static void test() throws Exception {
+            c.v = 1;     short val1 = get();
+            c.v = 32767; short val2 = get();
+            assertEquals(val1, 1);
+            assertEquals(val2, (isStableEnabled ? 1 : 32767));
+        }
+    }
+
+    /* ==================================================== */
+    // @Stable array == field && all components are stable
+
+    static class ShortArrayDim1 {
+        public @Stable short[] v;
+
+        public static final ShortArrayDim1 c = new ShortArrayDim1();
+        public static short get() { return c.v[0]; }
+        public static short get1() { return c.v[10]; }
+        public static short[] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new short[1]; c.v[0] = 1; short val1 = get();
+                                    c.v[0] = 2; short val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new short[1]; c.v[0] = 3; short val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+
+            {
+                c.v = new short[20]; c.v[10] = 1; short val1 = get1();
+                                     c.v[10] = 2; short val2 = get1();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new short[20]; c.v[10] = 3; short val3 = get1();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+
+            {
+                c.v = new short[1]; short[] val1 = get2();
+                c.v = new short[1]; short[] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ShortArrayDim2 {
+        public @Stable short[][] v;
+
+        public static final ShortArrayDim2 c = new ShortArrayDim2();
+        public static short get() { return c.v[0][0]; }
+        public static short[] get1() { return c.v[0]; }
+        public static short[][] get2() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new short[1][1]; c.v[0][0] = 1; short val1 = get();
+                                       c.v[0][0] = 2; short val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new short[1][1]; c.v[0][0] = 3; short val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+
+                c.v[0] = new short[1]; c.v[0][0] = 4; short val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1 : 4));
+            }
+
+            {
+                c.v = new short[1][1]; short[] val1 = get1();
+                c.v[0] = new short[1]; short[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new short[1][1]; short[][] val1 = get2();
+                c.v = new short[1][1]; short[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ShortArrayDim3 {
+        public @Stable short[][][] v;
+
+        public static final ShortArrayDim3 c = new ShortArrayDim3();
+        public static short get() { return c.v[0][0][0]; }
+        public static short[] get1() { return c.v[0][0]; }
+        public static short[][] get2() { return c.v[0]; }
+        public static short[][][] get3() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new short[1][1][1]; c.v[0][0][0] = 1; short val1 = get();
+                                          c.v[0][0][0] = 2; short val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new short[1][1][1]; c.v[0][0][0] = 3; short val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+
+                c.v[0] = new short[1][1]; c.v[0][0][0] = 4; short val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1 : 4));
+
+                c.v[0][0] = new short[1]; c.v[0][0][0] = 5; short val5 = get();
+                assertEquals(val5, (isStableEnabled ? 1 : 5));
+            }
+
+            {
+                c.v = new short[1][1][1]; short[] val1 = get1();
+                c.v[0][0] = new short[1]; short[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new short[1][1][1]; short[][] val1 = get2();
+                c.v[0] = new short[1][1]; short[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new short[1][1][1]; short[][][] val1 = get3();
+                c.v = new short[1][1][1]; short[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ShortArrayDim4 {
+        public @Stable short[][][][] v;
+
+        public static final ShortArrayDim4 c = new ShortArrayDim4();
+        public static short get() { return c.v[0][0][0][0]; }
+        public static short[] get1() { return c.v[0][0][0]; }
+        public static short[][] get2() { return c.v[0][0]; }
+        public static short[][][] get3() { return c.v[0]; }
+        public static short[][][][] get4() { return c.v; }
+        public static void test() throws Exception {
+            {
+                c.v = new short[1][1][1][1]; c.v[0][0][0][0] = 1; short val1 = get();
+                                             c.v[0][0][0][0] = 2; short val2 = get();
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+
+                c.v = new short[1][1][1][1]; c.v[0][0][0][0] = 3; short val3 = get();
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+
+                c.v[0] = new short[1][1][1]; c.v[0][0][0][0] = 4; short val4 = get();
+                assertEquals(val4, (isStableEnabled ? 1 : 4));
+
+                c.v[0][0] = new short[1][1]; c.v[0][0][0][0] = 5; short val5 = get();
+                assertEquals(val5, (isStableEnabled ? 1 : 5));
+
+                c.v[0][0][0] = new short[1]; c.v[0][0][0][0] = 6; short val6 = get();
+                assertEquals(val6, (isStableEnabled ? 1 : 6));
+            }
+
+            {
+                c.v = new short[1][1][1][1]; short[] val1 = get1();
+                c.v[0][0][0] = new short[1]; short[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new short[1][1][1][1]; short[][] val1 = get2();
+                c.v[0][0] = new short[1][1]; short[][] val2 = get2();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new short[1][1][1][1]; short[][][] val1 = get3();
+                c.v[0] = new short[1][1][1]; short[][][] val2 = get3();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new short[1][1][1][1]; short[][][][] val1 = get4();
+                c.v = new short[1][1][1][1]; short[][][][] val2 = get4();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+        }
+    }
+
+    /* ==================================================== */
+    // Dynamic Dim is higher than static
+
+    static class ObjectArrayLowerDim0 {
+        public @Stable Object v;
+
+        public static final ObjectArrayLowerDim0 c = new ObjectArrayLowerDim0();
+        public static short get() { return ((short[])c.v)[0]; }
+        public static short[] get1() { return (short[])c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new short[1]; ((short[])c.v)[0] = 1; short val1 = get();
+                                    ((short[])c.v)[0] = 2; short val2 = get();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, 2);
+            }
+
+            {
+                c.v = new short[1]; short[] val1 = get1();
+                c.v = new short[1]; short[] val2 = get1();
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim1 {
+        public @Stable Object[] v;
+
+        public static final ObjectArrayLowerDim1 c = new ObjectArrayLowerDim1();
+        public static short get() { return ((short[][])c.v)[0][0]; }
+        public static short[] get1() { return (short[])(c.v[0]); }
+        public static Object[] get2() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new short[1][1]; ((short[][])c.v)[0][0] = 1; short val1 = get();
+                                       ((short[][])c.v)[0][0] = 2; short val2 = get();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, 2);
+            }
+
+            {
+                c.v = new short[1][1]; c.v[0] = new short[0]; short[] val1 = get1();
+                                       c.v[0] = new short[0]; short[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new short[0][0]; Object[] val1 = get2();
+                c.v = new short[0][0]; Object[] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class ObjectArrayLowerDim2 {
+        public @Stable Object[][] v;
+
+        public static final ObjectArrayLowerDim2 c = new ObjectArrayLowerDim2();
+        public static short get() { return ((short[][][])c.v)[0][0][0]; }
+        public static short[] get1() { return (short[])(c.v[0][0]); }
+        public static short[][] get2() { return (short[][])(c.v[0]); }
+        public static Object[][] get3() { return c.v; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new short[1][1][1]; ((short[][][])c.v)[0][0][0] = 1; short val1 = get();
+                                          ((short[][][])c.v)[0][0][0] = 2; short val2 = get();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, 2);
+            }
+
+            {
+                c.v = new short[1][1][1]; c.v[0][0] = new short[0]; short[] val1 = get1();
+                                          c.v[0][0] = new short[0]; short[] val2 = get1();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new short[1][1][1]; c.v[0] = new short[0][0]; short[][] val1 = get2();
+                                          c.v[0] = new short[0][0]; short[][] val2 = get2();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+
+            {
+                c.v = new short[0][0][0]; Object[][] val1 = get3();
+                c.v = new short[0][0][0]; Object[][] val2 = get3();
+
+                assertTrue((isStableEnabled ? (val1 == val2) : (val1 != val2)));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField {
+        static class A {
+            public @Stable short a;
+
+        }
+        public @Stable A v;
+
+        public static final NestedStableField c = new NestedStableField();
+        public static A get() { return c.v; }
+        public static short get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.a = 1; A val1 = get();
+                               c.v.a = 2; A val2 = get();
+
+                assertEquals(val1.a, 2);
+                assertEquals(val2.a, 2);
+            }
+
+            {
+                c.v = new A(); c.v.a = 1; short val1 = get1();
+                               c.v.a = 2; short val2 = get1();
+                c.v = new A(); c.v.a = 3; short val3 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField1 {
+        static class A {
+            public @Stable short a;
+            public @Stable A next;
+        }
+        public @Stable A v;
+
+        public static final NestedStableField1 c = new NestedStableField1();
+        public static A get() { return c.v.next.next.next.next.next.next.next; }
+        public static short get1() { return get().a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.next = new A();   c.v.next.next  = c.v;
+                               c.v.a = 1; c.v.next.a = 1; A val1 = get();
+                               c.v.a = 2; c.v.next.a = 2; A val2 = get();
+
+                assertEquals(val1.a, 2);
+                assertEquals(val2.a, 2);
+            }
+
+            {
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 1; short val1 = get1();
+                               c.v.a = 2; short val2 = get1();
+                c.v = new A(); c.v.next = c.v;
+                               c.v.a = 3; short val3 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val2, (isStableEnabled ? 1 : 2));
+                assertEquals(val3, (isStableEnabled ? 1 : 3));
+            }
+        }
+    }
+   /* ==================================================== */
+
+    static class NestedStableField2 {
+        static class A {
+            public @Stable short a;
+            public @Stable A left;
+            public         A right;
+        }
+
+        public @Stable A v;
+
+        public static final NestedStableField2 c = new NestedStableField2();
+        public static short get() { return c.v.left.left.left.a; }
+        public static short get1() { return c.v.left.left.right.left.a; }
+
+        public static void test() throws Exception {
+            {
+                c.v = new A(); c.v.left = c.v.right = c.v;
+                               c.v.a = 1; short val1 = get(); short val2 = get1();
+                               c.v.a = 2; short val3 = get(); short val4 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val3, (isStableEnabled ? 1 : 2));
+
+                assertEquals(val2, 1);
+                assertEquals(val4, 2);
+            }
+        }
+    }
+
+    /* ==================================================== */
+
+    static class NestedStableField3 {
+        static class A {
+            public @Stable short a;
+            public @Stable A[] left;
+            public         A[] right;
+        }
+
+        public @Stable A[] v;
+
+        public static final NestedStableField3 c = new NestedStableField3();
+        public static short get() { return c.v[0].left[1].left[0].left[1].a; }
+        public static short get1() { return c.v[1].left[0].left[1].right[0].left[1].a; }
+
+        public static void test() throws Exception {
+            {
+                A elem = new A();
+                c.v = new A[] { elem, elem }; c.v[0].left = c.v[0].right = c.v;
+                               elem.a = 1; short val1 = get(); short val2 = get1();
+                               elem.a = 2; short val3 = get(); short val4 = get1();
+
+                assertEquals(val1, 1);
+                assertEquals(val3, (isStableEnabled ? 1 : 2));
+
+                assertEquals(val2, 1);
+                assertEquals(val4, 2);
+            }
+        }
+    }
+
+    /* ==================================================== */
+    // Auxiliary methods
+    static void assertEquals(int i, int j) { if (i != j)  throw new AssertionError(i + " != " + j); }
+    static void assertTrue(boolean b) { if (!b)  throw new AssertionError(); }
+
+    static boolean failed = false;
+
+    public static void run(Class<?> test) {
+        Throwable ex = null;
+        System.out.print(test.getName()+": ");
+        try {
+            test.getMethod("test").invoke(null);
+        } catch (InvocationTargetException e) {
+            ex = e.getCause();
+        } catch (Throwable e) {
+            ex = e;
+        } finally {
+            if (ex == null) {
+                System.out.println("PASSED");
+            } else {
+                failed = true;
+                System.out.println("FAILED");
+                ex.printStackTrace(System.out);
+            }
+        }
+    }
+
+    static final boolean isStableEnabled;
+    static {
+        HotSpotDiagnosticMXBean diagnostic
+                = ManagementFactoryHelper.getDiagnosticMXBean();
+        VMOption tmp;
+        try {
+            tmp = diagnostic.getVMOption("FoldStableValues");
+        } catch (IllegalArgumentException e) {
+            tmp = null;
+        }
+        isStableEnabled = (tmp == null ? false : Boolean.parseBoolean(tmp.getValue()));
+    }
+}
--- a/hotspot/test/compiler/tiered/NonTieredLevelsTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/tiered/NonTieredLevelsTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -70,6 +70,9 @@
 
     @Override
     protected void test() throws Exception {
+        if (skipXcompOSR()) {
+          return;
+        }
         checkNotCompiled();
         compile();
         checkCompiled();
--- a/hotspot/test/compiler/tiered/TieredLevelsTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/tiered/TieredLevelsTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,6 +51,9 @@
 
     @Override
     protected void test() throws Exception {
+        if (skipXcompOSR()) {
+          return;
+        }
         checkNotCompiled();
         compile();
         checkCompiled();
--- a/hotspot/test/compiler/types/TestMeetTopArrayExactConstantArray.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/types/TestMeetTopArrayExactConstantArray.java	Wed Jul 05 19:33:51 2017 +0200
@@ -25,7 +25,7 @@
  * @test
  * @bug 8027571
  * @summary meet of TopPTR exact array with constant array is not symmetric
- * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseOnStackReplacement -XX:TypeProfileLevel=222 -XX:+UnlockExperimentalVMOptions -XX:+UseTypeSpeculation -XX:-BackgroundCompilation TestMeetTopArrayExactConstantArray
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseOnStackReplacement -XX:TypeProfileLevel=222 -XX:+UseTypeSpeculation -XX:-BackgroundCompilation TestMeetTopArrayExactConstantArray
  *
  */
 
--- a/hotspot/test/compiler/types/TestSpeculationFailedHigherEqual.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/types/TestSpeculationFailedHigherEqual.java	Wed Jul 05 19:33:51 2017 +0200
@@ -25,7 +25,7 @@
  * @test
  * @bug 8027422
  * @summary type methods shouldn't always operate on speculative part
- * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:TypeProfileLevel=222 -XX:+UnlockExperimentalVMOptions -XX:+UseTypeSpeculation -XX:-BackgroundCompilation TestSpeculationFailedHigherEqual
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:TypeProfileLevel=222 -XX:+UseTypeSpeculation -XX:-BackgroundCompilation TestSpeculationFailedHigherEqual
  *
  */
 
--- a/hotspot/test/compiler/types/TypeSpeculation.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/types/TypeSpeculation.java	Wed Jul 05 19:33:51 2017 +0200
@@ -25,7 +25,7 @@
  * @test
  * @bug 8024070
  * @summary Test that type speculation doesn't cause incorrect execution
- * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseOnStackReplacement -XX:-BackgroundCompilation -XX:TypeProfileLevel=222 -XX:+UnlockExperimentalVMOptions -XX:+UseTypeSpeculation TypeSpeculation
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseOnStackReplacement -XX:-BackgroundCompilation -XX:TypeProfileLevel=222 -XX:+UseTypeSpeculation TypeSpeculation
  *
  */
 
--- a/hotspot/test/compiler/uncommontrap/TestSpecTrapClassUnloading.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/uncommontrap/TestSpecTrapClassUnloading.java	Wed Jul 05 19:33:51 2017 +0200
@@ -25,7 +25,7 @@
  * @test
  * @bug 8031752
  * @summary speculative traps need to be cleaned up at GC
- * @run main/othervm -XX:-TieredCompilation -XX:-UseOnStackReplacement -XX:-BackgroundCompilation -XX:+UnlockExperimentalVMOptions -XX:+UseTypeSpeculation -XX:TypeProfileLevel=222 -XX:CompileCommand=exclude,java.lang.reflect.Method::invoke -XX:CompileCommand=exclude,sun.reflect.DelegatingMethodAccessorImpl::invoke -Xmx1M TestSpecTrapClassUnloading
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:-UseOnStackReplacement -XX:-BackgroundCompilation -XX:+UseTypeSpeculation -XX:TypeProfileLevel=222 -XX:CompileCommand=exclude,java.lang.reflect.Method::invoke -XX:CompileCommand=exclude,sun.reflect.DelegatingMethodAccessorImpl::invoke -Xmx1M TestSpecTrapClassUnloading
  *
  */
 
--- a/hotspot/test/compiler/whitebox/CompilerWhiteBoxTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/whitebox/CompilerWhiteBoxTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -196,6 +196,29 @@
     }
 
     /**
+     * Checks, that {@linkplain #method} is not compiled at the given compilation
+     * level or above.
+     *
+     * @param compLevel
+     *
+     * @throws RuntimeException if {@linkplain #method} is in compiler queue or
+     *                          is compiled, or if {@linkplain #method} has zero
+     *                          compilation level.
+     */
+
+    protected final void checkNotCompiled(int compLevel) {
+        if (WHITE_BOX.isMethodQueuedForCompilation(method)) {
+            throw new RuntimeException(method + " must not be in queue");
+        }
+        if (WHITE_BOX.getMethodCompilationLevel(method, false) >= compLevel) {
+            throw new RuntimeException(method + " comp_level must be >= maxCompLevel");
+        }
+        if (WHITE_BOX.getMethodCompilationLevel(method, true) >= compLevel) {
+            throw new RuntimeException(method + " osr_comp_level must be >= maxCompLevel");
+        }
+    }
+
+    /**
      * Checks, that {@linkplain #method} is not compiled.
      *
      * @throws RuntimeException if {@linkplain #method} is in compiler queue or
@@ -380,6 +403,20 @@
         /** flag for OSR test case */
         boolean isOsr();
     }
+
+    /**
+     * @return {@code true} if the current test case is OSR and the mode is
+     *          Xcomp, otherwise {@code false}
+     */
+    protected boolean skipXcompOSR() {
+        boolean result =  testCase.isOsr()
+                && CompilerWhiteBoxTest.MODE.startsWith("compiled ");
+        if (result && IS_VERBOSE) {
+            System.err.printf("Warning: %s is not applicable in %s%n",
+                    testCase.name(), CompilerWhiteBoxTest.MODE);
+        }
+        return result;
+    }
 }
 
 enum SimpleTestCase implements CompilerWhiteBoxTest.TestCase {
--- a/hotspot/test/compiler/whitebox/DeoptimizeAllTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/whitebox/DeoptimizeAllTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,11 +51,8 @@
      */
     @Override
     protected void test() throws Exception {
-        if (testCase.isOsr() && CompilerWhiteBoxTest.MODE.startsWith(
-                "compiled ")) {
-          System.err.printf("Warning: %s is not applicable in %s%n",
-                testCase.name(), CompilerWhiteBoxTest.MODE);
-          return;
+        if (skipXcompOSR()) {
+            return;
         }
         compile();
         checkCompiled();
--- a/hotspot/test/compiler/whitebox/DeoptimizeMethodTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/whitebox/DeoptimizeMethodTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,11 +51,8 @@
      */
     @Override
     protected void test() throws Exception {
-        if (testCase.isOsr() && CompilerWhiteBoxTest.MODE.startsWith(
-                "compiled ")) {
-          System.err.printf("Warning: %s is not applicable in %s%n",
-                testCase.name(), CompilerWhiteBoxTest.MODE);
-          return;
+        if (skipXcompOSR()) {
+            return;
         }
         compile();
         checkCompiled();
--- a/hotspot/test/compiler/whitebox/IsMethodCompilableTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/whitebox/IsMethodCompilableTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,13 +24,17 @@
 /*
  * @test IsMethodCompilableTest
  * @bug 8007270 8006683 8007288 8022832
- * @library /testlibrary /testlibrary/whitebox
+ * @library /testlibrary /testlibrary/whitebox /testlibrary/com/oracle/java/testlibrary
  * @build IsMethodCompilableTest
  * @run main ClassFileInstaller sun.hotspot.WhiteBox
- * @run main/othervm/timeout=2400 -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:CompileCommand=compileonly,SimpleTestCase$Helper::* IsMethodCompilableTest
+ * @run main ClassFileInstaller com.oracle.java.testlibrary.Platform
+ * @run main/othervm/timeout=2400 -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:PerMethodRecompilationCutoff=3 -XX:CompileCommand=compileonly,SimpleTestCase$Helper::* IsMethodCompilableTest
  * @summary testing of WB::isMethodCompilable()
  * @author igor.ignatyev@oracle.com
  */
+
+import com.oracle.java.testlibrary.Platform;
+
 public class IsMethodCompilableTest extends CompilerWhiteBoxTest {
     /**
      * Value of {@code -XX:PerMethodRecompilationCutoff}
@@ -43,7 +47,7 @@
         if (tmp == -1) {
             PER_METHOD_RECOMPILATION_CUTOFF = -1 /* Inf */;
         } else {
-            PER_METHOD_RECOMPILATION_CUTOFF = 1 + (0xFFFFFFFFL & tmp);
+            PER_METHOD_RECOMPILATION_CUTOFF = (0xFFFFFFFFL & tmp);
         }
     }
 
@@ -60,19 +64,23 @@
     /**
      * Tests {@code WB::isMethodCompilable()} by recompilation of tested method
      * 'PerMethodRecompilationCutoff' times and checks compilation status. Also
-     * checks that WB::clearMethodState() clears no-compilable flags.
+     * checks that WB::clearMethodState() clears no-compilable flags. Only
+     * applicable to c2 compiled methods.
      *
      * @throws Exception if one of the checks fails.
      */
     @Override
     protected void test() throws Exception {
-        if (testCase.isOsr() && CompilerWhiteBoxTest.MODE.startsWith(
-                "compiled ")) {
-          System.err.printf("Warning: %s is not applicable in %s%n",
-                testCase.name(), CompilerWhiteBoxTest.MODE);
-          return;
+
+        // Only c2 compilations can be disabled through PerMethodRecompilationCutoff
+        if (!Platform.isServer()) {
+            return;
         }
-        if (!isCompilable()) {
+
+        if (skipXcompOSR()) {
+            return;
+        }
+        if (!isCompilable(COMP_LEVEL_FULL_OPTIMIZATION)) {
             throw new RuntimeException(method + " must be compilable");
         }
         System.out.println("PerMethodRecompilationCutoff = "
@@ -83,39 +91,37 @@
             return;
         }
 
-        // deoptimize 'PerMethodRecompilationCutoff' times and clear state
-        for (long i = 0L, n = PER_METHOD_RECOMPILATION_CUTOFF - 1; i < n; ++i) {
-            compileAndDeoptimize();
+        // deoptimize 'PerMethodRecompilationCutoff' times
+        for (long attempts = 0, successes = 0;
+               (successes < PER_METHOD_RECOMPILATION_CUTOFF)  &&
+               (attempts < PER_METHOD_RECOMPILATION_CUTOFF*2) &&
+               isCompilable(COMP_LEVEL_FULL_OPTIMIZATION); attempts++) {
+            if (compileAndDeoptimize() == COMP_LEVEL_FULL_OPTIMIZATION) {
+                successes++;
+            }
         }
-        if (!testCase.isOsr() && !isCompilable()) {
+
+        if (!testCase.isOsr() && !isCompilable(COMP_LEVEL_FULL_OPTIMIZATION)) {
             // in osr test case count of deopt maybe more than iterations
             throw new RuntimeException(method + " is not compilable after "
-                    + (PER_METHOD_RECOMPILATION_CUTOFF - 1) + " iterations");
+                    + PER_METHOD_RECOMPILATION_CUTOFF + " iterations");
         }
-        WHITE_BOX.clearMethodState(method);
 
-        // deoptimize 'PerMethodRecompilationCutoff' + 1 times
-        long i;
-        for (i = 0L; i < PER_METHOD_RECOMPILATION_CUTOFF
-                && isCompilable(); ++i) {
-            compileAndDeoptimize();
-        }
-        if (!testCase.isOsr() && i != PER_METHOD_RECOMPILATION_CUTOFF) {
-            // in osr test case count of deopt maybe more than iterations
-            throw new RuntimeException(method + " is not compilable after "
-                    + i + " iterations, but must only after "
-                    + PER_METHOD_RECOMPILATION_CUTOFF);
-        }
-        if (isCompilable()) {
+        // Now compile once more
+        compileAndDeoptimize();
+
+        if (isCompilable(COMP_LEVEL_FULL_OPTIMIZATION)) {
             throw new RuntimeException(method + " is still compilable after "
                     + PER_METHOD_RECOMPILATION_CUTOFF + " iterations");
         }
+        checkNotCompiled();
         compile();
-        checkNotCompiled();
+        waitBackgroundCompilation();
+        checkNotCompiled(COMP_LEVEL_FULL_OPTIMIZATION);
 
         // WB.clearMethodState() must reset no-compilable flags
         WHITE_BOX.clearMethodState(method);
-        if (!isCompilable()) {
+        if (!isCompilable(COMP_LEVEL_FULL_OPTIMIZATION)) {
             throw new RuntimeException(method
                     + " is not compilable after clearMethodState()");
         }
@@ -123,9 +129,11 @@
         checkCompiled();
     }
 
-    private void compileAndDeoptimize() throws Exception {
+    private int compileAndDeoptimize() throws Exception {
         compile();
         waitBackgroundCompilation();
+        int compLevel = getCompLevel();
         deoptimize();
+        return compLevel;
     }
 }
--- a/hotspot/test/compiler/whitebox/MakeMethodNotCompilableTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/compiler/whitebox/MakeMethodNotCompilableTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -53,11 +53,8 @@
      */
     @Override
     protected void test() throws Exception {
-        if (testCase.isOsr() && CompilerWhiteBoxTest.MODE.startsWith(
-                "compiled ")) {
-          System.err.printf("Warning: %s is not applicable in %s%n",
-                testCase.name(), CompilerWhiteBoxTest.MODE);
-          return;
+        if (skipXcompOSR()) {
+            return;
         }
         checkNotCompiled();
         if (!isCompilable()) {
--- a/hotspot/test/runtime/6294277/SourceDebugExtension.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/runtime/6294277/SourceDebugExtension.java	Wed Jul 05 19:33:51 2017 +0200
@@ -25,7 +25,7 @@
  * @test
  * @bug 6294277
  * @summary java -Xdebug crashes on SourceDebugExtension attribute larger than 64K
- * @run main/othervm -Xdebug -Xrunjdwp:transport=dt_socket,address=8888,server=y,suspend=n SourceDebugExtension
+ * @run main/othervm -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n SourceDebugExtension
  */
 import java.io.*;
 
--- a/hotspot/test/runtime/CompressedOops/CompressedClassPointers.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/runtime/CompressedOops/CompressedClassPointers.java	Wed Jul 05 19:33:51 2017 +0200
@@ -83,8 +83,8 @@
     public static void heapBaseMinAddressTest() throws Exception {
         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
             "-XX:HeapBaseMinAddress=1m",
-            "-XX:+PrintMiscellaneous",
-            "-XX:+Verbose",
+            "-XX:+UnlockDiagnosticVMOptions",
+            "-XX:+PrintCompressedOopsMode",
             "-version");
         OutputAnalyzer output = new OutputAnalyzer(pb.start());
         output.shouldContain("HeapBaseMinAddress must be at least");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/serviceability/jvmti/TestRedefineWithUnresolvedClass.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 Redefine a class with an UnresolvedClass reference in the constant pool.
+ * @bug 8035150
+ * @library /testlibrary
+ * @build UnresolvedClassAgent com.oracle.java.testlibrary.ProcessTools com.oracle.java.testlibrary.OutputAnalyzer
+ * @run main TestRedefineWithUnresolvedClass
+ */
+
+import java.io.File;
+import java.util.Arrays;
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+public class TestRedefineWithUnresolvedClass {
+
+    final static String slash = File.separator;
+    final static String testClasses = System.getProperty("test.classes") + slash;
+
+    public static void main(String... args) throws Throwable {
+        // delete this class to cause a NoClassDefFoundError
+        File unresolved = new File(testClasses, "MyUnresolvedClass.class");
+        if (unresolved.exists() && !unresolved.delete()) {
+            throw new Exception("Could not delete: " + unresolved);
+        }
+
+        // build the javaagent
+        buildJar("UnresolvedClassAgent");
+
+        // launch a VM with the javaagent
+        launchTest();
+    }
+
+    private static void buildJar(String jarName) throws Throwable {
+        String testSrc = System.getProperty("test.src", "?") + slash;
+
+        String jarPath = String.format("%s%s.jar", testClasses, jarName);
+        String manifestPath = String.format("%s%s.mf", testSrc, jarName);
+        String className = String.format("%s.class", jarName);
+
+        String[] args = new String[] {"-cfm", jarPath, manifestPath, "-C", testClasses, className};
+
+        System.out.println("Running jar " + Arrays.toString(args));
+        sun.tools.jar.Main jarTool = new sun.tools.jar.Main(System.out, System.err, "jar");
+        if (!jarTool.run(args)) {
+            throw new Exception("jar failed: args=" + Arrays.toString(args));
+        }
+    }
+
+    private static void launchTest() throws Throwable {
+        String[] args = {
+            "-javaagent:" + testClasses + "UnresolvedClassAgent.jar",
+            "-Dtest.classes=" + testClasses,
+            "UnresolvedClassAgent" };
+        OutputAnalyzer output = ProcessTools.executeTestJvm(args);
+        output.shouldHaveExitValue(0);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/serviceability/jvmti/UnresolvedClassAgent.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.DataInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.lang.instrument.ClassDefinition;
+import java.lang.instrument.Instrumentation;
+
+/*
+ * This class is present during compilation, but will be deleted before execution.
+ */
+class MyUnresolvedClass {
+    static void bar() {
+    }
+}
+
+class MyRedefinedClass {
+    static void foo() {
+        MyUnresolvedClass.bar();
+    }
+}
+
+public class UnresolvedClassAgent {
+    public static void main(String... args) {
+    }
+
+    public static void premain(String args, Instrumentation inst) throws Exception {
+        try {
+            MyRedefinedClass.foo();
+        } catch(NoClassDefFoundError err) {
+            System.out.println("NoClassDefFoundError (expected)");
+        }
+
+        File f = new File(System.getProperty("test.classes"), "MyRedefinedClass.class");
+        byte[] buf = new byte[(int)f.length()];
+        try (DataInputStream dis = new DataInputStream(new FileInputStream(f))) {
+            dis.readFully(buf);
+        }
+        ClassDefinition cd = new ClassDefinition(MyRedefinedClass.class, buf);
+        inst.redefineClasses(new ClassDefinition[] {cd});
+
+        try {
+            MyRedefinedClass.foo();
+        } catch(NoClassDefFoundError err) {
+            System.out.println("NoClassDefFoundError (expected again)");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/serviceability/jvmti/UnresolvedClassAgent.mf	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,3 @@
+Manifest-Version: 1.0
+Premain-Class: UnresolvedClassAgent
+Can-Redefine-Classes: true
--- a/hotspot/test/testlibrary/com/oracle/java/testlibrary/Platform.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/testlibrary/com/oracle/java/testlibrary/Platform.java	Wed Jul 05 19:33:51 2017 +0200
@@ -28,6 +28,15 @@
     private static final String dataModel   = System.getProperty("sun.arch.data.model");
     private static final String vmVersion   = System.getProperty("java.vm.version");
     private static final String osArch      = System.getProperty("os.arch");
+    private static final String vmName      = System.getProperty("java.vm.name");
+
+     public static boolean isClient() {
+         return vmName.endsWith(" Client VM");
+     }
+
+     public static boolean isServer() {
+         return vmName.endsWith(" Server VM");
+     }
 
     public static boolean is32bit() {
         return dataModel.equals("32");
--- a/hotspot/test/testlibrary/com/oracle/java/testlibrary/ProcessTools.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/hotspot/test/testlibrary/com/oracle/java/testlibrary/ProcessTools.java	Wed Jul 05 19:33:51 2017 +0200
@@ -163,10 +163,87 @@
 
     // Reporting
     StringBuilder cmdLine = new StringBuilder();
-    for (String cmd : args)
-        cmdLine.append(cmd).append(' ');
+    for (String cmd : args) {
+      cmdLine.append(cmd).append(' ');
+    }
     System.out.println("Command line: [" + cmdLine.toString() + "]");
 
     return new ProcessBuilder(args.toArray(new String[args.size()]));
   }
+
+  /**
+   * Executes a test jvm process, waits for it to finish and returns the process output.
+   * The default jvm options from jtreg, test.vm.opts and test.java.opts, are added.
+   * The java from the test.jdk is used to execute the command.
+   *
+   * The command line will be like:
+   * {test.jdk}/bin/java {test.vm.opts} {test.java.opts} cmds
+   *
+   * @param cmds User specifed arguments.
+   * @return The output from the process.
+   */
+  public static OutputAnalyzer executeTestJvm(String... cmds) throws Throwable {
+    ProcessBuilder pb = createJavaProcessBuilder(Utils.addTestJavaOpts(cmds));
+    return executeProcess(pb);
+  }
+
+  /**
+   * Executes a process, waits for it to finish and returns the process output.
+   * @param pb The ProcessBuilder to execute.
+   * @return The output from the process.
+   */
+  public static OutputAnalyzer executeProcess(ProcessBuilder pb) throws Throwable {
+    OutputAnalyzer output = null;
+    try {
+      output = new OutputAnalyzer(pb.start());
+      return output;
+    } catch (Throwable t) {
+      System.out.println("executeProcess() failed: " + t);
+      throw t;
+    } finally {
+      System.out.println(getProcessLog(pb, output));
+    }
+  }
+
+  /**
+   * Executes a process, waits for it to finish and returns the process output.
+   * @param cmds The command line to execute.
+   * @return The output from the process.
+   */
+  public static OutputAnalyzer executeProcess(String... cmds) throws Throwable {
+    return executeProcess(new ProcessBuilder(cmds));
+  }
+
+  /**
+   * Used to log command line, stdout, stderr and exit code from an executed process.
+   * @param pb The executed process.
+   * @param output The output from the process.
+   */
+  public static String getProcessLog(ProcessBuilder pb, OutputAnalyzer output) {
+    String stderr = output == null ? "null" : output.getStderr();
+    String stdout = output == null ? "null" : output.getStdout();
+    String exitValue = output == null ? "null": Integer.toString(output.getExitValue());
+    StringBuilder logMsg = new StringBuilder();
+    final String nl = System.getProperty("line.separator");
+    logMsg.append("--- ProcessLog ---" + nl);
+    logMsg.append("cmd: " + getCommandLine(pb) + nl);
+    logMsg.append("exitvalue: " + exitValue + nl);
+    logMsg.append("stderr: " + stderr + nl);
+    logMsg.append("stdout: " + stdout + nl);
+    return logMsg.toString();
+  }
+
+  /**
+   * @return The full command line for the ProcessBuilder.
+   */
+  public static String getCommandLine(ProcessBuilder pb) {
+    if (pb == null) {
+      return "null";
+    }
+    StringBuilder cmd = new StringBuilder();
+    for (String s : pb.command()) {
+      cmd.append(s).append(" ");
+    }
+    return cmd.toString().trim();
+  }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/testlibrary/com/oracle/java/testlibrary/Utils.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,263 @@
+/*
+ * 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 static com.oracle.java.testlibrary.Asserts.assertTrue;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
+
+/**
+ * Common library for various test helper functions.
+ */
+public final class Utils {
+
+    /**
+     * Returns the sequence used by operating system to separate lines.
+     */
+    public static final String NEW_LINE = System.getProperty("line.separator");
+
+    /**
+     * Returns the value of 'test.vm.opts'system property.
+     */
+    public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim();
+
+    /**
+     * Returns the value of 'test.java.opts'system property.
+     */
+    public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim();
+
+    /**
+    * Returns the value of 'test.timeout.factor' system property
+    * converted to {@code double}.
+    */
+    public static final double TIMEOUT_FACTOR;
+    static {
+        String toFactor = System.getProperty("test.timeout.factor", "1.0");
+        TIMEOUT_FACTOR = Double.parseDouble(toFactor);
+    }
+
+    private Utils() {
+        // Private constructor to prevent class instantiation
+    }
+
+    /**
+     * Returns the list of VM options.
+     *
+     * @return List of VM options
+     */
+    public static List<String> getVmOptions() {
+        return Arrays.asList(safeSplitString(VM_OPTIONS));
+    }
+
+    /**
+     * Returns the list of VM options with -J prefix.
+     *
+     * @return The list of VM options with -J prefix
+     */
+    public static List<String> getForwardVmOptions() {
+        String[] opts = safeSplitString(VM_OPTIONS);
+        for (int i = 0; i < opts.length; i++) {
+            opts[i] = "-J" + opts[i];
+        }
+        return Arrays.asList(opts);
+    }
+
+    /**
+     * Returns the default JTReg arguments for a jvm running a test.
+     * This is the combination of JTReg arguments test.vm.opts and test.java.opts.
+     * @return An array of options, or an empty array if no opptions.
+     */
+    public static String[] getTestJavaOpts() {
+        List<String> opts = new ArrayList<String>();
+        Collections.addAll(opts, safeSplitString(VM_OPTIONS));
+        Collections.addAll(opts, safeSplitString(JAVA_OPTIONS));
+        return opts.toArray(new String[0]);
+    }
+
+    /**
+     * Combines given arguments with default JTReg arguments for a jvm running a test.
+     * This is the combination of JTReg arguments test.vm.opts and test.java.opts
+     * @return The combination of JTReg test java options and user args.
+     */
+    public static String[] addTestJavaOpts(String... userArgs) {
+        List<String> opts = new ArrayList<String>();
+        Collections.addAll(opts, getTestJavaOpts());
+        Collections.addAll(opts, userArgs);
+        return opts.toArray(new String[0]);
+    }
+
+    /**
+     * Splits a string by white space.
+     * Works like String.split(), but returns an empty array
+     * if the string is null or empty.
+     */
+    private static String[] safeSplitString(String s) {
+        if (s == null || s.trim().isEmpty()) {
+            return new String[] {};
+        }
+        return s.trim().split("\\s+");
+    }
+
+    /**
+     * @return The full command line for the ProcessBuilder.
+     */
+    public static String getCommandLine(ProcessBuilder pb) {
+        StringBuilder cmd = new StringBuilder();
+        for (String s : pb.command()) {
+            cmd.append(s).append(" ");
+        }
+        return cmd.toString();
+    }
+
+    /**
+     * Returns the free port on the local host.
+     * The function will spin until a valid port number is found.
+     *
+     * @return The port number
+     * @throws InterruptedException if any thread has interrupted the current thread
+     * @throws IOException if an I/O error occurs when opening the socket
+     */
+    public static int getFreePort() throws InterruptedException, IOException {
+        int port = -1;
+
+        while (port <= 0) {
+            Thread.sleep(100);
+
+            ServerSocket serverSocket = null;
+            try {
+                serverSocket = new ServerSocket(0);
+                port = serverSocket.getLocalPort();
+            } finally {
+                serverSocket.close();
+            }
+        }
+
+        return port;
+    }
+
+    /**
+     * Returns the name of the local host.
+     *
+     * @return The host name
+     * @throws UnknownHostException if IP address of a host could not be determined
+     */
+    public static String getHostname() throws UnknownHostException {
+        InetAddress inetAddress = InetAddress.getLocalHost();
+        String hostName = inetAddress.getHostName();
+
+        assertTrue((hostName != null && !hostName.isEmpty()),
+                "Cannot get hostname");
+
+        return hostName;
+    }
+
+    /**
+     * Uses "jcmd -l" to search for a jvm pid. This function will wait
+     * forever (until jtreg timeout) for the pid to be found.
+     * @param key Regular expression to search for
+     * @return The found pid.
+     */
+    public static int waitForJvmPid(String key) throws Throwable {
+        final long iterationSleepMillis = 250;
+        System.out.println("waitForJvmPid: Waiting for key '" + key + "'");
+        System.out.flush();
+        while (true) {
+            int pid = tryFindJvmPid(key);
+            if (pid >= 0) {
+                return pid;
+            }
+            Thread.sleep(iterationSleepMillis);
+        }
+    }
+
+    /**
+     * Searches for a jvm pid in the output from "jcmd -l".
+     *
+     * Example output from jcmd is:
+     * 12498 sun.tools.jcmd.JCmd -l
+     * 12254 /tmp/jdk8/tl/jdk/JTwork/classes/com/sun/tools/attach/Application.jar
+     *
+     * @param key A regular expression to search for.
+     * @return The found pid, or -1 if Enot found.
+     * @throws Exception If multiple matching jvms are found.
+     */
+    public static int tryFindJvmPid(String key) throws Throwable {
+        OutputAnalyzer output = null;
+        try {
+            JDKToolLauncher jcmdLauncher = JDKToolLauncher.create("jcmd");
+            jcmdLauncher.addToolArg("-l");
+            output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
+            output.shouldHaveExitValue(0);
+
+            // Search for a line starting with numbers (pid), follwed by the key.
+            Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
+            Matcher matcher = pattern.matcher(output.getStdout());
+
+            int pid = -1;
+            if (matcher.find()) {
+                pid = Integer.parseInt(matcher.group(1));
+                System.out.println("findJvmPid.pid: " + pid);
+                if (matcher.find()) {
+                    throw new Exception("Found multiple JVM pids for key: " + key);
+                }
+            }
+            return pid;
+        } catch (Throwable t) {
+            System.out.println(String.format("Utils.findJvmPid(%s) failed: %s", key, t));
+            throw t;
+        }
+    }
+
+    /**
+     * Returns file content as a list of strings
+     *
+     * @param file File to operate on
+     * @return List of strings
+     * @throws IOException
+     */
+    public static List<String> fileAsList(File file) throws IOException {
+        assertTrue(file.exists() && file.isFile(),
+                file.getAbsolutePath() + " does not exist or not a file");
+        List<String> output = new ArrayList<>();
+        try (BufferedReader reader = new BufferedReader(new FileReader(file.getAbsolutePath()))) {
+            while (reader.ready()) {
+                output.add(reader.readLine().replace(NEW_LINE, ""));
+            }
+        }
+        return output;
+    }
+
+}
--- a/jdk/.hgtags	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/.hgtags	Wed Jul 05 19:33:51 2017 +0200
@@ -247,3 +247,4 @@
 8c8275426a3207d91393354f7a7f9bc362ec25cf jdk9-b02
 4111af6151ed8ca8e3f5603c69729a68427e1d5b jdk9-b03
 627deed79b595a4789fc9151455b663a47381257 jdk9-b04
+263198a1d8f1f4cb97d35f40c61704b08ebd3686 jdk9-b05
--- a/jdk/make/CompileJavaClasses.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/CompileJavaClasses.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -307,12 +307,6 @@
       $(JDK_TOPDIR)/src/solaris/classes/sun/nio/ch/sctp/SctpServerChannelImpl.java
 endif
 
-# The exception handling of swing beaninfo
-# These resources violates the convention of having code and resources together under
-# $(JDK_TOPDIR)/src/.../classes directories
-$(JDK_OUTPUTDIR)/classes/javax/swing/beaninfo/images/%.gif: $(JDK_TOPDIR)/make/data/swingbeaninfo/images/%.gif
-	$(call install-file)
-
 # The JDK_USER_DEFINED_FILTER is a poor man's incremental build: by specifying
 # JDK_FILTER at the make command line, only a subset of the JDK java files will
 # be recompiled. If multiple paths are separated by comma, convert that into a
@@ -341,6 +335,7 @@
     BIN:=$(JDK_OUTPUTDIR)/classes,\
     COPY:=$(COPY_PATTERNS),\
     COPY_FILES:=$(COPY_FILES),\
+    CLEAN_FILES:=$(CLEAN_FILES),\
     HEADERS:=$(JDK_OUTPUTDIR)/gensrc_headers,\
     ADD_JAVAC_FLAGS:=$(BUILD_JDK_SOURCEPATH)))
 
@@ -378,7 +373,8 @@
           SETUP := GENERATE_JDKBYTECODE, \
           JAVAC_FLAGS := -cp $(JDK_OUTPUTDIR)/classes, \
           SRC := $(JDK_OUTPUTDIR)/gensrc_ab/32bit, \
-          BIN := $(JDK_OUTPUTDIR)/classes_ab/32bit))
+          BIN := $(JDK_OUTPUTDIR)/classes_ab/32bit, \
+          HEADERS := $(JDK_OUTPUTDIR)/gensrc_headers))
 
       $(BUILD_ACCESSBRIDGE_32): $(BUILD_JDK)
 
@@ -386,7 +382,8 @@
           SETUP := GENERATE_JDKBYTECODE, \
           JAVAC_FLAGS := -cp $(JDK_OUTPUTDIR)/classes, \
           SRC := $(JDK_OUTPUTDIR)/gensrc_ab/legacy, \
-          BIN := $(JDK_OUTPUTDIR)/classes_ab/legacy))
+          BIN := $(JDK_OUTPUTDIR)/classes_ab/legacy, \
+          HEADERS := $(JDK_OUTPUTDIR)/gensrc_headers))
 
       $(BUILD_ACCESSBRIDGE_LEGACY): $(BUILD_JDK)
 
@@ -396,7 +393,8 @@
           SETUP := GENERATE_JDKBYTECODE, \
           JAVAC_FLAGS := -cp $(JDK_OUTPUTDIR)/classes, \
           SRC := $(JDK_OUTPUTDIR)/gensrc_ab/64bit, \
-          BIN := $(JDK_OUTPUTDIR)/classes_ab/64bit))
+          BIN := $(JDK_OUTPUTDIR)/classes_ab/64bit, \
+          HEADERS := $(JDK_OUTPUTDIR)/gensrc_headers))
 
       $(BUILD_ACCESSBRIDGE_64): $(BUILD_JDK)
 
--- a/jdk/make/CompileLaunchers.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/CompileLaunchers.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -32,7 +32,7 @@
 # Setup the java compilers for the JDK build.
 include Setup.gmk
 
-# Prepare the find cache. Only used on windows.
+# Prepare the find cache.
 $(eval $(call FillCacheFind, $(JDK_TOPDIR)/src/share/bin))
 
 # Build tools
--- a/jdk/make/CompileNativeLibraries.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/CompileNativeLibraries.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -35,7 +35,7 @@
 # Copy files (can now depend on $(COPY_FILES))
 include CopyFiles.gmk
 
-# Prepare the find cache. Only used if running on windows.
+# Prepare the find cache.
 $(eval $(call FillCacheFind, $(JDK_TOPDIR)/src))
 
 # Build tools
--- a/jdk/make/CopyIntoClasses.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/CopyIntoClasses.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -25,121 +25,53 @@
 
 # Copy icu and _dict files used by the text break iterator
 
-COPY_PATTERNS = .icu _dict
-
-# Copy config files for com.sun.org.apache.xml.internal.security
-
-XMLSECURITY_RESOURCEDIR = $(JDK_TOPDIR)/src/share/classes/com/sun/org/apache/xml/internal/security/resource
-COPY_FILES += \
-    $(XMLSECURITY_RESOURCEDIR)/config.dtd \
-    $(XMLSECURITY_RESOURCEDIR)/config.xml
-
-# Copy sun/tools related files into the classes directory.
-
-# Extra jstat files
-JSTAT_RESOURCEDIR = $(JDK_TOPDIR)/src/share/classes/sun/tools/jstat/resources
-COPY_FILES += \
-    $(JSTAT_RESOURCEDIR)/jstat_options \
-    $(JSTAT_RESOURCEDIR)/jstat_unsupported_options
-
-# Extra jhat files
-JHAT_RESOURCEDIR = $(JDK_TOPDIR)/src/share/classes/com/sun/tools/hat/resources
-COPY_FILES += \
-    $(JHAT_RESOURCEDIR)/hat.js \
-    $(JHAT_RESOURCEDIR)/oqlhelp.html \
-    $(JHAT_RESOURCEDIR)/platform_names.txt
+COPY_PATTERNS := .icu _dict .dat _options .js aliasmap .spp .wav .css \
+    .png .gif .xml .dtd .txt oqlhelp.html
 
-# Extra jrunscript files
-JRUNSCRIPT_RESOURCEDIR = $(JDK_TOPDIR)/src/share/classes/com/sun/tools/script/shell
-COPY_FILES += \
-    $(JRUNSCRIPT_RESOURCEDIR)/init.js \
-    $(JRUNSCRIPT_RESOURCEDIR)/messages.properties
-
-# Extra jvmstat files
-COPY_FILES += \
-    $(JDK_TOPDIR)/src/share/classes/sun/jvmstat/perfdata/resources/aliasmap
-
-# JConsole resources
-JCONSOLE_RESOURCES_DIR = $(JDK_TOPDIR)/src/share/classes/sun/tools/jconsole/resources
-COPY_FILES += \
-    $(wildcard $(JCONSOLE_RESOURCES_DIR)/*.png) \
-    $(wildcard $(JCONSOLE_RESOURCES_DIR)/*.gif)
+# These directories should not be copied at all
+EXCLUDES += \
+    com/sun/org/apache/xml/internal/security/resource/schema \
+    java/awt/doc-files \
+    java/lang/doc-files \
+    javax/swing/doc-files \
+    javax/swing/text/doc-files \
+    javax/swing/plaf/synth/doc-files \
+    javax/swing/undo/doc-files \
+    sun/awt/X11/doc-files \
+    sun/util/cldr/resources \
+    #
 
-# Print resources
-PRINT_RESOURCES_DIR = $(JDK_TOPDIR)/src/share/classes/sun/print/resources
-COPY_FILES += \
-    $(wildcard $(PRINT_RESOURCES_DIR)/*.png)
+# These files should never be included
+EXFILES += build.xml README.txt version.txt
 
-# IDN resources
-COPY_FILES += \
-    $(JDK_TOPDIR)/src/share/classes/sun/net/idn/uidna.spp
-
-#
-# Swing plaf resources
-#
-SWING_PLAF_WINDOWS_RESOURCES_DIR = $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/windows
-COPY_FILES += \
-    $(wildcard $(SWING_PLAF_WINDOWS_RESOURCES_DIR)/icons/*.gif) \
-    $(wildcard $(SWING_PLAF_WINDOWS_RESOURCES_DIR)/icons/*.png)
+# These icons are handled in GensrcIcons.gmk
+EXFILES += \
+    sun/awt/X11/java-icon16.png \
+    sun/awt/X11/java-icon24.png \
+    sun/awt/X11/java-icon32.png \
+    sun/awt/X11/java-icon48.png \
+    $(wildcard $(JDK_TOPDIR)/src/share/classes/sun/awt/resources/*.png) \
+    #
 
 ifndef OPENJDK
-  SWING_PLAF_WINDOWS_RESOURCES_DIR_CLOSED = $(JDK_TOPDIR)/src/closed/share/classes/com/sun/java/swing/plaf/windows
-  # Filter out JavaCup32.png from OpenJDK
-  COPY_FILES := $(filter-out $(SWING_PLAF_WINDOWS_RESOURCES_DIR)/icons/JavaCup32.png, $(COPY_FILES))
-  # Alter JavaCup32.png from ClosedJDK
-  COPY_FILES += \
-      $(SWING_PLAF_WINDOWS_RESOURCES_DIR_CLOSED)/icons/JavaCup32.png
+  # Theses icons have closed replacements
+  SWING_PLAF_MOTIF_RESOURCES_DIR := $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/motif
+  EXFILES += \
+      $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/windows/icons/JavaCup32.png \
+      $(JDK_TOPDIR)/src/share/classes/javax/swing/plaf/basic/icons/JavaCup16.png \
+      $(wildcard $(SWING_PLAF_MOTIF_RESOURCES_DIR)/icons/*.gif) \
+      $(wildcard $(SWING_PLAF_MOTIF_RESOURCES_DIR)/icons/*.png) \
+      #
+
+  EXFILES += mib_core.txt
 endif
 
 ifeq ($(ENABLE_JFR), true)
-  JFR_CONFIGURATION_DIR_CLOSED = $(JDK_TOPDIR)/src/closed/share/classes/oracle/jrockit/jfr/settings
+  JFR_CONFIGURATION_DIR_CLOSED := $(JDK_TOPDIR)/src/closed/share/classes/oracle/jrockit/jfr/settings
   COPY_FILES += \
       $(JFR_CONFIGURATION_DIR_CLOSED)/jfc.xsd
 endif
 
-SWING_PLAF_BASIC_RESOURCES_DIR = $(JDK_TOPDIR)/src/share/classes/javax/swing/plaf/basic
-COPY_FILES += \
-    $(wildcard $(SWING_PLAF_BASIC_RESOURCES_DIR)/icons/*.png)
-
-ifndef OPENJDK
-  SWING_PLAF_BASIC_RESOURCES_DIR_CLOSED = $(JDK_TOPDIR)/src/closed/share/classes/javax/swing/plaf/basic
-  # Filter out JavaCup16.png from OpenJDK
-  COPY_FILES := $(filter-out $(SWING_PLAF_BASIC_RESOURCES_DIR)/icons/JavaCup16.png, $(COPY_FILES))
-  # Alter JavaCup16.png from ClosedJDK
-  COPY_FILES += \
-      $(SWING_PLAF_BASIC_RESOURCES_DIR_CLOSED)/icons/JavaCup16.png
-endif
-
-ifdef OPENJDK
-  SWING_PLAF_MOTIF_RESOURCES_DIR = $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/motif
-  COPY_FILES += \
-      $(wildcard $(SWING_PLAF_MOTIF_RESOURCES_DIR)/icons/*.gif) \
-      $(wildcard $(SWING_PLAF_MOTIF_RESOURCES_DIR)/icons/*.png)
-else
-  SWING_PLAF_MOTIF_RESOURCES_DIR_CLOSED = $(JDK_TOPDIR)/src/closed/share/classes/com/sun/java/swing/plaf/motif
-  COPY_FILES += \
-      $(wildcard $(SWING_PLAF_MOTIF_RESOURCES_DIR_CLOSED)/icons/*.gif) \
-      $(wildcard $(SWING_PLAF_MOTIF_RESOURCES_DIR_CLOSED)/icons/*.png)
-endif
-
-SWING_PLAF_METAL_RESOURCES_DIR = $(JDK_TOPDIR)/src/share/classes/javax/swing/plaf/metal
-COPY_FILES += \
-    $(wildcard $(SWING_PLAF_METAL_RESOURCES_DIR)/icons/*.gif) \
-    $(wildcard $(SWING_PLAF_METAL_RESOURCES_DIR)/icons/*.png) \
-    $(wildcard $(SWING_PLAF_METAL_RESOURCES_DIR)/icons/ocean/*.gif) \
-    $(wildcard $(SWING_PLAF_METAL_RESOURCES_DIR)/icons/ocean/*.png) \
-    $(wildcard $(SWING_PLAF_METAL_RESOURCES_DIR)/sounds/*.wav)
-
-ifneq ($(OPENJDK_TARGET_OS), windows)
-  # Only copy GTK resources on Solaris/Linux
-  SWING_PLAF_GTK_RESOURCES_DIR = $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/gtk
-  COPY_FILES += \
-      $(wildcard $(SWING_PLAF_GTK_RESOURCES_DIR)/icons/*.gif) \
-      $(wildcard $(SWING_PLAF_GTK_RESOURCES_DIR)/icons/*.png) \
-      $(wildcard $(SWING_PLAF_GTK_RESOURCES_DIR)/resources/metacity/SwingFallbackTheme/metacity-1/*.xml)
-endif
-# END: Swing plaf resources
-
 SWING_BEANINFO_RESOURCES_SRC_DIR = $(JDK_TOPDIR)/make/data/swingbeaninfo/images
 SWING_BEANINFO_RESOURCES_SRC = $(wildcard $(SWING_BEANINFO_RESOURCES_SRC_DIR)/*.gif)
 OUT_BEANINFO_RESOURCES = $(patsubst $(SWING_BEANINFO_RESOURCES_SRC_DIR)%, \
@@ -147,13 +79,13 @@
     $(SWING_BEANINFO_RESOURCES_SRC))
 
 COPY_EXTRA += $(OUT_BEANINFO_RESOURCES)
-# END: Swing beaninfo resources
 
-# Swing text resources
-SWING_TEXT_RESOURCEDIR = $(JDK_TOPDIR)/src/share/classes/javax/swing/text
-COPY_FILES += \
-    $(SWING_TEXT_RESOURCEDIR)/html/default.css \
-    $(wildcard $(SWING_TEXT_RESOURCEDIR)/rtf/charsets/*.txt)
+# The exception handling of swing beaninfo
+# These resources violates the convention of having code and resources together under
+# $(JDK_TOPDIR)/src/.../classes directories
+$(JDK_OUTPUTDIR)/classes/javax/swing/beaninfo/images/%.gif: \
+    $(JDK_TOPDIR)/make/data/swingbeaninfo/images/%.gif
+	$(call install-file)
 
 ##########################################################################################
 #
@@ -222,14 +154,7 @@
 COPY_EXTRA += $(OUT_SERVICES_FILES)
 COPY_EXTRA += $(OUT_SERVICES_FILES_PRINT)
 
-###
-
-$(JDK_OUTPUTDIR)/classes/sun/nio/cs/ext/sjis0213.dat: $(JDK_OUTPUTDIR)/gensrc/sun/nio/cs/ext/sjis0213.dat
-	$(call install-file)
-
-COPY_EXTRA += $(JDK_OUTPUTDIR)/classes/sun/nio/cs/ext/sjis0213.dat
-
-###
+################################################################################
 
 JAVAX_SOUND_SRC := $(JDK_TOPDIR)/src/share/classes/com/sun/media/sound/services
 
@@ -248,3 +173,30 @@
 JAVAX_SOUND_RULES := $(foreach F, $(JAVAX_SOUND_SRC_FILES), $(JDK_OUTPUTDIR)/classes/META-INF/services/$(notdir $F):$(JAVAX_SOUND_SRC)/$F)
 
 $(foreach R, $(JAVAX_SOUND_RULES), $(eval $(call addto_meta-inf_services, $R)))
+
+################################################################################
+
+CLEAN_FILES := $(wildcard \
+    $(JDK_TOPDIR)/src/share/classes/com/sun/imageio/plugins/common/*.properties \
+    $(JDK_TOPDIR)/src/share/classes/com/sun/java/util/jar/pack/*.properties \
+    $(JDK_TOPDIR)/src/share/classes/com/sun/jndi/cosnaming/jndiprovider.properties \
+    $(JDK_TOPDIR)/src/share/classes/com/sun/jndi/ldap/jndiprovider.properties \
+    $(JDK_TOPDIR)/src/share/classes/com/sun/org/apache/xml/internal/security/resource/*.properties \
+    $(JDK_TOPDIR)/src/share/classes/com/sun/rowset/*.properties \
+    $(JDK_TOPDIR)/src/share/classes/com/sun/tools/script/shell/*.properties \
+    $(JDK_TOPDIR)/src/share/classes/javax/sql/rowset/*.properties \
+    $(JDK_TOPDIR)/src/share/classes/sun/rmi/registry/resources/*.properties \
+    $(JDK_TOPDIR)/src/share/classes/sun/rmi/rmic/resources/*.properties \
+    $(JDK_TOPDIR)/src/share/classes/sun/rmi/server/resources/*.properties \
+    $(JDK_TOPDIR)/src/share/classes/sun/tools/javac/resources/*.properties \
+    $(JDK_TOPDIR)/src/share/classes/sun/tools/jconsole/resources/*.properties \
+    $(JDK_TOPDIR)/src/share/classes/sun/tools/serialver/resources/*.properties \
+    )
+
+# Copy zh_HK files from zh_TW
+
+$(JDK_OUTPUTDIR)/classes/%_zh_HK.properties: $(JDK_OUTPUTDIR)/classes/%_zh_TW.properties
+	$(install-file)
+
+COPY_EXTRA += $(patsubst $(JDK_TOPDIR)/src/share/classes/%, $(JDK_OUTPUTDIR)/classes/%, \
+    $(subst _zh_TW,_zh_HK, $(filter %_zh_TW.properties, $(CLEAN_FILES))))
--- a/jdk/make/CreateJars.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/CreateJars.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -30,9 +30,6 @@
 
 default: all
 
-# Prepare the find cache. Only used if running on windows.
-$(eval $(call FillCacheFind, $(JDK_OUTPUTDIR)/classes))
-
 include Tools.gmk
 
 include Profiles.gmk
--- a/jdk/make/Images.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/Images.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -30,7 +30,7 @@
 
 default: images
 
-# Prepare the find cache. Only used if running on windows.
+# Prepare the find cache.
 $(eval $(call FillCacheFind, \
     $(wildcard $(JDK_OUTPUTDIR)/bin \
         $(JDK_OUTPUTDIR)/lib \
--- a/jdk/make/Import.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/Import.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -252,7 +252,7 @@
 	$(ECHO) Unzipping $(<F)
 	$(MKDIR) -p $(@D)
 	$(RM) $@
-	($(CD) $(JDK_OUTPUTDIR) && $(UNZIP) $< > $@.tmp)
+	($(CD) $(JDK_OUTPUTDIR) && $(UNZIP) -q -o $< > $@.tmp)
 	$(MV) $@.tmp $@
 endef
 
--- a/jdk/make/Setup.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/Setup.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -38,7 +38,7 @@
 # boot jdk to generate tools that need to be run with the boot jdk.
 # Thus we force the target bytecode to the previous JDK version.
 $(eval $(call SetupJavaCompiler,GENERATE_OLDBYTECODE, \
-    JVM := $(JAVA), \
+    JVM := $(JAVA_SMALL), \
     JAVAC := $(NEW_JAVAC), \
     FLAGS := $(BOOT_JDK_SOURCETARGET) -bootclasspath $(BOOT_RTJAR) $(DISABLE_WARNINGS), \
     SERVER_DIR := $(SJAVAC_SERVER_DIR), \
@@ -60,7 +60,7 @@
 # I.e. the rt.jar, but since rt.jar has not yet been generated
 # (it will be in "make images") therefore we use classes instead.
 $(eval $(call SetupJavaCompiler,GENERATE_USINGJDKBYTECODE, \
-    JVM := $(JAVA), \
+    JVM := $(JAVA_SMALL), \
     JAVAC := $(NEW_JAVAC), \
     FLAGS := -bootclasspath $(JDK_OUTPUTDIR)/classes $(DISABLE_WARNINGS), \
     SERVER_DIR := $(SJAVAC_SERVER_DIR), \
--- a/jdk/make/Tools.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/Tools.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
 # 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,7 +23,7 @@
 # questions.
 #
 
-# Cache all finds needed for this file. Only used on windows.
+# Cache all finds needed for this file.
 $(eval $(call FillCacheFind, $(JDK_TOPDIR)/make/src/classes))
 
 # The exception handling of swing beaninfo which have the own tool directory
@@ -48,79 +48,76 @@
 BUILD_TOOLS += $(JDK_OUTPUTDIR)/btclasses/build/tools/deps/refs.allowed
 
 # Add a checksum ("jsum") to the end of a text file. Prevents trivial tampering with class lists.
-TOOL_ADDJSUM = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_ADDJSUM = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.addjsum.AddJsum
 
 # The buildmetaindex tool creates a meta-index to make core class loaders lazier.
-TOOL_BUILDMETAINDEX = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_BUILDMETAINDEX = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.buildmetaindex.BuildMetaIndex
 
-TOOL_COMPILEFONTCONFIG = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_COMPILEFONTCONFIG = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.compilefontconfig.CompileFontConfig
 
-TOOL_COMPILEPROPERTIES = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_COMPILEPROPERTIES = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.compileproperties.CompileProperties
 
-TOOL_STRIPPROPERTIES = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
-    build.tools.stripproperties.StripProperties
-
-TOOL_JARREORDER = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_JARREORDER = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.jarreorder.JarReorder
 
-TOOL_GENERATECHARACTER = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_GENERATECHARACTER = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.generatecharacter.GenerateCharacter
 
-TOOL_CHARACTERNAME = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_CHARACTERNAME = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.generatecharacter.CharacterName
 
-TOOL_DTDBUILDER = $(JAVA) -Ddtd_home=$(JDK_TOPDIR)/make/data/dtdbuilder \
+TOOL_DTDBUILDER = $(JAVA_SMALL) -Ddtd_home=$(JDK_TOPDIR)/make/data/dtdbuilder \
     -cp $(JDK_OUTPUTDIR)/btclasses build.tools.dtdbuilder.DTDBuilder
 
-TOOL_GENERATEBREAKITERATORDATA = $(JAVA) \
+TOOL_GENERATEBREAKITERATORDATA = $(JAVA_SMALL) \
     -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.generatebreakiteratordata.GenerateBreakIteratorData
 
-TOOL_GENERATECURRENCYDATA = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_GENERATECURRENCYDATA = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.generatecurrencydata.GenerateCurrencyData
 
-TOOL_HASHER = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_HASHER = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.hasher.Hasher
 
-TOOL_TZDB = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_TZDB = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.tzdb.TzdbZoneRulesCompiler
 
 
 # TODO: There are references to the jdwpgen.jar in jdk/make/netbeans/jdwpgen/build.xml
 # and nbproject/project.properties in the same dir. Needs to be looked at.
-TOOL_JDWPGEN = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses build.tools.jdwpgen.Main
+TOOL_JDWPGEN = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses build.tools.jdwpgen.Main
 
 # TODO: Lots of files in jdk/make/tools/CharsetMapping dir
-TOOL_CHARSETMAPPING = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_CHARSETMAPPING = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.charsetmapping.Main $(LOG_INFO)
 
-TOOL_SPP = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses build.tools.spp.Spp
+TOOL_SPP = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses build.tools.spp.Spp
 
 # Nimbus is used somewhere in the swing build.
-TOOL_GENERATENIMBUS = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_GENERATENIMBUS = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.generatenimbus.Generator
 
-TOOL_WRAPPERGENERATOR = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_WRAPPERGENERATOR = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.x11wrappergen.WrapperGenerator
 
-TOOL_AWT_TOBIN = $(JAVA) -Djava.awt.headless=true -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_AWT_TOBIN = $(JAVA_SMALL) -Djava.awt.headless=true -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.icondata.awt.ToBin
 
-TOOL_OSX_TOBIN = $(JAVA) -Djava.awt.headless=true -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_OSX_TOBIN = $(JAVA_SMALL) -Djava.awt.headless=true -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.icondata.osxapp.ToBin
 
-TOOL_CLDRCONVERTER = $(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_CLDRCONVERTER = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.cldrconverter.CLDRConverter
 
-TOOL_CHECKDEPS = $(JAVA) -Xbootclasspath/p:$(INTERIM_LANGTOOLS_JAR) \
+TOOL_CHECKDEPS = $(JAVA_SMALL) -Xbootclasspath/p:$(INTERIM_LANGTOOLS_JAR) \
     -cp $(JDK_OUTPUTDIR)/btclasses:$(JDK_OUTPUTDIR) \
     build.tools.deps.CheckDeps
 
-TOOL_ADDTORESTRICTEDPKGS=$(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
+TOOL_ADDTORESTRICTEDPKGS = $(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
     build.tools.addtorestrictedpkgs.AddToRestrictedPkgs
 
 ##########################################################################################
--- a/jdk/make/data/tzdata/VERSION	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/data/tzdata/VERSION	Wed Jul 05 19:33:51 2017 +0200
@@ -21,4 +21,4 @@
 # or visit www.oracle.com if you need additional information or have any
 # questions.
 #
-tzdata2013i
+tzdata2014a
--- a/jdk/make/data/tzdata/asia	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/data/tzdata/asia	Wed Jul 05 19:33:51 2017 +0200
@@ -1113,8 +1113,13 @@
 Rule	Zion	1986	only	-	Sep	 7	0:00	0	S
 Rule	Zion	1987	only	-	Apr	15	0:00	1:00	D
 Rule	Zion	1987	only	-	Sep	13	0:00	0	S
-Rule	Zion	1988	only	-	Apr	 9	0:00	1:00	D
-Rule	Zion	1988	only	-	Sep	 3	0:00	0	S
+
+# From Avigdor Finkelstein (2014-03-05):
+# I check the Parliament (Knesset) records and there it's stated that the
+# [1988] transition should take place on Saturday night, when the Sabbath
+# ends and changes to Sunday.
+Rule	Zion	1988	only	-	Apr	10	0:00	1:00	D
+Rule	Zion	1988	only	-	Sep	 4	0:00	0	S
 
 # From Ephraim Silverberg
 # (1997-03-04, 1998-03-16, 1998-12-28, 2000-01-17, 2000-07-25, 2004-12-22,
--- a/jdk/make/data/tzdata/australasia	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/data/tzdata/australasia	Wed Jul 05 19:33:51 2017 +0200
@@ -377,16 +377,18 @@
 # http://www.fiji.gov.fj/index.php?option=com_content&view=article&id=6702&catid=71&Itemid=155
 
 # From the Fijian Government Media Center (2013-08-30) via David Wheeler:
-# Fiji will start daylight savings on Sunday 27th October, 2013 and end at 3am
-# on Sunday 19th January, 2014....  move clocks forward by one hour from 2am
+# Fiji will start daylight savings on Sunday 27th October, 2013 ...
+# move clocks forward by one hour from 2am
 # http://www.fiji.gov.fj/Media-Center/Press-Releases/DAYLIGHT-SAVING-STARTS-ON-SUNDAY,-27th-OCTOBER-201.aspx
-#
-# From Paul Eggert (2013-09-09):
+
+# From Steffen Thorsen (2013-01-10):
+# Fiji will end DST on 2014-01-19 02:00:
+# http://www.fiji.gov.fj/Media-Center/Press-Releases/DAYLIGHT-SAVINGS-TO-END-THIS-MONTH-%281%29.aspx
+
+# From Paul Eggert (2014-01-10):
 # For now, guess that Fiji springs forward the Sunday before the fourth
-# Monday in October.  This matches both recent practice and
-# timeanddate.com's current spring-forward prediction.
-# For the January 2014 transition we guessed right while timeanddate.com
-# guessed wrong, so leave the fall-back prediction alone.
+# Monday in October, and springs back the penultimate Sunday in January.
+# This is ad hoc, but matches recent practice.
 
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Fiji	1998	1999	-	Nov	Sun>=1	2:00	1:00	S
@@ -395,7 +397,8 @@
 Rule	Fiji	2010	only	-	Mar	lastSun	3:00	0	-
 Rule	Fiji	2010	max	-	Oct	Sun>=21	2:00	1:00	S
 Rule	Fiji	2011	only	-	Mar	Sun>=1	3:00	0	-
-Rule	Fiji	2012	max	-	Jan	Sun>=18	3:00	0	-
+Rule	Fiji	2012	2013	-	Jan	Sun>=18	3:00	0	-
+Rule	Fiji	2014	max	-	Jan	Sun>=18	2:00	0	-
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Pacific/Fiji	11:55:44 -	LMT	1915 Oct 26	# Suva
 			12:00	Fiji	FJ%sT	# Fiji Time
--- a/jdk/make/data/tzdata/europe	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/data/tzdata/europe	Wed Jul 05 19:33:51 2017 +0200
@@ -2768,14 +2768,18 @@
 # According to the articles linked below, Turkey will change into summer
 # time zone (GMT+3) on March 28, 2011 at 3:00 a.m. instead of March 27.
 # This change is due to a nationwide exam on 27th.
-#
-# <a href="http://www.worldbulletin.net/?aType=haber&ArticleID=70872">
 # http://www.worldbulletin.net/?aType=haber&ArticleID=70872
-# </a>
 # Turkish:
-# <a href="http://www.hurriyet.com.tr/ekonomi/17230464.asp?gid=373">
 # http://www.hurriyet.com.tr/ekonomi/17230464.asp?gid=373
-# </a>
+
+# From Faruk Pasin (2014-02-14):
+# The DST for Turkey has been changed for this year because of the
+# Turkish Local election....
+# http://www.sabah.com.tr/Ekonomi/2014/02/12/yaz-saatinde-onemli-degisiklik
+# ... so Turkey will move clocks forward one hour on March 31 at 3:00 a.m.
+# From Paul Eggert (2014-02-17):
+# Here is an English-language source:
+# http://www.worldbulletin.net/turkey/129016/turkey-switches-to-daylight-saving-time-march-31
 
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Turkey	1916	only	-	May	 1	0:00	1:00	S
@@ -2844,6 +2848,8 @@
 			2:00	Turkey	EE%sT	2007
 			2:00	EU	EE%sT	2011 Mar 27 1:00u
 			2:00	-	EET	2011 Mar 28 1:00u
+			2:00	EU	EE%sT	2014 Mar 30 1:00u
+			2:00	-	EET	2014 Mar 31 1:00u
 			2:00	EU	EE%sT
 Link	Europe/Istanbul	Asia/Istanbul	# Istanbul is in both continents.
 
@@ -2865,19 +2871,13 @@
 # approval from 266 deputies.
 #
 # Ukraine abolishes transter back to the winter time (in Russian)
-# <a href="http://news.mail.ru/politics/6861560/">
 # http://news.mail.ru/politics/6861560/
-# </a>
 #
 # The Ukrainians will no longer change the clock (in Russian)
-# <a href="http://www.segodnya.ua/news/14290482.html">
 # http://www.segodnya.ua/news/14290482.html
-# </a>
 #
 # Deputies cancelled the winter time (in Russian)
-# <a href="http://www.pravda.com.ua/rus/news/2011/09/20/6600616/">
 # http://www.pravda.com.ua/rus/news/2011/09/20/6600616/
-# </a>
 #
 # From Philip Pizzey (2011-10-18):
 # Today my Ukrainian colleagues have informed me that the
@@ -2888,18 +2888,39 @@
 # As far as I understand, the recent change to the Ukrainian time zone
 # (Europe/Kiev) to introduce permanent daylight saving time (similar
 # to Russia) was reverted today:
-#
-# <a href="http://portal.rada.gov.ua/rada/control/en/publish/article/info_left?art_id=287324&cat_id=105995">
 # http://portal.rada.gov.ua/rada/control/en/publish/article/info_left?art_id=287324&cat_id=105995
-# </a>
 #
 # Also reported by Alexander Bokovoy (2011-10-18) who also noted:
 # The law documents themselves are at
+# http://w1.c1.rada.gov.ua/pls/zweb_n/webproc4_1?id=&pf3511=41484
+
+# From Vladimir in Moscow via Alois Treindl re Kiev time 1991/2 (2014-02-28):
+# First in Ukraine they changed Time zone from UTC+3 to UTC+2 with DST:
+#       03 25 1990 02:00 -03.00 1       Time Zone 3 with DST
+#       07 01 1990 02:00 -02.00 1       Time Zone 2 with DST
+# * Ukrainian Government's Resolution of 18.06.1990, No. 134.
+# http://search.ligazakon.ua/l_doc2.nsf/link1/T001500.html
 #
-# <a href="http://w1.c1.rada.gov.ua/pls/zweb_n/webproc4_1?id=&pf3511=41484">
-# http://w1.c1.rada.gov.ua/pls/zweb_n/webproc4_1?id=&pf3511=41484
-# </a>
-
+# They did not end DST in September, 1990 (according to the law,
+# "summer time" was still in action):
+#       09 30 1990 03:00 -02.00 1       Time Zone 2 with DST
+# * Ukrainian Government's Resolution of 21.09.1990, No. 272.
+# http://search.ligazakon.ua/l_doc2.nsf/link1/KP900272.html
+#
+# Again no change in March, 1991 ("summer time" in action):
+#       03 31 1991 02:00 -02.00 1       Time Zone 2 with DST
+#
+# DST ended in September 1991 ("summer time" ended):
+#       09 29 1991 03:00 -02.00 0       Time Zone 2, no DST
+# * Ukrainian Government's Resolution of 25.09.1991, No. 225.
+# http://www.uazakon.com/documents/date_21/pg_iwgdoc.htm
+# This is an answer.
+#
+# Since 1992 they had normal DST procedure:
+#       03 29 1992 02:00 -02.00 1       DST started
+#       09 27 1992 03:00 -02.00 0       DST ended
+# * Ukrainian Government's Resolution of 20.03.1992, No. 139.
+# http://www.uazakon.com/documents/date_8u/pg_grcasa.htm
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 # Most of Ukraine since 1970 has been like Kiev.
@@ -2910,9 +2931,8 @@
 			2:00	-	EET	1930 Jun 21
 			3:00	-	MSK	1941 Sep 20
 			1:00	C-Eur	CE%sT	1943 Nov  6
-			3:00	Russia	MSK/MSD	1990
-			3:00	-	MSK	1990 Jul  1 2:00
-			2:00	-	EET	1992
+			3:00	Russia	MSK/MSD	1990 Jul  1 2:00
+			2:00	1:00	EEST	1991 Sep 29 3:00
 			2:00	E-Eur	EE%sT	1995
 			2:00	EU	EE%sT
 # Ruthenia used CET 1990/1991.
--- a/jdk/make/data/tzdata/northamerica	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/data/tzdata/northamerica	Wed Jul 05 19:33:51 2017 +0200
@@ -414,9 +414,10 @@
 # US Pacific time, represented by Los Angeles
 #
 # California, northern Idaho (Benewah, Bonner, Boundary, Clearwater,
-# Idaho, Kootenai, Latah, Lewis, Nez Perce, and Shoshone counties,
-# and the northern three-quarters of Idaho county),
-# most of Nevada, most of Oregon, and Washington
+# Kootenai, Latah, Lewis, Nez Perce, and Shoshone counties, Idaho county
+# north of the Salmon River, and the towns of Burgdorf and Warren),
+# Nevada (except West Wendover), Oregon (except the northern 3/4 of
+# Malheur county), and Washington
 #
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
 Rule	CA	1948	only	-	Mar	14	2:00	1:00	D
--- a/jdk/make/data/tzdata/southamerica	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/data/tzdata/southamerica	Wed Jul 05 19:33:51 2017 +0200
@@ -1298,6 +1298,13 @@
 # start date is 2013-09-08 00:00....
 # http://www.gob.cl/informa/2013/02/15/gobierno-anuncia-fechas-de-cambio-de-hora-para-el-ano-2013.htm
 
+# From Jose Miguel Garrido (2014-02-19):
+# Today appeared in the Diario Oficial a decree amending the time change
+# dates to 2014.
+# DST End: last Saturday of April 2014 (Sun 27 Apr 2014 03:00 UTC)
+# DST Start: first Saturday of September 2014 (Sun 07 Sep 2014 04:00 UTC)
+# http://www.diariooficial.interior.gob.cl//media/2014/02/19/do-20140219.pdf
+
 # NOTE: ChileAQ rules for Antarctic bases are stored separately in the
 # 'antarctica' file.
 
@@ -1631,6 +1638,9 @@
 # From Carlos Raul Perasso (2013-03-15):
 # The change in Paraguay is now final.  Decree number 10780
 # http://www.presidencia.gov.py/uploads/pdf/presidencia-3b86ff4b691c79d4f5927ca964922ec74772ce857c02ca054a52a37b49afc7fb.pdf
+# From Carlos Raul Perasso (2014-02-28):
+# Decree 1264 can be found at:
+# http://www.presidencia.gov.py/archivos/documentos/DECRETO1264_ey9r8zai.pdf
 Rule	Para	2013	max	-	Mar	Sun>=22	0:00	0	-
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
@@ -1689,18 +1699,19 @@
 Zone America/Port_of_Spain -4:06:04 -	LMT	1912 Mar 2
 			-4:00	-	AST
 
+# These all agree with Trinidad and Tobago since 1970.
 Link America/Port_of_Spain America/Anguilla
 Link America/Port_of_Spain America/Dominica
 Link America/Port_of_Spain America/Grenada
 Link America/Port_of_Spain America/Guadeloupe
-Link America/Port_of_Spain America/Marigot
+Link America/Port_of_Spain America/Marigot	# St Martin (French part)
 Link America/Port_of_Spain America/Montserrat
 Link America/Port_of_Spain America/St_Barthelemy
-Link America/Port_of_Spain America/St_Kitts
+Link America/Port_of_Spain America/St_Kitts	# St Kitts & Nevis
 Link America/Port_of_Spain America/St_Lucia
-Link America/Port_of_Spain America/St_Thomas
+Link America/Port_of_Spain America/St_Thomas	# Virgin Islands (US)
 Link America/Port_of_Spain America/St_Vincent
-Link America/Port_of_Spain America/Tortola
+Link America/Port_of_Spain America/Tortola	# Virgin Islands (UK)
 
 # Uruguay
 # From Paul Eggert (1993-11-18):
--- a/jdk/make/gensrc/GensrcProperties.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/gensrc/GensrcProperties.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -23,8 +23,10 @@
 # questions.
 #
 
-# Prepare the find cache. This is only used on windows.
-$(eval $(call FillCacheFind, $(JDK_TOPDIR)/src/share/classes $(JDK_TOPDIR)/src/windows/classes))
+# Prepare the find cache.
+$(eval $(call FillCacheFind, $(JDK_TOPDIR)/src/share/classes \
+    $(JDK_TOPDIR)/src/windows/classes \
+    $(JDK_TOPDIR)/src/macosx/classes))
 
 # All .properties files to be compiled are appended to this variable.
 ALL_COMPILED_PROPSOURCES :=
@@ -33,19 +35,10 @@
 # The (very long) command line for compilation, stored in a file, prior to use.
 COMPILE_PROPCMDLINE :=
 
-# All .properties files to be cleaned are appended to this variable.
-ALL_CLEANED_PROPSOURCES :=
-# All generated cleaned .properties files from cleaning are appended to this variable.
-ALL_CLEANED_PROPOUTPUT :=
-# The (very long) command line for cleaning, stored in a file, prior to use.
-CLEAN_PROPCMDLINE :=
-
 define add_properties_to_compile
   # $1 is the name of the properties group
   # $2 is the files belonging to this group
   # $3 is the super class for the generated java file.
-  # $4 is a from pattern for translating stripped name from source to target
-  # $5 is the to pattern replacing $3 in the target
 
   # Strip away prefix and suffix,
   # leaving for example: sun/util/resources/CurrencyNames_sv
@@ -53,16 +46,14 @@
       $$(patsubst $(JDK_TOPDIR)/src/macosx/classes/%.properties, %, \
       $$(patsubst $(JDK_TOPDIR)/src/share/classes/%.properties, %, $2)))
 
-  # Apply optional name transformation, example: hz_TW -> hz_HK
-  $(if $4, $1_PROPPATHS := $$(patsubst $4, $5, $$($1_PROPPATHS)))
-
   # Accumulate all found properties files.
   ALL_COMPILED_PROPSOURCES += $2
 
   # Generate the list of to be created java files.
   ALL_COMPILED_PROPJAVAS += $$(patsubst %, $(JDK_OUTPUTDIR)/gensrc/%.java, $$($1_PROPPATHS))
 
-  # Now generate a sequence of "-compile ...CurrencyNames_sv.properties ...CurrencyNames_sv.java ListResourceBundle"
+  # Now generate a sequence of 
+  # "-compile ...CurrencyNames_sv.properties ...CurrencyNames_sv.java ListResourceBundle"
   # suitable to be fed into the CompileProperties command.
   COMPILE_PROPCMDLINE += $$(subst _SPACE_,$(SPACE),$$(join $$(addprefix -compile_SPACE_, $2), \
       $$(addsuffix _SPACE_$(strip $3), \
@@ -70,290 +61,55 @@
       $$(addsuffix .java, $$($1_PROPPATHS))))))
 endef
 
-define add_properties_to_clean
-  # $1 is the name of the properties group
-  # $2 is the files belonging to this group
-  # $3 is a from pattern for translating stripped name from source to target
-  # $4 is the to pattern replacing $3 in the target
-  # $5 optional name of extra directory to put properties files in (ex: resources)
-
-  # Strip away prefix and suffix,
-  # leaving for example: sun/util/resources/CurrencyNames_sv
-  $1_PROPPATHS := $$(patsubst $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/classes/%.properties, %, \
-      $$(patsubst $(JDK_TOPDIR)/src/share/classes/%.properties, %, $2))
-
-  # Apply optional name transformation, example: hz_TW -> hz_HK
-  $(if $3, $1_PROPPATHS := $$(patsubst $3, $4, $$($1_PROPPATHS)))
-
-  # Accumulate all found properties files.
-  ALL_CLEANED_PROPSOURCES += $2
-
-  # Generate the list of to be created java files.
-  $1_PROPOUTPUT := $$(patsubst %, $(JDK_OUTPUTDIR)/classes/%.properties, $$($1_PROPPATHS))
-  # If the properties target file isn't in a "resources" dir, add one.
-  ifneq ($5, )
-    $1_PROPOUTPUT := $$(foreach p, $$($1_PROPOUTPUT), $$(dir $$p)$5/$$(notdir $$p))
-  endif
-
-  ALL_CLEANED_PROPOUTPUT += $$($1_PROPOUTPUT)
+################################################################################
+# Some packages have properties that need to be converted to java source files.
+COMPILE_PROP_SRC_FILES := \
+    $(filter %.properties, $(call CacheFind, \
+        $(JDK_TOPDIR)/src/share/classes/com/sun/accessibility/internal/resources \
+        $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/motif/resources \
+        $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/windows/resources \
+        $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/basic/resources \
+        $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/metal/resources \
+        $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/synth/resources \
+        $(JDK_TOPDIR)/src/share/classes/com/sun/tools/jdi/resources \
+        $(JDK_TOPDIR)/src/share/classes/sun/awt/resources \
+        $(JDK_TOPDIR)/src/share/classes/sun/launcher/resources \
+        $(JDK_TOPDIR)/src/share/classes/sun/management/resources \
+        $(JDK_TOPDIR)/src/share/classes/sun/print/resources \
+        $(JDK_TOPDIR)/src/share/classes/sun/tools/jar/resources \
+        $(JDK_TOPDIR)/src/share/classes/sun/util/logging/resources)) \
+    #
 
-  # Now generate a sequence of "-clean ...[src]...CurrencyNames_sv.properties ...[build]...CurrencyNames_sv.properties"
-  # suitable to be fed into the StripProperties command.
-  CLEAN_PROPCMDLINE += $$(subst _SPACE_,$(SPACE),$$(join $$(addprefix -clean_SPACE_,$2), \
-      $$(addprefix _SPACE_, $$($1_PROPOUTPUT))))
-endef
-
-# Some packages contain pregenerated java files instead of properties files.
-# But unfortunately not all properties should be converted, some should be
-# copied....argggghhh.
-
-# For example:
-#    sun/applet/resources
-#    sun/misc/resources
-#    sun/text/resources
-#    sun/tools/jconsole/resources
-#    sun/tools/native2ascii/resources
-#    sun/util/resources
-
-# Some packages have properties that need to be converted to java source files.
-
-#com/apple/laf/resources
 ifeq ($(OPENJDK_TARGET_OS), macosx)
-  $(eval $(call add_properties_to_compile,COM_APPLE_LAF, \
-      $(filter %.properties, \
-      $(call CacheFind, $(JDK_TOPDIR)/src/macosx/classes/com/apple/laf/resources)), \
-      ListResourceBundle))
+  COMPILE_PROP_SRC_FILES += \
+      $(filter %.properties, $(call CacheFind, \
+          $(JDK_TOPDIR)/src/macosx/classes/com/apple/laf/resources \
+          $(JDK_TOPDIR)/src/macosx/classes/sun/awt/resources)) \
+      #
 endif
 
-#com/sun/accessibility/internal/resources
-$(eval $(call add_properties_to_compile,COM_SUN_ACCESSIBILITY, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/accessibility/internal/resources)), \
-    ListResourceBundle))
-$(eval $(call add_properties_to_compile,COM_SUN_ACCESSIBILITY_HK, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/accessibility/internal/resources)), \
-    ListResourceBundle, %zh_TW, %zh_HK))
-#com/sun/imageio/plugins/common
-$(eval $(call add_properties_to_clean,COM_SUN_IMAGEIO, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/imageio))))
-#com/sun/java/swing/plaf/gtk/resources
-ifneq ($(OPENJDK_TARGET_OS), windows)
-  # Only compile GTK resource bundles on Solaris/Linux
-  $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_GTK, \
-      $(filter %.properties, \
-      $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/gtk/resources)), \
-      ListResourceBundle))
-  $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_GTK_HK, \
-      $(filter %.properties, \
-      $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/gtk/resources)), \
-      ListResourceBundle, %zh_TW, %zh_HK))
-endif
-#com/sun/java/swing/plaf/motif/resources
-$(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_MOTIF, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/motif/resources)), \
-    ListResourceBundle))
-$(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_MOTIF_HK, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/motif/resources)), \
-    ListResourceBundle, %zh_TW, %zh_HK))
-#com/sun/java/swing/plaf/windows/resources
-$(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_WINDOWS, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/windows/resources)), \
-    ListResourceBundle))
-$(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_WINDOWS_HK, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/windows/resources)), \
-    ListResourceBundle, %zh_TW, %zh_HK))
-#com/sun/java/util/jar/pack
-$(eval $(call add_properties_to_clean,JNDI_COSNAMING, \
-    $(JDK_TOPDIR)/src/share/classes/com/sun/java/util/jar/pack/intrinsic.properties))
-#com/sun/jndi/cosnaming
-$(eval $(call add_properties_to_clean,JNDI_COSNAMING, \
-    $(JDK_TOPDIR)/src/share/classes/com/sun/jndi/cosnaming/jndiprovider.properties))
-#com/sun/jndi/ldap
-$(eval $(call add_properties_to_clean,JNDI_COSNAMING, \
-    $(JDK_TOPDIR)/src/share/classes/com/sun/jndi/ldap/jndiprovider.properties))
-
-#com/sun/org/apache/xml/internal/security/resource
-#FIXME: The "xmlsecurity*.properties" pattern is not ideal; we might want to find
-#a better way to select the properties files that are needed.
-$(eval $(call add_properties_to_clean,XML_SECURITY, \
-    $(filter $(JDK_TOPDIR)/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity%.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/org/apache/xml/internal/security/resource))))
-
-#com/sun/rowset
-$(eval $(call add_properties_to_clean,COM_SUN_ROWSET, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/rowset))))
-$(eval $(call add_properties_to_clean,COM_SUN_ROWSET_HK, \
-    $(filter %zh_TW.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/rowset)), \
-    %zh_TW, %zh_HK))
-
-#com/sun/swing/internal/plaf/basic/resources
-$(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_BASIC, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/basic/resources)), \
-    ListResourceBundle))
-$(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_BASIC_HK, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/basic/resources)), \
-    ListResourceBundle, %zh_TW, %zh_HK))
-#com/sun/swing/internal/plaf/metal/resources
-$(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_METAL, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/metal/resources)), \
-    ListResourceBundle))
-$(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_METAL_HK, \
-    $(filter %.properties, $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/metal/resources)), \
-    ListResourceBundle, %zh_TW, %zh_HK))
-#com/sun/swing/internal/plaf/synth/resources
-$(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_SYNTH, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/synth/resources)), \
-    ListResourceBundle))
-$(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_SYNTH_HK, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/synth/resources)), \
-    ListResourceBundle, %zh_TW, %zh_HK))
-
-#com/sun/tools/jdi/resources
-$(eval $(call add_properties_to_compile,COM_SUN_TOOLS_JDI, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/com/sun/tools/jdi/resources)), \
-    ListResourceBundle))
-
-#com/sun/tools/script/shell
-#java/util
-#javax/sql/rowset
-$(eval $(call add_properties_to_clean,JAVAX_SQL_ROWSET, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/javax/sql/rowset))))
-#sun/awt/resources
-$(eval $(call add_properties_to_compile,SUN_AWT, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/awt/resources)), \
-    ListResourceBundle))
-$(eval $(call add_properties_to_compile,SUN_AWT_HK, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/awt/resources)), \
-    ListResourceBundle, %zh_TW, %zh_HK))
-#sun/awt/windows/
 ifeq ($(OPENJDK_TARGET_OS), windows)
-  $(eval $(call add_properties_to_compile,SUN_AWT, \
-      $(filter $(JDK_TOPDIR)/src/windows/classes/sun/awt/windows/awtLocalization%.properties, \
-      $(call CacheFind, $(JDK_TOPDIR)/src/windows/classes/sun/awt/windows)), \
-      ListResourceBundle))
-  $(eval $(call add_properties_to_compile,SUN_AWT_HK, \
-      $(filter $(JDK_TOPDIR)/src/windows/classes/sun/awt/windows/awtLocalization%.properties, \
-      $(call CacheFind, $(JDK_TOPDIR)/src/windows/classes/sun/awt/windows)), \
-      ListResourceBundle, %zh_TW, %zh_HK))
-endif
-# os x specific awt properties
-ifeq ($(OPENJDK_TARGET_OS),macosx)
-$(eval $(call add_properties_to_compile,SUN_AWT,\
-	$(filter $(JDK_TOPDIR)/src/macosx/classes/sun/awt/resources/%.properties,\
-	$(call CacheFind,$(JDK_TOPDIR)/src/macosx/classes/sun/awt/resources)),\
-	ListResourceBundle))
+  COMPILE_PROP_SRC_FILES += \
+      $(filter %.properties, $(call CacheFind, \
+          $(JDK_TOPDIR)/src/windows/classes/sun/awt/windows)) \
+      #
+else # ! windows
+  COMPILE_PROP_SRC_FILES += \
+      $(filter %.properties, $(call CacheFind, \
+          $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/gtk/resources)) \
+      #
 endif
 
-#sun/launcher/resources
-$(eval $(call add_properties_to_compile,SUN_LAUNCHER, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/launcher/resources)), \
-    ListResourceBundle))
-$(eval $(call add_properties_to_compile,SUN_LAUNCHER_HK, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/launcher/resources)), \
-    ListResourceBundle, %zh_TW, %zh_HK))
-#sun/management/resources
-$(eval $(call add_properties_to_compile,SUN_MANAGEMENT, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/management/resources)), \
-    ListResourceBundle))
-$(eval $(call add_properties_to_compile,SUN_MANAGEMENT_KH, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/management/resources)), \
-    ListResourceBundle, %zh_TW, %zh_HK))
-#sun/print
-#sun/print/resources
-$(eval $(call add_properties_to_compile,SUN_PRINT, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/print/resources)), \
-    ListResourceBundle))
-$(eval $(call add_properties_to_compile,SUN_PRINT_HK, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/print/resources)), \
-    ListResourceBundle, %zh_TW, %zh_HK))
-#sun/rmi/registry/resources
-$(eval $(call add_properties_to_clean,SUN_RMI_REGISTRY, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/rmi/registry/resources))))
-$(eval $(call add_properties_to_clean,SUN_RMI_REGISTRY_HK, \
-    $(filter %zh_TW.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/rmi/registry/resources)), \
-    %zh_TW, %zh_HK))
-
-#sun/rmi/rmic/resources
-$(eval $(call add_properties_to_clean,SUN_RMI_RMIC, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/rmi/rmic/resources))))
+$(eval $(call add_properties_to_compile,LIST_RESOURCE_BUNDLE, \
+    $(COMPILE_PROP_SRC_FILES), ListResourceBundle))
 
-#sun/rmi/server/resources
-$(eval $(call add_properties_to_clean,SUN_RMI_SERVER, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/rmi/server/resources))))
-$(eval $(call add_properties_to_clean,SUN_RMI_SERVER_HK, \
-    $(filter %zh_TW.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/rmi/server/resources)), \
-    %zh_TW, %zh_HK))
-
-# sun/tools/jar/resources
-$(eval $(call add_properties_to_compile,SUN_TOOLS_JAR, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/tools/jar/resources)), \
-    ListResourceBundle))
-$(eval $(call add_properties_to_compile,SUN_TOOLS_JAR_HK, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/tools/jar/resources)), \
-    ListResourceBundle, %zh_TW, %zh_HK))
-
-#sun/tools/javac/resources
-# It's unclear if the other localized property files here are supposed to be copied or not
-# but the old build system didn't copy them.
-$(eval $(call add_properties_to_clean,SUN_TOOLS_SERIALVER, \
-    $(filter %javac.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/tools/javac/resources))))
-
-#sun/tools/jconsole/resources
-$(eval $(call add_properties_to_clean,SUN_TOOLS_JCONSOLE, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/tools/jconsole/resources))))
-
-#sun/tools/serialver
-$(eval $(call add_properties_to_clean,SUN_TOOLS_SERIALVER, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/tools/serialver)), , ,resources))
-
-#sun/util/logging/resources
-$(eval $(call add_properties_to_compile,SUN_UTIL_LOGGING, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/util/logging/resources)), \
-    ListResourceBundle))
-$(eval $(call add_properties_to_compile,SUN_UTIL_LOGGING_HK, \
-    $(filter %.properties, \
-    $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/util/logging/resources)), \
-    ListResourceBundle, %zh_TW, %zh_HK))
 # sun/util/resources
 $(eval $(call add_properties_to_compile,SUN_UTIL, \
     $(filter %.properties, \
     $(call CacheFind, $(JDK_TOPDIR)/src/share/classes/sun/util/resources)), \
     sun.util.resources.LocaleNamesBundle))
 
+################################################################################
 # Now setup the rule for the generation of the resource bundles.
 $(JDK_OUTPUTDIR)/gensrc/_the.compiled_properties: $(ALL_COMPILED_PROPSOURCES) $(BUILD_TOOLS)
         # Generate all output directories in advance since the build tool does not do that...
@@ -363,33 +119,31 @@
 	$(TOOL_COMPILEPROPERTIES) -quiet @$(JDK_OUTPUTDIR)/gensrc/_the.cmdline
 	$(TOUCH) $@
 
-# Now setup the rule for the generation of the cleaned properties.
-# FIXME: We currently don't handle removed properties incrementally.
-$(JDK_OUTPUTDIR)/classes/_the.cleaned_properties: $(ALL_CLEANED_PROPSOURCES) $(BUILD_TOOLS)
-	$(RM) $(JDK_OUTPUTDIR)/classes/_the.cleaned_properties.cmdline
-        # Generate all output directories in advance since the build tool does not do that...
-	$(MKDIR) -p $(sort $(dir $(ALL_CLEANED_PROPOUTPUT)))
-	$(ECHO) Copying and cleaning $(words $(ALL_CLEANED_PROPSOURCES)) properties
-	$(call ListPathsSafely,CLEAN_PROPCMDLINE,\n, >> $(JDK_OUTPUTDIR)/classes/_the.cleaned_properties.cmdline)
-	$(TOOL_STRIPPROPERTIES) @$(JDK_OUTPUTDIR)/classes/_the.cleaned_properties.cmdline
-	$(TOUCH) $@
-
 $(ALL_COMPILED_PROPJAVAS): $(JDK_OUTPUTDIR)/gensrc/_the.compiled_properties
 
-$(ALL_CLEANED_PROPOUTPUT): $(JDK_OUTPUTDIR)/classes/_the.cleaned_properties
-
+################################################################################
+# Some zh_HK resources are just copies of zh_TW
 
-# Some zh_HK resources are just copied of zh_TW
+define convert_tw_to_hk
+  $(MKDIR) -p $(@D)
+  $(CAT) $< | $(SED) -e '/class/s/_zh_TW/_zh_HK/' > $@
+endef
+
 $(JDK_OUTPUTDIR)/gensrc/%_zh_HK.java: $(JDK_TOPDIR)/src/share/classes/%_zh_TW.java
-	$(MKDIR) -p $(@D)
-	$(CAT) $< | $(SED) -e '/class/s/_zh_TW/_zh_HK/' > $@
+	$(call convert_tw_to_hk)
+
+$(JDK_OUTPUTDIR)/gensrc/%_zh_HK.java: $(JDK_OUTPUTDIR)/gensrc/%_zh_TW.java
+	$(call convert_tw_to_hk)
 
 ZH_HK_JAVA := sun/applet/resources/MsgAppletViewer_zh_HK.java \
     sun/misc/resources/Messages_zh_HK.java \
     sun/security/util/AuthResources_zh_HK.java \
     sun/security/util/Resources_zh_HK.java
 
-ZH_HK_JAVA_FILES := $(addprefix $(JDK_OUTPUTDIR)/gensrc/, $(ZH_HK_JAVA))
+ZH_HK_JAVA_FILES := $(addprefix $(JDK_OUTPUTDIR)/gensrc/, $(ZH_HK_JAVA)) \
+    $(filter-out $(JDK_OUTPUTDIR)/gensrc/sun/util/resources/zh/%, \
+    $(subst _zh_TW,_zh_HK,$(filter %_zh_TW.java, $(ALL_COMPILED_PROPJAVAS))))
 
+################################################################################
 
-GENSRC_PROPERTIES := $(ALL_COMPILED_PROPJAVAS) $(ALL_CLEANED_PROPOUTPUT) $(ZH_HK_JAVA_FILES)
+GENSRC_PROPERTIES := $(ALL_COMPILED_PROPJAVAS) $(ZH_HK_JAVA_FILES)
--- a/jdk/make/lib/Awt2dLibraries.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/lib/Awt2dLibraries.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -1196,7 +1196,6 @@
 ifndef BUILD_HEADLESS_ONLY
   LIBSPLASHSCREEN_DIRS := \
     $(JDK_TOPDIR)/src/share/native/sun/awt/image/jpeg \
-    $(JDK_TOPDIR)/src/share/native/sun/awt/libpng \
     $(JDK_TOPDIR)/src/share/native/sun/awt/splashscreen
 
   ifeq ($(USE_EXTERNAL_LIBGIF), true)
@@ -1206,6 +1205,11 @@
     GIFLIB_CFLAGS := -I$(JDK_TOPDIR)/src/share/native/sun/awt/giflib
   endif
 
+  ifeq ($(USE_EXTERNAL_LIBPNG), false)
+    LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/share/native/sun/awt/libpng
+    LIBPNG_CFLAGS := -I$(JDK_TOPDIR)/src/share/native/sun/awt/libpng
+  endif
+
   ifneq ($(OPENJDK_TARGET_OS), macosx)
     LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/sun/awt/splashscreen
   else
@@ -1268,11 +1272,13 @@
       EXCLUDE_FILES := imageioJPEG.c jpegdecoder.c pngtest.c, \
       LANG := C, \
       OPTIMIZATION := LOW, \
-      CFLAGS := $(LIBSPLASHSCREEN_CFLAGS) $(CFLAGS_JDKLIB) $(GIFLIB_CFLAGS), \
+      CFLAGS := $(LIBSPLASHSCREEN_CFLAGS) $(CFLAGS_JDKLIB) \
+                $(GIFLIB_CFLAGS) $(PNG_CFLAGS), \
       MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libsplashscreen/mapfile-vers, \
       LDFLAGS := $(LDFLAGS_JDKLIB) \
           $(call SET_SHARED_LIBRARY_ORIGIN), \
-      LDFLAGS_SUFFIX := $(LIBSPLASHSCREEN_LDFLAGS_SUFFIX) $(LIBZ) $(GIFLIB_LDFLAGS), \
+      LDFLAGS_SUFFIX := $(LIBSPLASHSCREEN_LDFLAGS_SUFFIX) $(LIBZ) \
+                        $(GIFLIB_LDFLAGS) $(PNG_LIBS), \
       LDFLAGS_SUFFIX_solaris := -lc, \
       VERSIONINFO_RESOURCE := $(JDK_TOPDIR)/src/windows/resource/version.rc, \
       RC_FLAGS := $(RC_FLAGS) \
@@ -1315,6 +1321,7 @@
       LDFLAGS := $(LDFLAGS_JDKLIB) \
           $(call SET_SHARED_LIBRARY_ORIGIN), \
       LDFLAGS_SUFFIX := $(LIBM) $(LDFLAGS_JDKLIB_SUFFIX), \
+      LDFLAGS_SUFFIX_windows := $(WIN_JAVA_LIB), \
       LDFLAGS_SUFFIX_posix := -lm, \
       VERSIONINFO_RESOURCE := $(JDK_TOPDIR)/src/windows/resource/version.rc, \
       RC_FLAGS := $(RC_FLAGS) \
--- a/jdk/make/lib/ServiceabilityLibraries.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/make/lib/ServiceabilityLibraries.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -203,7 +203,6 @@
 ##########################################################################################
 
 LIBINSTRUMENT_SRC := $(JDK_TOPDIR)/src/share/instrument \
-    $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/java/io \
     $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/instrument
 
 LIBINSTRUMENT_FILES := \
@@ -218,9 +217,8 @@
     JavaExceptions.c \
     PathCharsValidator.c \
     Reentrancy.c \
-    Utilities.c \
-    canonicalize_md.c
-
+    Utilities.c
+    
 LIBINSTRUMENT_DIR := $(JDK_OUTPUTDIR)/objs/libinstrument
 LIBINSTRUMENT_CFLAGS := $(CFLAGS_JDKLIB) \
     -I$(JDK_TOPDIR)/src/share/instrument \
@@ -239,6 +237,8 @@
   LIBINSTRUMENT_CFLAGS := $(filter-out -MD, $(LIBINSTRUMENT_CFLAGS))
   # equivalent of strcasecmp is stricmp on Windows
   LIBINSTRUMENT_CFLAGS += -Dstrcasecmp=stricmp
+else
+  LIBINSTRUMENT_LDFLAGS_SUFFIX := -ljava
 endif
 
 $(eval $(call SetupNativeCompilation,BUILD_LIBINSTRUMENT, \
--- a/jdk/make/src/classes/build/tools/stripproperties/StripProperties.java	Tue Mar 25 12:31:49 2014 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,288 +0,0 @@
-/*
- * 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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 build.tools.stripproperties;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedWriter;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-
-/**
- * Reads a properties file from standard input and writes an equivalent
- * properties file without comments to standard output.
- */
-public class StripProperties {
-
-    private static void error(String msg, Exception e) {
-        System.err.println("ERROR: stripproperties: " + msg);
-        if ( e != null ) {
-            System.err.println("EXCEPTION: " + e.toString());
-            e.printStackTrace();
-        }
-    }
-
-    private static List<String> infiles = new ArrayList<String>();
-    private static List<String> outfiles = new ArrayList<String>();
-
-    private static boolean parseOptions(String args[]) {
-        boolean ok = true;
-
-        for ( int i = 0; i < args.length ; i++ ) {
-            if ( "-clean".equals(args[i]) && i+2 < args.length ) {
-                infiles.add(args[++i]);
-                outfiles.add(args[++i]);
-            } else if ( args[i].charAt(0)=='@') {
-                String filename = args[i].substring(1);
-                FileInputStream finput = null;
-                byte contents[] = null;
-                try {
-                    finput = new FileInputStream(filename);
-                    int byteCount = finput.available();
-                    if ( byteCount <= 0 ) {
-                        error("The @file is empty", null);
-                        ok = false;
-                    } else {
-                        contents = new byte[byteCount];
-                        int bytesRead = finput.read(contents);
-                        if ( byteCount != bytesRead ) {
-                            error("Cannot read all of @file", null);
-                            ok = false;
-                        }
-                    }
-                } catch ( IOException e ) {
-                    error("cannot open " + filename, e);
-                    ok = false;
-                }
-                if ( finput != null ) {
-                    try {
-                        finput.close();
-                    } catch ( IOException e ) {
-                        ok = false;
-                        error("cannot close " + filename, e);
-                    }
-                }
-                if ( ok && contents != null ) {
-                    String tokens[] = (new String(contents)).split("\\s+");
-                    if ( tokens.length > 0 ) {
-                        ok = parseOptions(tokens);
-                    }
-                }
-                if ( !ok ) {
-                    break;
-                }
-            } else {
-                infiles.add(args[i]);
-                outfiles.add(args[i]);
-            }
-        }
-        return ok;
-    }
-
-    private static boolean stripFiles(List<String> infiles, List<String> outfiles) {
-        boolean ok = true;
-        Iterator<String> inIter  = infiles.iterator();
-        Iterator<String> outIter = outfiles.iterator();
-
-        for (; inIter.hasNext(); ) {
-            String infile = inIter.next();
-            String outfile = outIter.next();
-
-            Properties prop = new Properties();
-            InputStream in = null;
-            try {
-                in = new BufferedInputStream(new FileInputStream(infile));
-                prop.load(in);
-            } catch ( FileNotFoundException e ) {
-                error("Cannot access file " + infile, e);
-                ok = false;
-            } catch ( IOException e ) {
-                error("IO exception processing file " + infile, e);
-                ok = false;
-            }
-            if ( in != null ) {
-                try {
-                    in.close();
-                } catch ( IOException e ) {
-                    error("IO exception closing file " + infile, e);
-                    ok = false;
-                }
-            }
-            if ( !ok ) {
-                break;
-            }
-
-            OutputStream out = null;
-            try {
-                out = new FileOutputStream(outfile);
-                storeProperties(prop, out);
-                out.flush();
-            } catch ( IOException e ) {
-                error("IO exception processing file " + outfile, e);
-                ok = false;
-            }
-            if ( out != null ) {
-                try {
-                    out.close();
-                } catch ( IOException e ) {
-                    error("IO exception closing file " + outfile, e);
-                    ok = false;
-                }
-            }
-            if ( !ok ) {
-                break;
-            }
-
-        }
-        return ok;
-    }
-
-    /**
-     * Strip the properties filenames supplied, replacing their contents.
-     * @param args Names of properties files to process and replace contents
-     */
-    public static void main(String args[]) {
-        boolean ok = parseOptions(args);
-        if ( !ok || !stripFiles(infiles, outfiles) ) {
-            System.exit(1);
-        }
-    }
-
-    // --- code below here is adapted from java.util.Properties ---
-
-    private static final String specialSaveChars = "=: \t\r\n\f#!";
-
-    /*
-     * Converts unicodes to encoded &#92;uxxxx
-     * and writes out any of the characters in specialSaveChars
-     * with a preceding slash
-     */
-    private static String saveConvert(String theString, boolean escapeSpace) {
-        int len = theString.length();
-        StringBuffer outBuffer = new StringBuffer(len*2);
-
-        for(int x=0; x<len; x++) {
-            char aChar = theString.charAt(x);
-            switch(aChar) {
-                case ' ':
-                    if (x == 0 || escapeSpace) {
-                        outBuffer.append('\\');
-                    }
-                    outBuffer.append(' ');
-                    break;
-                case '\\':
-                    outBuffer.append('\\');
-                    outBuffer.append('\\');
-                    break;
-                case '\t':
-                    outBuffer.append('\\');
-                    outBuffer.append('t');
-                    break;
-                case '\n':
-                    outBuffer.append('\\');
-                    outBuffer.append('n');
-                    break;
-                case '\r':
-                    outBuffer.append('\\');
-                    outBuffer.append('r');
-                    break;
-                case '\f':
-                    outBuffer.append('\\');
-                    outBuffer.append('f');
-                    break;
-                default:
-                    if ((aChar < 0x0020) || (aChar == 0x007e) || (aChar > 0x00ff)) {
-                        outBuffer.append('\\');
-                        outBuffer.append('u');
-                        outBuffer.append(toHex((aChar >> 12) & 0xF));
-                        outBuffer.append(toHex((aChar >>  8) & 0xF));
-                        outBuffer.append(toHex((aChar >>  4) & 0xF));
-                        outBuffer.append(toHex( aChar        & 0xF));
-                    } else {
-                        if (specialSaveChars.indexOf(aChar) != -1) {
-                            outBuffer.append('\\');
-                        }
-                        outBuffer.append(aChar);
-                    }
-            }
-        }
-        return outBuffer.toString();
-    }
-
-    /**
-     * Writes the content of <code>properties</code> to <code>out</code>.
-     * The format is that of Properties.store with the following modifications:
-     * <ul>
-     * <li>No header or date is written
-     * <li>Latin-1 characters are written as single bytes, not escape sequences
-     * <li>Line breaks are indicated by a single \n independent of platform
-     * <ul>
-     */
-    private static void storeProperties(Properties properties, OutputStream out)
-    throws IOException {
-        BufferedWriter awriter;
-        awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
-        for (Enumeration<Object> e = properties.keys(); e.hasMoreElements();) {
-            String key = (String)e.nextElement();
-            String val = (String)properties.get(key);
-            key = saveConvert(key, true);
-
-            /* No need to escape embedded and trailing spaces for value, hence
-             * pass false to flag.
-             */
-            val = saveConvert(val, false);
-            writeln(awriter, key + "=" + val);
-        }
-        awriter.flush();
-    }
-
-    private static void writeln(BufferedWriter bw, String s) throws IOException {
-        bw.write(s);
-        bw.write("\n");
-    }
-
-    /**
-     * Convert a nibble to a hex character
-     * @param   nibble  the nibble to convert.
-     */
-    private static char toHex(int nibble) {
-        return hexDigit[(nibble & 0xF)];
-    }
-
-    /** A table of hex digits */
-    private static final char[] hexDigit = {
-        '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
-    };
-}
--- a/jdk/src/macosx/classes/apple/laf/JRSUIUtils.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/apple/laf/JRSUIUtils.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,9 @@
 import com.apple.laf.AquaImageFactory.NineSliceMetrics;
 
 import apple.laf.JRSUIConstants.*;
+import sun.security.action.GetPropertyAction;
+
+import java.security.AccessController;
 
 public class JRSUIUtils {
     static boolean isLeopard = isMacOSXLeopard();
@@ -47,7 +50,7 @@
 
     static boolean currentMacOSXVersionMatchesGivenVersionRange(final int version, final boolean inclusive, final boolean matchBelow, final boolean matchAbove) {
         // split the "10.x.y" version number
-        String osVersion = System.getProperty("os.version");
+        String osVersion = AccessController.doPrivileged(new GetPropertyAction("os.version"));
         String[] fragments = osVersion.split("\\.");
 
         // sanity check the "10." part of the version
--- a/jdk/src/macosx/classes/com/apple/laf/AquaFileChooserUI.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/com/apple/laf/AquaFileChooserUI.java	Wed Jul 05 19:33:51 2017 +0200
@@ -42,7 +42,6 @@
 import javax.swing.plaf.*;
 import javax.swing.table.*;
 
-import sun.swing.AbstractFilterComboBoxModel;
 import sun.swing.SwingUtilities2;
 
 public class AquaFileChooserUI extends FileChooserUI {
@@ -1267,9 +1266,70 @@
     /**
      * Data model for a type-face selection combo-box.
      */
-    protected class FilterComboBoxModel extends AbstractFilterComboBoxModel {
-        protected JFileChooser getFileChooser() {
-            return AquaFileChooserUI.this.getFileChooser();
+    protected class FilterComboBoxModel extends AbstractListModel<FileFilter> implements ComboBoxModel<FileFilter>,
+            PropertyChangeListener {
+        protected FileFilter[] filters;
+        protected FilterComboBoxModel() {
+            super();
+            filters = getFileChooser().getChoosableFileFilters();
+        }
+
+        public void propertyChange(PropertyChangeEvent e) {
+            String prop = e.getPropertyName();
+            if(prop == JFileChooser.CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY) {
+                filters = (FileFilter[]) e.getNewValue();
+                fireContentsChanged(this, -1, -1);
+            } else if (prop == JFileChooser.FILE_FILTER_CHANGED_PROPERTY) {
+                fireContentsChanged(this, -1, -1);
+            }
+        }
+
+        public void setSelectedItem(Object filter) {
+            if(filter != null) {
+                getFileChooser().setFileFilter((FileFilter) filter);
+                fireContentsChanged(this, -1, -1);
+            }
+        }
+
+        public Object getSelectedItem() {
+            // Ensure that the current filter is in the list.
+            // NOTE: we shouldnt' have to do this, since JFileChooser adds
+            // the filter to the choosable filters list when the filter
+            // is set. Lets be paranoid just in case someone overrides
+            // setFileFilter in JFileChooser.
+            FileFilter currentFilter = getFileChooser().getFileFilter();
+            boolean found = false;
+            if(currentFilter != null) {
+                for (FileFilter filter : filters) {
+                    if (filter == currentFilter) {
+                        found = true;
+                    }
+                }
+                if(found == false) {
+                    getFileChooser().addChoosableFileFilter(currentFilter);
+                }
+            }
+            return getFileChooser().getFileFilter();
+        }
+
+        public int getSize() {
+            if(filters != null) {
+                return filters.length;
+            } else {
+                return 0;
+            }
+        }
+
+        public FileFilter getElementAt(int index) {
+            if(index > getSize() - 1) {
+                // This shouldn't happen. Try to recover gracefully.
+                return getFileChooser().getFileFilter();
+            }
+            if(filters != null) {
+                return filters[index];
+            } else {
+                return null;
+            }
         }
     }
 
--- a/jdk/src/macosx/classes/com/apple/laf/AquaIcon.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/com/apple/laf/AquaIcon.java	Wed Jul 05 19:33:51 2017 +0200
@@ -295,7 +295,14 @@
         }
 
         Image createImage() {
-            return AquaUtils.getCImageCreator().createSystemImageFromSelector(selector, getIconWidth(), getIconHeight());
+            int w = getIconWidth();
+            int h = getIconHeight();
+            return new AquaImageFactory.MultiResolutionIconImage(
+                    AquaUtils.getCImageCreator().createSystemImageFromSelector(
+                            selector, w, h),
+                    AquaUtils.getCImageCreator().createSystemImageFromSelector(
+                            selector, 2 * w, 2 * h)
+            );
         }
     }
 }
--- a/jdk/src/macosx/classes/com/apple/laf/AquaImageFactory.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/com/apple/laf/AquaImageFactory.java	Wed Jul 05 19:33:51 2017 +0200
@@ -46,6 +46,10 @@
 import com.apple.laf.AquaIcon.SystemIcon;
 import com.apple.laf.AquaUtils.RecyclableObject;
 import com.apple.laf.AquaUtils.RecyclableSingleton;
+import java.util.Arrays;
+import java.util.List;
+import sun.awt.image.MultiResolutionBufferedImage;
+import sun.awt.image.MultiResolutionImage;
 
 public class AquaImageFactory {
     public static IconUIResource getConfirmImageIcon() {
@@ -120,28 +124,48 @@
 
     private static final int kAlertIconSize = 64;
     static IconUIResource getAppIconCompositedOn(final Image background) {
-        final double scaleFactor = 1.0; // revise for HiDPI
+
+        final BufferedImage iconImage = getAppIconImageCompositedOn(background, 1);
+
+        if (background instanceof MultiResolutionIconImage) {
+            BufferedImage background2x
+                    = ((MultiResolutionIconImage) background).resolutionVariant;
+            BufferedImage icon2xImage = getAppIconImageCompositedOn(background2x, 2);
+
+            return new IconUIResource(new ImageIcon(
+                    new MultiResolutionIconImage(iconImage, icon2xImage)));
+        }
+        return new IconUIResource(new ImageIcon(iconImage));
+    }
+
+    static BufferedImage getAppIconImageCompositedOn(final Image background, int scaleFactor) {
 
-        final int kAlertSubIconSize = (int)(kAlertIconSize * 0.5 * scaleFactor);
-        final int kAlertSubIconInset = (int)(kAlertIconSize * scaleFactor) - kAlertSubIconSize;
-        final Icon smallAppIconScaled = new AquaIcon.CachingScalingIcon(kAlertSubIconSize, kAlertSubIconSize) {
-            Image createImage() {
-                return getThisApplicationsIcon(kAlertSubIconSize, kAlertSubIconSize);
-            }
-        };
+        final int scaledAlertIconSize = kAlertIconSize * scaleFactor;
+        final int kAlertSubIconSize = (int) (scaledAlertIconSize * 0.5);
+        final int kAlertSubIconInset = scaledAlertIconSize - kAlertSubIconSize;
+        final Icon smallAppIconScaled = new AquaIcon.CachingScalingIcon(
+                kAlertSubIconSize, kAlertSubIconSize) {
+                    Image createImage() {
+                        return getThisApplicationsIcon(kAlertSubIconSize, kAlertSubIconSize);
+                    }
+                };
 
-        final BufferedImage image = new BufferedImage(kAlertIconSize, kAlertIconSize, BufferedImage.TYPE_INT_ARGB);
+        final BufferedImage image = new BufferedImage(scaledAlertIconSize,
+                scaledAlertIconSize, BufferedImage.TYPE_INT_ARGB);
         final Graphics g = image.getGraphics();
-        g.drawImage(background, 0, 0, (int)(kAlertIconSize * scaleFactor), (int)(kAlertIconSize * scaleFactor), null);
+        g.drawImage(background, 0, 0,
+                scaledAlertIconSize, scaledAlertIconSize, null);
         if (g instanceof Graphics2D) {
             // improves icon rendering quality in Quartz
-            ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
+            ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_RENDERING,
+                    RenderingHints.VALUE_RENDER_QUALITY);
         }
 
-        smallAppIconScaled.paintIcon(null, g, kAlertSubIconInset, kAlertSubIconInset);
+        smallAppIconScaled.paintIcon(null, g,
+                kAlertSubIconInset, kAlertSubIconInset);
         g.dispose();
 
-        return new IconUIResource(new ImageIcon(image));
+        return image;
     }
 
     public static IconUIResource getTreeFolderIcon() {
@@ -207,7 +231,7 @@
 
         @Override
         protected Image getInstance() {
-            return Toolkit.getDefaultToolkit().getImage("NSImage://" + namedImage);
+            return getNSIcon(namedImage);
         }
     }
 
@@ -271,11 +295,27 @@
     }
 
     public static Icon getMenuItemCheckIcon() {
-        return new InvertableImageIcon(AquaUtils.generateLightenedImage(Toolkit.getDefaultToolkit().getImage("NSImage://NSMenuItemSelection"), 25));
+        return new InvertableImageIcon(AquaUtils.generateLightenedImage(
+                getNSIcon("NSMenuItemSelection"), 25));
     }
 
     public static Icon getMenuItemDashIcon() {
-        return new InvertableImageIcon(AquaUtils.generateLightenedImage(Toolkit.getDefaultToolkit().getImage("NSImage://NSMenuMixedState"), 25));
+        return new InvertableImageIcon(AquaUtils.generateLightenedImage(
+                getNSIcon("NSMenuMixedState"), 25));
+    }
+
+    private static Image getNSIcon(String imageName) {
+        Image icon = Toolkit.getDefaultToolkit()
+                .getImage("NSImage://" + imageName);
+
+        if (icon instanceof MultiResolutionImage) {
+            return icon;
+        }
+
+        Image icon2x = AquaUtils.getCImageCreator().createImageFromName(
+                imageName, 2 * icon.getWidth(null), 2 * icon.getHeight(null));
+        return new MultiResolutionBufferedImage(
+                BufferedImage.TYPE_INT_ARGB_PRE, 0, icon, icon2x);
     }
 
     public static class NineSliceMetrics {
@@ -484,4 +524,29 @@
     public static Color getSelectionInactiveForegroundColorUIResource() {
         return new SystemColorProxy(LWCToolkit.getAppleColor(LWCToolkit.INACTIVE_SELECTION_FOREGROUND_COLOR));
     }
+
+    static class MultiResolutionIconImage extends BufferedImage
+            implements MultiResolutionImage {
+
+        BufferedImage resolutionVariant;
+
+        public MultiResolutionIconImage(BufferedImage image, BufferedImage resolutionVariant) {
+            super(image.getWidth(), image.getHeight(), image.getType());
+            this.resolutionVariant = resolutionVariant;
+            Graphics g = getGraphics();
+            g.drawImage(image, 0, 0, null);
+            g.dispose();
+        }
+
+        @Override
+        public Image getResolutionVariant(int width, int height) {
+            return ((width <= getWidth() && height <= getHeight()))
+                    ? this : resolutionVariant;
+        }
+
+        @Override
+        public List<Image> getResolutionVariants() {
+            return Arrays.asList(this, resolutionVariant);
+        }
+    }
 }
--- a/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java	Wed Jul 05 19:33:51 2017 +0200
@@ -48,6 +48,7 @@
 import sun.swing.SwingUtilities2;
 
 import com.apple.laf.AquaImageFactory.SlicedImageControl;
+import sun.awt.image.MultiResolutionBufferedImage;
 
 final class AquaUtils {
 
@@ -123,6 +124,13 @@
 
     static Image generateLightenedImage(final Image image, final int percent) {
         final GrayFilter filter = new GrayFilter(true, percent);
+        return (image instanceof MultiResolutionBufferedImage)
+                ? ((MultiResolutionBufferedImage) image).map(
+                        rv -> generateLightenedImage(rv, filter))
+                : generateLightenedImage(image, filter);
+    }
+
+    static Image generateLightenedImage(Image image, ImageFilter filter) {
         final ImageProducer prod = new FilteredImageSource(image.getSource(), filter);
         return Toolkit.getDefaultToolkit().createImage(prod);
     }
--- a/jdk/src/macosx/classes/sun/java2d/opengl/CGLGraphicsConfig.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/java2d/opengl/CGLGraphicsConfig.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,9 +30,6 @@
 import java.awt.Component;
 import java.awt.Graphics;
 import java.awt.Graphics2D;
-import java.awt.GraphicsConfiguration;
-import java.awt.GraphicsDevice;
-import java.awt.GraphicsEnvironment;
 import java.awt.Image;
 import java.awt.ImageCapabilities;
 import java.awt.Rectangle;
@@ -80,23 +77,34 @@
     private ContextCapabilities oglCaps;
     private OGLContext context;
     private final Object disposerReferent = new Object();
+    private final int maxTextureSize;
+
     private static native boolean initCGL();
     private static native long getCGLConfigInfo(int displayID, int visualnum,
                                                 int swapInterval);
     private static native int getOGLCapabilities(long configInfo);
 
+    /**
+     * Returns GL_MAX_TEXTURE_SIZE from the shared opengl context. Must be
+     * called under OGLRQ lock, because this method change current context.
+     *
+     * @return GL_MAX_TEXTURE_SIZE
+     */
+    private static native int nativeGetMaxTextureSize();
+
     static {
         cglAvailable = initCGL();
     }
 
     private CGLGraphicsConfig(CGraphicsDevice device, int pixfmt,
-                                long configInfo, ContextCapabilities oglCaps)
-    {
+                              long configInfo, int maxTextureSize,
+                              ContextCapabilities oglCaps) {
         super(device);
 
         this.pixfmt = pixfmt;
         this.pConfigInfo = configInfo;
         this.oglCaps = oglCaps;
+        this.maxTextureSize = maxTextureSize;
         context = new OGLContext(OGLRenderQueue.getInstance(), this);
 
         // add a record to the Disposer so that we destroy the native
@@ -126,6 +134,7 @@
         }
 
         long cfginfo = 0;
+        int textureSize = 0;
         final String ids[] = new String[1];
         OGLRenderQueue rq = OGLRenderQueue.getInstance();
         rq.lock();
@@ -138,11 +147,14 @@
             cfginfo = getCGLConfigInfo(device.getCGDisplayID(), pixfmt,
                                        kOpenGLSwapInterval);
             if (cfginfo != 0L) {
+                textureSize = nativeGetMaxTextureSize();
+                // 7160609: GL still fails to create a square texture of this
+                // size. Half should be safe enough.
+                // Explicitly not support a texture more than 2^14, see 8010999.
+                textureSize = textureSize <= 16384 ? textureSize / 2 : 8192;
                 OGLContext.setScratchSurface(cfginfo);
-                rq.flushAndInvokeNow(new Runnable() {
-                    public void run() {
-                        ids[0] = OGLContext.getOGLIdString();
-                    }
+                rq.flushAndInvokeNow(() -> {
+                    ids[0] = OGLContext.getOGLIdString();
                 });
             }
         } finally {
@@ -154,8 +166,7 @@
 
         int oglCaps = getOGLCapabilities(cfginfo);
         ContextCapabilities caps = new OGLContextCaps(oglCaps, ids[0]);
-
-        return new CGLGraphicsConfig(device, pixfmt, cfginfo, caps);
+        return new CGLGraphicsConfig(device, pixfmt, cfginfo, textureSize, caps);
     }
 
     public static boolean isCGLAvailable() {
@@ -246,8 +257,6 @@
         } finally {
             rq.unlock();
         }
-
-        updateTotalDisplayBounds();
     }
 
     @Override
@@ -421,57 +430,15 @@
         AccelDeviceEventNotifier.removeListener(l);
     }
 
-    private static final Rectangle totalDisplayBounds = new Rectangle();
-
-    private static void updateTotalDisplayBounds() {
-        synchronized (totalDisplayBounds) {
-            Rectangle virtualBounds = new Rectangle();
-            for (GraphicsDevice gd : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) {
-                for (GraphicsConfiguration gc : gd.getConfigurations()) {
-                    virtualBounds = virtualBounds.union(gc.getBounds());
-                }
-            }
-            totalDisplayBounds.setBounds(virtualBounds);
-        }
-    }
-
-    // 7160609: GL still fails to create a square texture of this size,
-    //          so we use this value to cap the total display bounds.
-    native private static int getMaxTextureSize();
-
     @Override
     public int getMaxTextureWidth() {
-        //Temporary disable this logic and use some magic constrain.
-        /*
-         int width;
-
-         synchronized (totalDisplayBounds) {
-         if (totalDisplayBounds.width == 0) {
-         updateTotalDisplayBounds();
-         }
-         width = totalDisplayBounds.width;
-         }
-
-         return Math.min(width, getMaxTextureSize());
-         */
-        return getMaxTextureSize() / (getDevice().getScaleFactor() * 2);
+        return Math.max(maxTextureSize / getDevice().getScaleFactor(),
+                        getBounds().width);
     }
 
     @Override
     public int getMaxTextureHeight() {
-        //Temporary disable this logic and use some magic constrain.
-        /*
-         int height;
-
-         synchronized (totalDisplayBounds) {
-         if (totalDisplayBounds.height == 0) {
-         updateTotalDisplayBounds();
-         }
-         height = totalDisplayBounds.height;
-         }
-
-         return Math.min(height, getMaxTextureSize());
-         */
-        return getMaxTextureSize() / (getDevice().getScaleFactor() * 2);
+        return Math.max(maxTextureSize / getDevice().getScaleFactor(),
+                        getBounds().height);
     }
 }
--- a/jdk/src/macosx/classes/sun/lwawt/LWChoicePeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/LWChoicePeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -168,16 +168,16 @@
         @Override
         public void firePopupMenuWillBecomeVisible() {
             super.firePopupMenuWillBecomeVisible();
-            SwingUtilities.invokeLater(new Runnable() {
-                @Override
-                public void run() {
-                    JPopupMenu popupMenu = getPopupMenu();
-                    if (popupMenu != null) {
-                        if (popupMenu.getInvoker() != LWChoicePeer.this.getTarget()) {
-                            popupMenu.setVisible(false);
-                            popupMenu.show(LWChoicePeer.this.getTarget(), 0, 0);
-                        }
-                    }
+            SwingUtilities.invokeLater(() -> {
+                JPopupMenu popupMenu = getPopupMenu();
+                // Need to override the invoker for proper grab handling
+                if (popupMenu != null && popupMenu.getInvoker() != getTarget()) {
+                    // The popup is now visible with correct location
+                    // Save it and restore after toggling visibility and changing invoker
+                    Point loc = popupMenu.getLocationOnScreen();
+                    SwingUtilities.convertPointFromScreen(loc, this);
+                    popupMenu.setVisible(false);
+                    popupMenu.show(getTarget(), loc.x, loc.y);
                 }
             });
         }
--- a/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,17 +28,16 @@
 import java.awt.*;
 import java.awt.List;
 import java.awt.datatransfer.*;
-import java.awt.dnd.*;
-import java.awt.dnd.peer.*;
 import java.awt.image.*;
 import java.awt.peer.*;
 import java.security.*;
 import java.util.*;
 
 import sun.awt.*;
-import sun.lwawt.macosx.*;
 import sun.print.*;
 
+import static sun.lwawt.LWWindowPeer.PeerType;
+
 public abstract class LWToolkit extends SunToolkit implements Runnable {
 
     private final static int STATE_NONE = 0;
@@ -114,7 +113,7 @@
     /*
      * Sends a request to stop the message pump.
      */
-    public void shutdown() {
+    public final void shutdown() {
         setRunState(STATE_SHUTDOWN);
         platformShutdown();
     }
@@ -145,7 +144,7 @@
         notifyAll();
     }
 
-    public boolean isTerminating() {
+    public final boolean isTerminating() {
         return getRunState() >= STATE_SHUTDOWN;
     }
 
@@ -162,7 +161,8 @@
         }
     }
 
-    public void run() {
+    @Override
+    public final void run() {
         setRunState(STATE_INIT);
         platformInit();
         AWTAutoShutdown.notifyToolkitThreadFree();
@@ -214,80 +214,51 @@
      * Note that LWWindowPeer implements WindowPeer, FramePeer
      * and DialogPeer interfaces.
      */
-    private LWWindowPeer createDelegatedPeer(Window target, PlatformComponent platformComponent,
-                                             PlatformWindow platformWindow, LWWindowPeer.PeerType peerType)
-    {
+    protected LWWindowPeer createDelegatedPeer(Window target,
+                                               PlatformComponent platformComponent,
+                                               PlatformWindow platformWindow,
+                                               PeerType peerType) {
         LWWindowPeer peer = new LWWindowPeer(target, platformComponent, platformWindow, peerType);
         targetCreatedPeer(target, peer);
         peer.initialize();
         return peer;
     }
 
-    private LWLightweightFramePeer createDelegatedLwPeer(LightweightFrame target,
-                                                         PlatformComponent platformComponent,
-                                                         PlatformWindow platformWindow)
-    {
-        LWLightweightFramePeer peer = new LWLightweightFramePeer(target, platformComponent, platformWindow);
+    @Override
+    public final FramePeer createLightweightFrame(LightweightFrame target) {
+        PlatformComponent platformComponent = createLwPlatformComponent();
+        PlatformWindow platformWindow = createPlatformWindow(PeerType.LW_FRAME);
+        LWLightweightFramePeer peer = new LWLightweightFramePeer(target,
+                                                                 platformComponent,
+                                                                 platformWindow);
         targetCreatedPeer(target, peer);
         peer.initialize();
         return peer;
     }
 
     @Override
-    public FramePeer createLightweightFrame(LightweightFrame target) {
-        PlatformComponent platformComponent = createLwPlatformComponent();
-        PlatformWindow platformWindow = createPlatformWindow(LWWindowPeer.PeerType.LW_FRAME);
-        return createDelegatedLwPeer(target, platformComponent, platformWindow);
-    }
-
-    @Override
-    public WindowPeer createWindow(Window target) {
+    public final WindowPeer createWindow(Window target) {
         PlatformComponent platformComponent = createPlatformComponent();
-        PlatformWindow platformWindow = createPlatformWindow(LWWindowPeer.PeerType.SIMPLEWINDOW);
-        return createDelegatedPeer(target, platformComponent, platformWindow, LWWindowPeer.PeerType.SIMPLEWINDOW);
+        PlatformWindow platformWindow = createPlatformWindow(PeerType.SIMPLEWINDOW);
+        return createDelegatedPeer(target, platformComponent, platformWindow, PeerType.SIMPLEWINDOW);
     }
 
     @Override
-    public FramePeer createFrame(Frame target) {
-        PlatformComponent platformComponent = createPlatformComponent();
-        PlatformWindow platformWindow = createPlatformWindow(LWWindowPeer.PeerType.FRAME);
-        return createDelegatedPeer(target, platformComponent, platformWindow, LWWindowPeer.PeerType.FRAME);
-    }
-
-    public LWWindowPeer createEmbeddedFrame(CEmbeddedFrame target) {
+    public final FramePeer createFrame(Frame target) {
         PlatformComponent platformComponent = createPlatformComponent();
-        PlatformWindow platformWindow = createPlatformWindow(LWWindowPeer.PeerType.EMBEDDED_FRAME);
-        return createDelegatedPeer(target, platformComponent, platformWindow, LWWindowPeer.PeerType.EMBEDDED_FRAME);
-    }
-
-    public LWWindowPeer createEmbeddedFrame(CViewEmbeddedFrame target) {
-        PlatformComponent platformComponent = createPlatformComponent();
-        PlatformWindow platformWindow = createPlatformWindow(LWWindowPeer.PeerType.VIEW_EMBEDDED_FRAME);
-        return createDelegatedPeer(target, platformComponent, platformWindow, LWWindowPeer.PeerType.VIEW_EMBEDDED_FRAME);
-    }
-
-
-    CPrinterDialogPeer createCPrinterDialog(CPrinterDialog target) {
-        PlatformComponent platformComponent = createPlatformComponent();
-        PlatformWindow platformWindow = createPlatformWindow(LWWindowPeer.PeerType.DIALOG);
-        CPrinterDialogPeer peer = new CPrinterDialogPeer(target, platformComponent, platformWindow);
-        targetCreatedPeer(target, peer);
-        return peer;
+        PlatformWindow platformWindow = createPlatformWindow(PeerType.FRAME);
+        return createDelegatedPeer(target, platformComponent, platformWindow, PeerType.FRAME);
     }
 
     @Override
     public DialogPeer createDialog(Dialog target) {
-        if (target instanceof CPrinterDialog) {
-            return createCPrinterDialog((CPrinterDialog)target);
-        }
-
         PlatformComponent platformComponent = createPlatformComponent();
-        PlatformWindow platformWindow = createPlatformWindow(LWWindowPeer.PeerType.DIALOG);
-        return createDelegatedPeer(target, platformComponent, platformWindow, LWWindowPeer.PeerType.DIALOG);
+        PlatformWindow platformWindow = createPlatformWindow(PeerType.DIALOG);
+        return createDelegatedPeer(target, platformComponent, platformWindow, PeerType.DIALOG);
     }
 
     @Override
-    public FileDialogPeer createFileDialog(FileDialog target) {
+    public final FileDialogPeer createFileDialog(FileDialog target) {
         FileDialogPeer peer = createFileDialogPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
@@ -296,7 +267,7 @@
     // ---- LIGHTWEIGHT COMPONENT PEERS ---- //
 
     @Override
-    public ButtonPeer createButton(Button target) {
+    public final ButtonPeer createButton(Button target) {
         PlatformComponent platformComponent = createPlatformComponent();
         LWButtonPeer peer = new LWButtonPeer(target, platformComponent);
         targetCreatedPeer(target, peer);
@@ -305,7 +276,7 @@
     }
 
     @Override
-    public CheckboxPeer createCheckbox(Checkbox target) {
+    public final CheckboxPeer createCheckbox(Checkbox target) {
         PlatformComponent platformComponent = createPlatformComponent();
         LWCheckboxPeer peer = new LWCheckboxPeer(target, platformComponent);
         targetCreatedPeer(target, peer);
@@ -314,12 +285,7 @@
     }
 
     @Override
-    public CheckboxMenuItemPeer createCheckboxMenuItem(CheckboxMenuItem target) {
-        throw new RuntimeException("not implemented");
-    }
-
-    @Override
-    public ChoicePeer createChoice(Choice target) {
+    public final ChoicePeer createChoice(Choice target) {
         PlatformComponent platformComponent = createPlatformComponent();
         LWChoicePeer peer = new LWChoicePeer(target, platformComponent);
         targetCreatedPeer(target, peer);
@@ -328,7 +294,7 @@
     }
 
     @Override
-    public LabelPeer createLabel(Label target) {
+    public final LabelPeer createLabel(Label target) {
         PlatformComponent platformComponent = createPlatformComponent();
         LWLabelPeer peer = new LWLabelPeer(target, platformComponent);
         targetCreatedPeer(target, peer);
@@ -337,7 +303,7 @@
     }
 
     @Override
-    public CanvasPeer createCanvas(Canvas target) {
+    public final CanvasPeer createCanvas(Canvas target) {
         PlatformComponent platformComponent = createPlatformComponent();
         LWCanvasPeer<?, ?> peer = new LWCanvasPeer<>(target, platformComponent);
         targetCreatedPeer(target, peer);
@@ -346,7 +312,7 @@
     }
 
     @Override
-    public ListPeer createList(List target) {
+    public final ListPeer createList(List target) {
         PlatformComponent platformComponent = createPlatformComponent();
         LWListPeer peer = new LWListPeer(target, platformComponent);
         targetCreatedPeer(target, peer);
@@ -355,22 +321,7 @@
     }
 
     @Override
-    public MenuPeer createMenu(Menu target) {
-        throw new RuntimeException("not implemented");
-    }
-
-    @Override
-    public MenuBarPeer createMenuBar(MenuBar target) {
-        throw new RuntimeException("not implemented");
-    }
-
-    @Override
-    public MenuItemPeer createMenuItem(MenuItem target) {
-        throw new RuntimeException("not implemented");
-    }
-
-    @Override
-    public PanelPeer createPanel(Panel target) {
+    public final PanelPeer createPanel(Panel target) {
         PlatformComponent platformComponent = createPlatformComponent();
         LWPanelPeer peer = new LWPanelPeer(target, platformComponent);
         targetCreatedPeer(target, peer);
@@ -379,12 +330,7 @@
     }
 
     @Override
-    public PopupMenuPeer createPopupMenu(PopupMenu target) {
-        throw new RuntimeException("not implemented");
-    }
-
-    @Override
-    public ScrollPanePeer createScrollPane(ScrollPane target) {
+    public final ScrollPanePeer createScrollPane(ScrollPane target) {
         PlatformComponent platformComponent = createPlatformComponent();
         LWScrollPanePeer peer = new LWScrollPanePeer(target, platformComponent);
         targetCreatedPeer(target, peer);
@@ -393,7 +339,7 @@
     }
 
     @Override
-    public ScrollbarPeer createScrollbar(Scrollbar target) {
+    public final ScrollbarPeer createScrollbar(Scrollbar target) {
         PlatformComponent platformComponent = createPlatformComponent();
         LWScrollBarPeer peer = new LWScrollBarPeer(target, platformComponent);
         targetCreatedPeer(target, peer);
@@ -402,7 +348,7 @@
     }
 
     @Override
-    public TextAreaPeer createTextArea(TextArea target) {
+    public final TextAreaPeer createTextArea(TextArea target) {
         PlatformComponent platformComponent = createPlatformComponent();
         LWTextAreaPeer peer = new LWTextAreaPeer(target, platformComponent);
         targetCreatedPeer(target, peer);
@@ -411,7 +357,7 @@
     }
 
     @Override
-    public TextFieldPeer createTextField(TextField target) {
+    public final TextFieldPeer createTextField(TextField target) {
         PlatformComponent platformComponent = createPlatformComponent();
         LWTextFieldPeer peer = new LWTextFieldPeer(target, platformComponent);
         targetCreatedPeer(target, peer);
@@ -422,56 +368,51 @@
     // ---- NON-COMPONENT PEERS ---- //
 
     @Override
-    public ColorModel getColorModel() throws HeadlessException {
-        return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getColorModel();
+    public final ColorModel getColorModel() throws HeadlessException {
+        return GraphicsEnvironment.getLocalGraphicsEnvironment()
+                                  .getDefaultScreenDevice()
+                                  .getDefaultConfiguration().getColorModel();
     }
 
     @Override
-    public boolean isDesktopSupported() {
+    public final boolean isDesktopSupported() {
         return true;
     }
 
     @Override
-    protected DesktopPeer createDesktopPeer(Desktop target) {
-       return new CDesktopPeer();
-    }
-
-    @Override
-    public DragSourceContextPeer createDragSourceContextPeer(DragGestureEvent dge) {
-        DragSourceContextPeer dscp = CDragSourceContextPeer.createDragSourceContextPeer(dge);
-
-        return dscp;
-    }
-
-    @Override
-    public KeyboardFocusManagerPeer getKeyboardFocusManagerPeer() {
+    public final KeyboardFocusManagerPeer getKeyboardFocusManagerPeer() {
         return LWKeyboardFocusManagerPeer.getInstance();
     }
 
     @Override
-    public synchronized MouseInfoPeer getMouseInfoPeer() {
+    public final synchronized MouseInfoPeer getMouseInfoPeer() {
         if (mouseInfoPeer == null) {
             mouseInfoPeer = createMouseInfoPeerImpl();
         }
         return mouseInfoPeer;
     }
 
-    protected MouseInfoPeer createMouseInfoPeerImpl() {
+    protected final MouseInfoPeer createMouseInfoPeerImpl() {
         return new LWMouseInfoPeer();
     }
 
-    public PrintJob getPrintJob(Frame frame, String doctitle, Properties props) {
+    @Override
+    public final PrintJob getPrintJob(Frame frame, String doctitle,
+                                      Properties props) {
         return getPrintJob(frame, doctitle, null, null);
     }
 
-    public PrintJob getPrintJob(Frame frame, String doctitle, JobAttributes jobAttributes, PageAttributes pageAttributes) {
+    @Override
+    public final PrintJob getPrintJob(Frame frame, String doctitle,
+                                      JobAttributes jobAttributes,
+                                      PageAttributes pageAttributes) {
         if (GraphicsEnvironment.isHeadless()) {
             throw new IllegalArgumentException();
         }
 
         PrintJob2D printJob = new PrintJob2D(frame, doctitle, jobAttributes, pageAttributes);
 
-        if (printJob.printDialog() == false) {
+        if (!printJob.printDialog()) {
             printJob = null;
         }
 
@@ -479,27 +420,7 @@
     }
 
     @Override
-    public RobotPeer createRobot(Robot target, GraphicsDevice screen) {
-        throw new RuntimeException("not implemented");
-    }
-
-    @Override
-    public boolean isTraySupported() {
-        throw new RuntimeException("not implemented");
-    }
-
-    @Override
-    public SystemTrayPeer createSystemTray(SystemTray target) {
-        throw new RuntimeException("not implemented");
-    }
-
-    @Override
-    public TrayIconPeer createTrayIcon(TrayIcon target) {
-        throw new RuntimeException("not implemented");
-    }
-
-    @Override
-    public Clipboard getSystemClipboard() {
+    public final Clipboard getSystemClipboard() {
         SecurityManager security = System.getSecurityManager();
         if (security != null) {
             security.checkPermission(AWTPermissions.ACCESS_CLIPBOARD_PERMISSION);
@@ -513,7 +434,8 @@
         return clipboard;
     }
 
-    protected abstract SecurityWarningWindow createSecurityWarning(Window ownerWindow, LWWindowPeer ownerPeer);
+    protected abstract SecurityWarningWindow createSecurityWarning(
+            Window ownerWindow, LWWindowPeer ownerPeer);
 
     // ---- DELEGATES ---- //
 
@@ -522,7 +444,7 @@
     /*
      * Creates a delegate for the given peer type (window, frame, dialog, etc.)
      */
-    protected abstract PlatformWindow createPlatformWindow(LWWindowPeer.PeerType peerType);
+    protected abstract PlatformWindow createPlatformWindow(PeerType peerType);
 
     protected abstract PlatformComponent createPlatformComponent();
 
@@ -556,7 +478,7 @@
     }
 
     @Override
-    public void grab(final Window w) {
+    public final void grab(final Window w) {
         final Object peer = AWTAccessor.getComponentAccessor().getPeer(w);
         if (peer != null) {
             ((LWWindowPeer) peer).grab();
@@ -564,7 +486,7 @@
     }
 
     @Override
-    public void ungrab(final Window w) {
+    public final void ungrab(final Window w) {
         final Object peer = AWTAccessor.getComponentAccessor().getPeer(w);
         if (peer != null) {
             ((LWWindowPeer) peer).ungrab(false);
--- a/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -629,6 +629,7 @@
         final boolean isNewDevice = updateGraphicsDevice();
         if (resized || isNewDevice) {
             replaceSurfaceData();
+            updateMinimumSize();
         }
 
         // Third, COMPONENT_MOVED/COMPONENT_RESIZED/PAINT events
@@ -1046,7 +1047,9 @@
 
     @Override
     public final void displayChanged() {
-        updateGraphicsDevice();
+        if (updateGraphicsDevice()) {
+            updateMinimumSize();
+        }
         // Replace surface unconditionally, because internal state of the
         // GraphicsDevice could be changed.
         replaceSurfaceData();
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CClipboard.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CClipboard.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,20 +40,23 @@
  * sun.awt.datatransfer.DataTransferer.
  */
 
-public class CClipboard extends SunClipboard {
+final class CClipboard extends SunClipboard {
 
     public CClipboard(String name) {
         super(name);
     }
 
+    @Override
     public long getID() {
         return 0;
     }
 
+    @Override
     protected void clearNativeContext() {
         // Leaving Empty, as WClipboard.clearNativeContext is empty as well.
     }
 
+    @Override
     protected void setContentsNative(Transferable contents) {
 
         // Don't use delayed Clipboard rendering for the Transferable's data.
@@ -89,6 +92,39 @@
         notifyChanged();
     }
 
+    @Override
+    protected native long[] getClipboardFormats();
+    @Override
+    protected native byte[] getClipboardData(long format) throws IOException;
+
+    // 1.5 peer method
+    @Override
+    protected void unregisterClipboardViewerChecked() {
+        // no-op because we lack OS support. This requires 4048791, which requires 4048792
+    }
+
+    // 1.5 peer method
+    @Override
+    protected void registerClipboardViewerChecked()    {
+        // no-op because we lack OS support. This requires 4048791, which requires 4048792
+    }
+
+    // 1.5 peer method
+    // no-op. This appears to be win32 specific. Filed 4048790 for investigation
+    //protected Transferable createLocaleTransferable(long[] formats) throws IOException;
+
+    private native void declareTypes(long[] formats, SunClipboard newOwner);
+    private native void setData(byte[] data, long format);
+
+    /**
+     * Invokes native check whether a change count on the general pasteboard is different
+     * than when we set it. The different count value means the current owner lost
+     * pasteboard ownership and someone else put data on the clipboard.
+     * @since 1.7
+     */
+    native void checkPasteboard();
+
+    /*** Native Callbacks ***/
     private void notifyLostOwnership() {
         lostOwnershipImpl();
     }
@@ -100,32 +136,4 @@
         }
         clipboard.checkChange(clipboard.getClipboardFormats());
     }
-
-    protected native long[] getClipboardFormats();
-    protected native byte[] getClipboardData(long format) throws IOException;
-
-    // 1.5 peer method
-    protected void unregisterClipboardViewerChecked() {
-        // no-op because we lack OS support. This requires 4048791, which requires 4048792
-    }
-
-    // 1.5 peer method
-    protected void registerClipboardViewerChecked()    {
-        // no-op because we lack OS support. This requires 4048791, which requires 4048792
-    }
-
-    // 1.5 peer method
-    // no-op. This appears to be win32 specific. Filed 4048790 for investigation
-    //protected Transferable createLocaleTransferable(long[] formats) throws IOException;
-
-    public native void declareTypes(long[] formats, SunClipboard newOwner);
-    public native void setData(byte[] data, long format);
-
-    /**
-     * Invokes native check whether a change count on the general pasteboard is different
-     * than when we set it. The different count value means the current owner lost
-     * pasteboard ownership and someone else put data on the clipboard.
-     * @since 1.7
-     */
-    public native void checkPasteboard();
 }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CCustomCursor.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CCustomCursor.java	Wed Jul 05 19:33:51 2017 +0200
@@ -38,6 +38,8 @@
 
     Image fImage;
     Point fHotspot;
+    int fWidth;
+    int fHeight;
 
     public CCustomCursor(final Image cursor, final Point hotSpot, final String name) throws IndexOutOfBoundsException, HeadlessException {
         super(name);
@@ -50,6 +52,7 @@
         // Make sure image is fully loaded.
         final Component c = new Canvas(); // for its imageUpdate method
         final MediaTracker tracker = new MediaTracker(c);
+        // MediaTracker loads resolution variants from MultiResolution Toolkit image
         tracker.addImage(fImage, 0);
         try {
             tracker.waitForAll();
@@ -67,15 +70,15 @@
             width = height = 1;
             fImage = createTransparentImage(width, height);
         } else {
-            // Scale image to nearest supported size
+            // Get the nearest supported cursor size
             final Dimension nativeSize = toolkit.getBestCursorSize(width, height);
-            if (nativeSize.width != width || nativeSize.height != height) {
-                fImage = fImage.getScaledInstance(nativeSize.width, nativeSize.height, Image.SCALE_DEFAULT);
-                width = nativeSize.width;
-                height = nativeSize.height;
-            }
+            width = nativeSize.width;
+            height = nativeSize.height;
         }
 
+        fWidth = width;
+        fHeight = height;
+
         // NOTE: this was removed for 3169146, but in 1.5 the JCK tests for an exception and fails if one isn't thrown.
         // See what JBuilder does.
         // Verify that the hotspot is within cursor bounds.
@@ -138,6 +141,7 @@
                 // failed to do its job. Return null to keep the cursor unchanged.
                 return 0L;
             } else {
+                fCImage.resizeRepresentations(fWidth, fHeight);
                 return fCImage.ptr;
             }
         } catch (IllegalArgumentException iae) {
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -56,11 +56,11 @@
     };
 
     static {
-        Map<String, Long> nameMap = new HashMap<String, Long>(predefinedClipboardNames.length, 1.0f);
-        Map<Long, String> formatMap = new HashMap<Long, String>(predefinedClipboardNames.length, 1.0f);
+        Map<String, Long> nameMap = new HashMap<>(predefinedClipboardNames.length, 1.0f);
+        Map<Long, String> formatMap = new HashMap<>(predefinedClipboardNames.length, 1.0f);
         for (int i = 1; i < predefinedClipboardNames.length; i++) {
-            nameMap.put(predefinedClipboardNames[i], new Long(i));
-            formatMap.put(new Long(i), predefinedClipboardNames[i]);
+            nameMap.put(predefinedClipboardNames[i], (long) i);
+            formatMap.put((long) i, predefinedClipboardNames[i]);
         }
         predefinedClipboardNameMap = Collections.synchronizedMap(nameMap);
         predefinedClipboardFormatMap = Collections.synchronizedMap(formatMap);
@@ -77,19 +77,11 @@
     public static final int CF_PNG         = 10;
     public static final int CF_JPEG        = 11;
 
-    public static final Long L_CF_TIFF = predefinedClipboardNameMap.get(predefinedClipboardNames[CF_TIFF]);
-
-    // Image file formats with java.awt.Image representation:
-    private static final Long[] imageFormats = new Long[] {
-        L_CF_TIFF
-    };
-
-
     private CDataTransferer() {}
 
     private static CDataTransferer fTransferer;
 
-    public static synchronized CDataTransferer getInstanceImpl() {
+    static synchronized CDataTransferer getInstanceImpl() {
         if (fTransferer == null) {
             fTransferer = new CDataTransferer();
         }
@@ -97,18 +89,22 @@
         return fTransferer;
     }
 
+    @Override
     public String getDefaultUnicodeEncoding() {
         return "utf-16le";
     }
 
+    @Override
     public boolean isLocaleDependentTextFormat(long format) {
         return format == CF_STRING;
     }
 
+    @Override
     public boolean isFileFormat(long format) {
         return format == CF_FILE;
     }
 
+    @Override
     public boolean isImageFormat(long format) {
         int ifmt = (int)format;
         switch(ifmt) {
@@ -122,43 +118,12 @@
         }
     }
 
-    protected Long[] getImageFormatsAsLongArray() {
-        return imageFormats;
-    }
-
-    public byte[] translateTransferable(Transferable contents, DataFlavor flavor, long format) throws IOException
-        {
-            byte[] bytes = super.translateTransferable(contents, flavor, format);
-
-            // 9-12-02 VL: we may need to do something like Windows here.
-            //if (format == CF_HTML) {
-            //    bytes = HTMLSupport.convertToHTMLFormat(bytes);
-            //}
-
-            return bytes;
-        }
-
-    protected Object translateBytesOrStream(InputStream stream, byte[] bytes, DataFlavor flavor, long format,
-                                            Transferable transferable) throws IOException
-        {
-            // 5-28-03 VL: [Radar 3266030]
-            // We need to do like Windows does here.
-            if (format == CF_HTML && flavor.isFlavorTextType()) {
-                if (stream == null) {
-                    stream = new ByteArrayInputStream(bytes);
-                    bytes = null;
-                }
-
-                stream = new HTMLDecodingInputStream(stream);
-            }
+    @Override
+    public Object translateBytes(byte[] bytes, DataFlavor flavor,
+                                    long format, Transferable transferable) throws IOException {
 
             if (format == CF_URL && URL.class.equals(flavor.getRepresentationClass()))
             {
-                if (bytes == null) {
-                    bytes = inputStreamToByteArray(stream);
-                    stream = null;
-                }
-
                 String charset = getDefaultTextCharset();
                 if (transferable != null && transferable.isDataFlavorSupported(javaTextEncodingFlavor)) {
                     try {
@@ -175,9 +140,9 @@
             }
 
             return super.translateBytes(bytes, flavor, format, transferable);
-        }
+    }
 
-
+    @Override
     synchronized protected Long getFormatForNativeAsLong(String str) {
         Long format = predefinedClipboardNameMap.get(str);
 
@@ -202,6 +167,7 @@
     // Get registered native format string for an index, return null if unknown:
     private native String formatForIndex(long index);
 
+    @Override
     protected String getNativeForFormat(long format) {
         String returnValue = null;
 
@@ -209,7 +175,7 @@
         if (format >= 0 && format < predefinedClipboardNames.length) {
             returnValue = predefinedClipboardNames[(int) format];
         } else {
-            Long formatObj = new Long(format);
+            Long formatObj = format;
             returnValue = predefinedClipboardFormatMap.get(formatObj);
 
             // predefinedClipboardFormatMap may not know this format:
@@ -233,10 +199,13 @@
 
     private final ToolkitThreadBlockedHandler handler = new CToolkitThreadBlockedHandler();
 
+    @Override
     public ToolkitThreadBlockedHandler getToolkitThreadBlockedHandler() {
         return handler;
     }
 
+    private native byte[] imageDataToPlatformImageBytes(int[] rData, int nW, int nH);
+    @Override
     protected byte[] imageToPlatformBytes(Image image, long format) {
         int w = image.getWidth(null);
         int h = image.getHeight(null);
@@ -252,32 +221,28 @@
     }
 
     private static native String[] nativeDragQueryFile(final byte[] bytes);
+    @Override
     protected String[] dragQueryFile(final byte[] bytes) {
         if (bytes == null) return null;
         if (new String(bytes).startsWith("Unsupported type")) return null;
         return nativeDragQueryFile(bytes);
     }
 
-    private native byte[] imageDataToPlatformImageBytes(int[] rData, int nW, int nH);
-
+    private native Image getImageForByteStream(byte[] bytes);
     /**
      * Translates a byte array which contains
      * platform-specific image data in the given format into an Image.
      */
-    protected Image platformImageBytesToImage(byte[] bytes, long format)
-        throws IOException
-    {
+    @Override
+    protected Image platformImageBytesToImage(byte[] bytes, long format) throws IOException {
         return getImageForByteStream(bytes);
     }
 
-    private native Image getImageForByteStream(byte[] bytes);
-
     @Override
     protected ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList) throws IOException {
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        for (int i = 0; i < fileList.size(); i++)
-        {
-            byte[] bytes = fileList.get(i).getBytes();
+        for (String file : fileList) {
+            byte[] bytes = file.getBytes();
             bos.write(bytes, 0, bytes.length);
             bos.write(0);
         }
@@ -303,246 +268,3 @@
 }
 
 
-// ---- Code borrowed from WDataTransferer: ----
-// This will come handy for supporting HTML data.
-
-final class HTMLSupport {
-    public static final String ENCODING = "UTF-8";
-
-    public static final String VERSION = "Version:";
-    public static final String START_HTML = "StartHTML:";
-    public static final String END_HTML = "EndHTML:";
-    public static final String START_FRAGMENT = "StartFragment:";
-    public static final String END_FRAGMENT = "EndFragment:";
-    public static final String START_FRAGMENT_CMT = "<!--StartFragment-->";
-    public static final String END_FRAGMENT_CMT = "<!--EndFragment-->";
-    public static final String EOLN = "\r\n";
-
-    private static final String VERSION_NUM = "0.9";
-    private static final String HTML_START_END = "-1";
-
-    private static final int PADDED_WIDTH = 10;
-
-    private static final int HEADER_LEN =
-        VERSION.length() + VERSION_NUM.length() + EOLN.length() +
-        START_HTML.length() + HTML_START_END.length() + EOLN.length() +
-        END_HTML.length() + HTML_START_END.length() + EOLN.length() +
-        START_FRAGMENT.length() + PADDED_WIDTH + EOLN.length() +
-        END_FRAGMENT.length() + PADDED_WIDTH + EOLN.length() +
-        START_FRAGMENT_CMT.length() + EOLN.length();
-    private static final String HEADER_LEN_STR =
-        toPaddedString(HEADER_LEN, PADDED_WIDTH);
-
-    private static final String TRAILER = END_FRAGMENT_CMT + EOLN + '\0';
-
-    private static String toPaddedString(int n, int width) {
-        String string = "" + n;
-        int len = string.length();
-        if (n >= 0 && len < width) {
-            char[] array = new char[width - len];
-            Arrays.fill(array, '0');
-            StringBuffer buffer = new StringBuffer();
-            buffer.append(array);
-            buffer.append(string);
-            string = buffer.toString();
-        }
-        return string;
-    }
-
-    public static byte[] convertToHTMLFormat(byte[] bytes) {
-        StringBuffer header = new StringBuffer(HEADER_LEN);
-        header.append(VERSION);
-        header.append(VERSION_NUM);
-        header.append(EOLN);
-        header.append(START_HTML);
-        header.append(HTML_START_END);
-        header.append(EOLN);
-        header.append(END_HTML);
-        header.append(HTML_START_END);
-        header.append(EOLN);
-        header.append(START_FRAGMENT);
-        header.append(HEADER_LEN_STR);
-        header.append(EOLN);
-        header.append(END_FRAGMENT);
-        // Strip terminating NUL byte from array
-        header.append(toPaddedString(HEADER_LEN + bytes.length - 1,
-                                     PADDED_WIDTH));
-        header.append(EOLN);
-        header.append(START_FRAGMENT_CMT);
-        header.append(EOLN);
-
-        byte[] headerBytes = null, trailerBytes = null;
-
-        try {
-            headerBytes = new String(header).getBytes(ENCODING);
-            trailerBytes = TRAILER.getBytes(ENCODING);
-        } catch (UnsupportedEncodingException cannotHappen) {
-        }
-
-        byte[] retval = new byte[headerBytes.length + bytes.length - 1 +
-            trailerBytes.length];
-
-        System.arraycopy(headerBytes, 0, retval, 0, headerBytes.length);
-        System.arraycopy(bytes, 0, retval, headerBytes.length,
-                         bytes.length - 1);
-        System.arraycopy(trailerBytes, 0, retval,
-                         headerBytes.length + bytes.length - 1,
-                         trailerBytes.length);
-
-        return retval;
-    }
-}
-
-/**
-* This stream takes an InputStream which provides data in CF_HTML format,
- * strips off the description and context to extract the original HTML data.
- */
-class HTMLDecodingInputStream extends InputStream {
-
-    private final BufferedInputStream bufferedStream;
-    private boolean descriptionParsed = false;
-    private boolean closed = false;
-    private int index;
-    private int end;
-
-    // InputStreamReader uses an 8K buffer. The size is not customizable.
-    public static final int BYTE_BUFFER_LEN = 8192;
-
-    // CharToByteUTF8.getMaxBytesPerChar returns 3, so we should not buffer
-    // more chars than 3 times the number of bytes we can buffer.
-    public static final int CHAR_BUFFER_LEN = BYTE_BUFFER_LEN / 3;
-
-    private static final String FAILURE_MSG =
-        "Unable to parse HTML description: ";
-    private static final String INVALID_MSG = " invalid";
-
-    public HTMLDecodingInputStream(InputStream bytestream) throws IOException {
-        bufferedStream = new BufferedInputStream(bytestream, BYTE_BUFFER_LEN);
-    }
-
-    private void parseDescription() throws IOException {
-        bufferedStream.mark(BYTE_BUFFER_LEN);
-
-        BufferedReader bufferedReader = new BufferedReader
-            (new InputStreamReader(bufferedStream, HTMLSupport.ENCODING),
-             CHAR_BUFFER_LEN);
-        String version = bufferedReader.readLine().trim();
-        if (version == null || !version.startsWith(HTMLSupport.VERSION)) {
-            // Not MS-compliant HTML text. Return raw text from read().
-            index = 0;
-            end = -1;
-            bufferedStream.reset();
-            return;
-        }
-
-        String input;
-        boolean startHTML, endHTML, startFragment, endFragment;
-        startHTML = endHTML = startFragment = endFragment = false;
-
-        try {
-            do {
-                input = bufferedReader.readLine().trim();
-                if (input == null) {
-                    close();
-                    throw new IOException(FAILURE_MSG);
-                } else if (input.startsWith(HTMLSupport.START_HTML)) {
-                    int val = Integer.parseInt
-                    (input.substring(HTMLSupport.START_HTML.length(),
-                                     input.length()).trim());
-                    if (val >= 0) {
-                        index = val;
-                        startHTML = true;
-                    } else if (val != -1) {
-                        close();
-                        throw new IOException(FAILURE_MSG +
-                                              HTMLSupport.START_HTML +
-                                              INVALID_MSG);
-                    }
-                } else if (input.startsWith(HTMLSupport.END_HTML)) {
-                    int val = Integer.parseInt
-                    (input.substring(HTMLSupport.END_HTML.length(),
-                                     input.length()).trim());
-                    if (val >= 0) {
-                        end = val;
-                        endHTML = true;
-                    } else if (val != -1) {
-                        close();
-                        throw new IOException(FAILURE_MSG +
-                                              HTMLSupport.END_HTML +
-                                              INVALID_MSG);
-                    }
-                } else if (!startHTML && !endHTML &&
-                           input.startsWith(HTMLSupport.START_FRAGMENT)) {
-                    index = Integer.parseInt
-                    (input.substring(HTMLSupport.START_FRAGMENT.length(),
-                                     input.length()).trim());
-                    if (index < 0) {
-                        close();
-                        throw new IOException(FAILURE_MSG +
-                                              HTMLSupport.START_FRAGMENT +
-                                              INVALID_MSG);
-                    }
-                    startFragment = true;
-                } else if (!startHTML && !endHTML &&
-                           input.startsWith(HTMLSupport.END_FRAGMENT)) {
-                    end = Integer.parseInt
-                    (input.substring(HTMLSupport.END_FRAGMENT.length(),
-                                     input.length()).trim());
-                    if (end < 0) {
-                        close();
-                        throw new IOException(FAILURE_MSG +
-                                              HTMLSupport.END_FRAGMENT +
-                                              INVALID_MSG);
-                    }
-                    endFragment = true;
-                }
-            } while (!((startHTML && endHTML) ||
-                       (startFragment && endFragment)));
-        } catch (NumberFormatException e) {
-            close();
-            throw new IOException(FAILURE_MSG + e);
-        }
-
-        bufferedStream.reset();
-
-        for (int i = 0; i < index; i++) {
-            if (bufferedStream.read() == -1) {
-                close();
-                throw new IOException(FAILURE_MSG +
-                                      "Byte stream ends in description.");
-            }
-        }
-    }
-
-    public int read() throws IOException {
-        if (closed) {
-            throw new IOException("Stream closed");
-        }
-
-        if (!descriptionParsed) {
-            parseDescription(); // initializes 'index' and 'end'
-            descriptionParsed = true;
-        }
-
-        if (end != -1 && index >= end) {
-            return -1;
-        }
-
-        int retval = bufferedStream.read();
-        if (retval == -1) {
-            index = end = 0; // so future read() calls will fail quickly
-            return -1;
-        }
-
-        index++;
-    //    System.out.print((char)retval);
-        return retval;
-    }
-
-    public void close() throws IOException {
-        if (!closed) {
-            closed = true;
-            bufferedStream.close();
-        }
-    }
-}
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -141,7 +141,7 @@
             // Create native dragging source:
             final long nativeDragSource = createNativeDragSource(component, nativeViewPtr, transferable, triggerEvent,
                 (int) (dragOrigin.getX()), (int) (dragOrigin.getY()), extModifiers,
-                clickCount, timestamp, fDragCImage, dragImageOffset.x, dragImageOffset.y,
+                clickCount, timestamp, fDragCImage != null ? fDragCImage.ptr : 0L, dragImageOffset.x, dragImageOffset.y,
                 getDragSourceContext().getSourceActions(), formats, formatMap);
 
             if (nativeDragSource == 0)
@@ -484,7 +484,7 @@
     // Native support:
     private native long createNativeDragSource(Component component, long nativePeer, Transferable transferable,
         InputEvent triggerEvent, int dragPosX, int dragPosY, int extModifiers, int clickCount, long timestamp,
-        CImage nsDragImage, int dragImageOffsetX, int dragImageOffsetY,
+        long nsDragImagePtr, int dragImageOffsetX, int dragImageOffsetY,
         int sourceActions, long[] formats, Map formatMap);
 
     private native void doDragging(long nativeDragSource);
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,17 +23,15 @@
  * questions.
  */
 
+
 package sun.lwawt.macosx;
 
-import sun.lwawt.LWToolkit;
-import sun.lwawt.LWWindowPeer;
-import sun.lwawt.macosx.CocoaConstants;
-import sun.lwawt.macosx.event.NSEvent;
+import java.awt.AWTKeyStroke;
+import java.awt.Point;
+import java.awt.Toolkit;
 
 import sun.awt.EmbeddedFrame;
-
-import java.awt.*;
-import java.awt.event.*;
+import sun.lwawt.LWWindowPeer;
 
 public class CEmbeddedFrame extends EmbeddedFrame {
 
@@ -48,7 +46,7 @@
 
     public void addNotify() {
         if (getPeer() == null) {
-            LWToolkit toolkit = (LWToolkit)Toolkit.getDefaultToolkit();
+            LWCToolkit toolkit = (LWCToolkit)Toolkit.getDefaultToolkit();
             LWWindowPeer peer = toolkit.createEmbeddedFrame(this);
             setPeer(peer);
             responder = new CPlatformResponder(peer, true);
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CFileDialog.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CFileDialog.java	Wed Jul 05 19:33:51 2017 +0200
@@ -46,17 +46,16 @@
         @Override
         public void run() {
             try {
-                boolean navigateApps = false;
-                int dialogMode = target.getMode();
+                boolean navigateApps = !AccessController.doPrivileged(
+                        new GetBooleanAction("apple.awt.use-file-dialog-packages"));
+                boolean chooseDirectories = AccessController.doPrivileged(
+                        new GetBooleanAction("apple.awt.fileDialogForDirectories"));
 
-                navigateApps = true;
-
+                int dialogMode = target.getMode();
                 String title = target.getTitle();
                 if (title == null) {
                     title = " ";
                 }
-                Boolean chooseDirectories = AccessController.doPrivileged(
-                        new GetBooleanAction("apple.awt.fileDialogForDirectories"));
 
                 String[] userFileNames = nativeRunFileDialog(title,
                         dialogMode,
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CImage.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CImage.java	Wed Jul 05 19:33:51 2017 +0200
@@ -31,6 +31,7 @@
 
 import java.util.Arrays;
 import java.util.List;
+import sun.awt.image.MultiResolutionImage;
 
 import sun.awt.image.SunWritableRaster;
 
@@ -44,6 +45,7 @@
     private static native void nativeCopyNSImageIntoArray(long image, int[] buffer, int w, int h);
     private static native Dimension2D nativeGetNSImageSize(long image);
     private static native void nativeSetNSImageSize(long image, double w, double h);
+    private static native void nativeResizeNSImageRepresentations(long image, double w, double h);
 
     static Creator creator = new Creator();
     static Creator getCreator() {
@@ -145,6 +147,12 @@
 
         // This is used to create a CImage from a Image
         public CImage createFromImage(final Image image) {
+            if (image instanceof MultiResolutionImage) {
+                List<Image> resolutionVariants
+                        = ((MultiResolutionImage) image).getResolutionVariants();
+                return createFromImages(resolutionVariants);
+            }
+
             int[] buffer = imageToArray(image, true);
             if (buffer == null) {
                 return null;
@@ -223,4 +231,8 @@
         if (ptr != 0) nativeSetNSImageSize(ptr, w, h);
         return this;
     }
+
+    void resizeRepresentations(double w, double h) {
+        if (ptr != 0) nativeResizeNSImageRepresentations(ptr, w, h);
+    }
 }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +28,7 @@
 import sun.awt.SunToolkit;
 import sun.lwawt.LWWindowPeer;
 import sun.lwawt.PlatformEventNotifier;
-import sun.lwawt.macosx.event.NSEvent;
+
 import java.awt.Toolkit;
 import java.awt.event.MouseEvent;
 import java.awt.event.InputEvent;
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +31,6 @@
 import sun.awt.CGraphicsConfig;
 import sun.awt.CGraphicsEnvironment;
 import sun.lwawt.LWWindowPeer;
-import sun.lwawt.macosx.event.NSEvent;
 
 import sun.java2d.SurfaceData;
 import sun.java2d.opengl.CGLLayer;
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -583,7 +583,12 @@
                     // setVisible could have changed the native maximized state
                     deliverZoom(true);
                 } else {
-                    switch (((Frame)target).getExtendedState()) {
+                    int frameState = ((Frame)target).getExtendedState();
+                    if ((frameState & Frame.ICONIFIED) != 0) {
+                        // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
+                        frameState = Frame.ICONIFIED;
+                    }
+                    switch (frameState) {
                         case Frame.ICONIFIED:
                             CWrapper.NSWindow.miniaturize(nsWindowPtr);
                             break;
@@ -608,9 +613,7 @@
             // Add myself as a child
             if (owner != null && owner.isVisible()) {
                 CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(), nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
-                if (target.isAlwaysOnTop()) {
-                    CWrapper.NSWindow.setLevel(nsWindowPtr, CWrapper.NSWindow.NSFloatingWindowLevel);
-                }
+                applyWindowLevel(target);
             }
 
             // Add my own children to myself
@@ -620,9 +623,7 @@
                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
                     if (pw != null && pw.isVisible()) {
                         CWrapper.NSWindow.addChildWindow(nsWindowPtr, pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove);
-                        if (w.isAlwaysOnTop()) {
-                            CWrapper.NSWindow.setLevel(pw.getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
-                        }
+                        pw.applyWindowLevel(w);
                     }
                 }
             }
@@ -788,6 +789,10 @@
         if (prevWindowState == windowState) return;
 
         final long nsWindowPtr = getNSWindowPtr();
+        if ((windowState & Frame.ICONIFIED) != 0) {
+            // Treat all state bit masks with ICONIFIED bit as ICONIFIED state.
+            windowState = Frame.ICONIFIED;
+        }
         switch (windowState) {
             case Frame.ICONIFIED:
                 if (prevWindowState == Frame.MAXIMIZED_BOTH) {
@@ -1041,8 +1046,14 @@
             CWrapper.NSWindow.addChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove);
         }
 
-        if (target.isAlwaysOnTop()) {
+        applyWindowLevel(target);
+    }
+
+    protected void applyWindowLevel(Window target) {
+        if (target.isAlwaysOnTop() && target.getType() != Window.Type.POPUP) {
             CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSFloatingWindowLevel);
+        } else if (target.getType() == Window.Type.POPUP) {
+            CWrapper.NSWindow.setLevel(getNSWindowPtr(), CWrapper.NSWindow.NSPopUpMenuWindowLevel);
         }
     }
 
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterJob.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterJob.java	Wed Jul 05 19:33:51 2017 +0200
@@ -41,7 +41,7 @@
 import sun.java2d.*;
 import sun.print.*;
 
-public class CPrinterJob extends RasterPrinterJob {
+final class CPrinterJob extends RasterPrinterJob {
     // NOTE: This uses RasterPrinterJob as a base, but it doesn't use
     // all of the RasterPrinterJob functions. RasterPrinterJob will
     // break down printing to pieces that aren't necessary under MacOSX
@@ -89,6 +89,7 @@
      * returns true.
      * @see java.awt.GraphicsEnvironment#isHeadless
      */
+    @Override
     public boolean printDialog() throws HeadlessException {
         if (GraphicsEnvironment.isHeadless()) {
             throw new HeadlessException();
@@ -131,6 +132,7 @@
      * @see java.awt.GraphicsEnvironment#isHeadless
      * @since     1.2
      */
+    @Override
     public PageFormat pageDialog(PageFormat page) throws HeadlessException {
         if (GraphicsEnvironment.isHeadless()) {
             throw new HeadlessException();
@@ -156,12 +158,14 @@
      * @return clone of <code>page</code>, altered to describe a default
      *                      <code>PageFormat</code>.
      */
+    @Override
     public PageFormat defaultPage(PageFormat page) {
         PageFormat newPage = (PageFormat)page.clone();
         getDefaultPage(newPage);
         return newPage;
     }
 
+    @Override
     protected void setAttributes(PrintRequestAttributeSet attributes) throws PrinterException {
         super.setAttributes(attributes);
 
@@ -216,7 +220,7 @@
         }
     }
 
-
+    @Override
     public void print(PrintRequestAttributeSet attributes) throws PrinterException {
         // NOTE: Some of this code is copied from RasterPrinterJob.
 
@@ -343,6 +347,7 @@
      * Returns the resolution in dots per inch across the width
      * of the page.
      */
+    @Override
     protected double getXRes() {
         // NOTE: This is not used in the CPrinterJob code path.
         return 0;
@@ -352,6 +357,7 @@
      * Returns the resolution in dots per inch down the height
      * of the page.
      */
+    @Override
     protected double getYRes() {
         // NOTE: This is not used in the CPrinterJob code path.
         return 0;
@@ -362,6 +368,7 @@
      * Value is in device pixels.
      * Not adjusted for orientation of the paper.
      */
+    @Override
     protected double getPhysicalPrintableX(Paper p) {
         // NOTE: This is not used in the CPrinterJob code path.
         return 0;
@@ -372,6 +379,7 @@
      * Value is in device pixels.
      * Not adjusted for orientation of the paper.
      */
+    @Override
     protected double getPhysicalPrintableY(Paper p) {
         // NOTE: This is not used in the CPrinterJob code path.
         return 0;
@@ -382,6 +390,7 @@
      * Value is in device pixels.
      * Not adjusted for orientation of the paper.
      */
+    @Override
     protected double getPhysicalPrintableWidth(Paper p) {
         // NOTE: This is not used in the CPrinterJob code path.
         return 0;
@@ -392,6 +401,7 @@
      * Value is in device pixels.
      * Not adjusted for orientation of the paper.
      */
+    @Override
     protected double getPhysicalPrintableHeight(Paper p) {
         // NOTE: This is not used in the CPrinterJob code path.
         return 0;
@@ -402,6 +412,7 @@
      * Value is in device pixels.
      * Not adjusted for orientation of the paper.
      */
+    @Override
     protected double getPhysicalPageWidth(Paper p) {
         // NOTE: This is not used in the CPrinterJob code path.
         return 0;
@@ -412,6 +423,7 @@
      * Value is in device pixels.
      * Not adjusted for orientation of the paper.
      */
+    @Override
     protected double getPhysicalPageHeight(Paper p) {
         // NOTE: This is not used in the CPrinterJob code path.
         return 0;
@@ -429,6 +441,7 @@
     /**
      * End a page.
      */
+    @Override
     protected void endPage(PageFormat format, Printable painter, int index) throws PrinterException {
         // NOTE: This is not used in the CPrinterJob code path.
         throw new PrinterException(sShouldNotReachHere);
@@ -441,6 +454,7 @@
      * page. The width and height of the band is
      * specified by the caller.
      */
+    @Override
     protected void printBand(byte[] data, int x, int y, int width, int height) throws PrinterException {
         // NOTE: This is not used in the CPrinterJob code path.
         throw new PrinterException(sShouldNotReachHere);
@@ -450,6 +464,7 @@
      * Called by the print() method at the start of
      * a print job.
      */
+    @Override
     protected void startDoc() throws PrinterException {
         // NOTE: This is not used in the CPrinterJob code path.
         throw new PrinterException(sShouldNotReachHere);
@@ -459,12 +474,14 @@
      * Called by the print() method at the end of
      * a print job.
      */
+    @Override
     protected void endDoc() throws PrinterException {
         // NOTE: This is not used in the CPrinterJob code path.
         throw new PrinterException(sShouldNotReachHere);
     }
 
     /* Called by cancelDoc */
+    @Override
     protected native void abortDoc();
 
     /**
@@ -502,10 +519,12 @@
     /**
      * validate the paper size against the current printer.
      */
+    @Override
     protected native void validatePaper(Paper origPaper, Paper newPaper );
 
     // The following methods are CPrinterJob specific.
 
+    @Override
     protected void finalize() {
         if (fNSPrintInfo != -1) {
             dispose(fNSPrintInfo);
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterJobDialog.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterJobDialog.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +29,7 @@
 import java.awt.*;
 import java.awt.print.*;
 
-public class CPrinterJobDialog extends CPrinterDialog {
+final class CPrinterJobDialog extends CPrinterDialog {
     private Pageable fPageable;
     private boolean fAllowPrintToFile;
 
@@ -39,5 +39,6 @@
         fAllowPrintToFile = allowPrintToFile;
     }
 
+    @Override
     protected native boolean showDialog();
 }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterPageDialog.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterPageDialog.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +29,7 @@
 import java.awt.*;
 import java.awt.print.*;
 
-public class CPrinterPageDialog extends CPrinterDialog {
+final class CPrinterPageDialog extends CPrinterDialog {
     private PageFormat fPage;
     private Printable fPainter;
 
@@ -39,5 +39,6 @@
         fPainter = painter;
     }
 
+    @Override
     protected native boolean showDialog();
 }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterSurfaceData.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterSurfaceData.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,11 +40,11 @@
 //    public static final SurfaceType IntArgbPQ = SurfaceType.IntArgb.deriveSubType(DESC_INT_ARGB_PQ);
     public static final SurfaceType IntRgbPQ = SurfaceType.IntRgb.deriveSubType(DESC_INT_RGB_PQ);
 
-    public static SurfaceData createData(PageFormat pf, long context) {
+    static SurfaceData createData(PageFormat pf, long context) {
         return new CPrinterSurfaceData(CPrinterGraphicsConfig.getConfig(pf), context);
     }
 
-    public CPrinterSurfaceData(GraphicsConfiguration gc, long context) {
+    private CPrinterSurfaceData(GraphicsConfiguration gc, long context) {
         super(IntRgbPQ, gc.getColorModel(), gc, gc.getBounds());
         initOps(context, this.fGraphicsStates, this.fGraphicsStatesObject, gc.getBounds().width, gc.getBounds().height);
     }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CTrayIcon.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CTrayIcon.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 
 import sun.awt.AWTAccessor;
 import sun.awt.SunToolkit;
-import sun.lwawt.macosx.event.NSEvent;
 
 import javax.swing.*;
 import java.awt.*;
@@ -76,8 +75,9 @@
                 menuPeer = (CPopupMenu)popup.getPeer();
                 if (menuPeer == null) {
                     popup.addNotify();
+                    menuPeer = (CPopupMenu)popup.getPeer();
                 }
-            }catch (Exception e){
+            } catch (Exception e) {
                 e.printStackTrace();
             }
         }
@@ -97,7 +97,12 @@
     //invocation from the AWTTrayIcon.m
     public long getPopupMenuModel(){
         if(popup == null) {
-            return 0L;
+            PopupMenu popupMenu = target.getPopupMenu();
+            if (popupMenu != null) {
+                popup = popupMenu;
+            } else {
+                return 0L;
+            }
         }
         return checkAndCreatePopupPeer().getModel();
     }
@@ -134,6 +139,10 @@
 
         dummyFrame.dispose();
 
+        if (popup != null) {
+            popup.removeNotify();
+        }
+
         LWCToolkit.targetDisposedPeer(target, this);
         target = null;
 
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CViewEmbeddedFrame.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,14 +22,17 @@
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
+
+
 package sun.lwawt.macosx;
 
 import java.awt.AWTKeyStroke;
 import java.awt.Toolkit;
 import java.lang.reflect.InvocationTargetException;
+
 import sun.awt.EmbeddedFrame;
-import sun.lwawt.LWToolkit;
 import sun.lwawt.LWWindowPeer;
+
 /*
  * The CViewEmbeddedFrame class is used in the SWT_AWT bridge.
  * This is a part of public API and should not be renamed or moved
@@ -48,7 +51,7 @@
     @Override
     public void addNotify() {
         if (getPeer() == null) {
-            LWToolkit toolkit = (LWToolkit) Toolkit.getDefaultToolkit();
+            LWCToolkit toolkit = (LWCToolkit) Toolkit.getDefaultToolkit();
             setPeer(toolkit.createEmbeddedFrame(this));
         }
         super.addNotify();
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java	Wed Jul 05 19:33:51 2017 +0200
@@ -247,10 +247,7 @@
                             nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
 
                     // do not allow security warning to be obscured by other windows
-                    if (ownerWindow.isAlwaysOnTop()) {
-                        CWrapper.NSWindow.setLevel(nsWindowPtr,
-                                CWrapper.NSWindow.NSFloatingWindowLevel);
-                    }
+                    applyWindowLevel(ownerWindow);
                 }
             }
         }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,73 +25,65 @@
 
 package sun.lwawt.macosx;
 
-import java.awt.geom.Rectangle2D;
-
-public final class CWrapper {
+final class CWrapper {
     private CWrapper() { }
 
-    public static final class NSWindow {
+    static final class NSWindow {
         // NSWindowOrderingMode
-        public static final int NSWindowAbove = 1;
-        public static final int NSWindowBelow = -1;
-        public static final int NSWindowOut = 0;
+        static final int NSWindowAbove = 1;
+        static final int NSWindowBelow = -1;
+        static final int NSWindowOut = 0;
 
         // Window level constants
         // The number of supported levels: (we'll use more in the future)
-        public static final int MAX_WINDOW_LEVELS = 2;
+        static final int MAX_WINDOW_LEVELS = 3;
         // The levels: (these are NOT real constants, these are keys. See native code.)
-        public static final int NSNormalWindowLevel = 0;
-        public static final int NSFloatingWindowLevel = 1;
+        static final int NSNormalWindowLevel = 0;
+        static final int NSFloatingWindowLevel = 1;
+        static final int NSPopUpMenuWindowLevel = 2;
 
         // 'level' is one of the keys defined above
-        public static native void setLevel(long window, int level);
+        static native void setLevel(long window, int level);
 
-        public static native void makeKeyAndOrderFront(long window);
-        public static native void makeKeyWindow(long window);
-        public static native void makeMainWindow(long window);
-        public static native boolean canBecomeMainWindow(long window);
-        public static native boolean isKeyWindow(long window);
+        static native void makeKeyAndOrderFront(long window);
+        static native void makeKeyWindow(long window);
+        static native void makeMainWindow(long window);
+        static native boolean canBecomeMainWindow(long window);
+        static native boolean isKeyWindow(long window);
 
-        public static native void orderFront(long window);
-        public static native void orderFrontRegardless(long window);
-        public static native void orderWindow(long window, int ordered, long relativeTo);
-        public static native void orderOut(long window);
+        static native void orderFront(long window);
+        static native void orderFrontRegardless(long window);
+        static native void orderWindow(long window, int ordered, long relativeTo);
+        static native void orderOut(long window);
 
-        public static native void addChildWindow(long parent, long child, int ordered);
-        public static native void removeChildWindow(long parent, long child);
+        static native void addChildWindow(long parent, long child, int ordered);
+        static native void removeChildWindow(long parent, long child);
 
-        public static native void setFrame(long window, int x, int y, int w, int h, boolean display);
+        static native void setAlphaValue(long window, float alpha);
+        static native void setOpaque(long window, boolean opaque);
+        static native void setBackgroundColor(long window, long color);
 
-        public static native void setAlphaValue(long window, float alpha);
-        public static native void setOpaque(long window, boolean opaque);
-        public static native void setBackgroundColor(long window, long color);
+        static native void miniaturize(long window);
+        static native void deminiaturize(long window);
+        static native boolean isZoomed(long window);
+        static native void zoom(long window);
 
-        public static native void miniaturize(long window);
-        public static native void deminiaturize(long window);
-        public static native boolean isZoomed(long window);
-        public static native void zoom(long window);
-
-        public static native void makeFirstResponder(long window, long responder);
+        static native void makeFirstResponder(long window, long responder);
     }
 
-    public static final class NSView {
-        public static native void addSubview(long view, long subview);
-        public static native void removeFromSuperview(long view);
+    static final class NSView {
+        static native void addSubview(long view, long subview);
+        static native void removeFromSuperview(long view);
 
-        public static native void setFrame(long view, int x, int y, int w, int h);
-        public static native Rectangle2D frame(long view);
-        public static native long window(long view);
+        static native void setFrame(long view, int x, int y, int w, int h);
+        static native long window(long view);
 
-        public static native void setHidden(long view, boolean hidden);
+        static native void setHidden(long view, boolean hidden);
 
-        public static native void setToolTip(long view, String msg);
+        static native void setToolTip(long view, String msg);
     }
 
-    public static final class NSObject {
-        public static native void release(long object);
-    }
-
-    public static final class NSColor {
-        public static native long clearColor();
+    static final class NSColor {
+        static native long clearColor();
     }
 }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,20 +33,25 @@
 import java.awt.event.InvocationEvent;
 import java.awt.event.KeyEvent;
 import java.awt.im.InputMethodHighlight;
+import java.awt.im.spi.InputMethodDescriptor;
 import java.awt.peer.*;
 import java.lang.reflect.*;
+import java.net.URL;
 import java.security.*;
 import java.util.*;
 import java.util.concurrent.Callable;
+import java.net.MalformedURLException;
 
 import sun.awt.*;
+import sun.awt.datatransfer.DataTransferer;
 import sun.lwawt.*;
 import sun.lwawt.LWWindowPeer.PeerType;
 import sun.security.action.GetBooleanAction;
+import sun.awt.image.MultiResolutionImage;
 
 import sun.util.CoreResourceBundleControl;
 
-class NamedCursor extends Cursor {
+final class NamedCursor extends Cursor {
     NamedCursor(String name) {
         super(name);
     }
@@ -72,6 +77,7 @@
 
         ResourceBundle platformResources = java.security.AccessController.doPrivileged(
                 new java.security.PrivilegedAction<ResourceBundle>() {
+            @Override
             public ResourceBundle run() {
                 ResourceBundle platformResources = null;
                 try {
@@ -109,8 +115,6 @@
     private static final boolean inAWT;
 
     public LWCToolkit() {
-        SunToolkit.setDataTransfererClassName("sun.lwawt.macosx.CDataTransferer");
-
         areExtraMouseButtonsEnabled = Boolean.parseBoolean(System.getProperty("sun.awt.enableExtraMouseButtons", "true"));
         //set system property if not yet assigned
         System.setProperty("sun.awt.enableExtraMouseButtons", ""+areExtraMouseButtonsEnabled);
@@ -131,18 +135,20 @@
 
     private native void loadNativeColors(final int[] systemColors, final int[] appleColors);
 
+    @Override
     protected void loadSystemColors(final int[] systemColors) {
         if (systemColors == null) return;
         loadNativeColors(systemColors, appleColors);
     }
 
     private static class AppleSpecificColor extends Color {
-        int index;
-        public AppleSpecificColor(int index) {
+        private final int index;
+        AppleSpecificColor(int index) {
             super(appleColors[index]);
             this.index = index;
         }
 
+        @Override
         public int getRGB() {
             return appleColors[index];
         }
@@ -150,31 +156,19 @@
 
     /**
      * Returns Apple specific colors that we may expose going forward.
-     *
      */
     public static Color getAppleColor(int color) {
         return new AppleSpecificColor(color);
     }
 
+    // This is only called from native code.
     static void systemColorsChanged() {
-        // This is only called from native code.
-        EventQueue.invokeLater(new Runnable() {
-            public void run() {
-                AccessController.doPrivileged (new PrivilegedAction<Object>() {
-                    public Object run() {
-                        try {
-                            final Method updateColorsMethod = SystemColor.class.getDeclaredMethod("updateSystemColors", new Class[0]);
-                            updateColorsMethod.setAccessible(true);
-                            updateColorsMethod.invoke(null, new Object[0]);
-                        } catch (final Throwable e) {
-                            e.printStackTrace();
-                            // swallow this if something goes horribly wrong
-                        }
-                        return null;
-                    }
-                });
-            }
-           });
+        EventQueue.invokeLater(() -> {
+            AccessController.doPrivileged ((PrivilegedAction<Object>) () -> {
+                AWTAccessor.getSystemColorAccessor().updateSystemColors();
+                return null;
+            });
+        });
     }
 
     public static LWCToolkit getLWCToolkit() {
@@ -190,13 +184,44 @@
         } else if (peerType == PeerType.LW_FRAME) {
             return new CPlatformLWWindow();
         } else {
-            assert (peerType == PeerType.SIMPLEWINDOW || peerType == PeerType.DIALOG || peerType == PeerType.FRAME);
+            assert (peerType == PeerType.SIMPLEWINDOW
+                    || peerType == PeerType.DIALOG
+                    || peerType == PeerType.FRAME);
             return new CPlatformWindow();
         }
     }
 
+    LWWindowPeer createEmbeddedFrame(CEmbeddedFrame target) {
+        PlatformComponent platformComponent = createPlatformComponent();
+        PlatformWindow platformWindow = createPlatformWindow(PeerType.EMBEDDED_FRAME);
+        return createDelegatedPeer(target, platformComponent, platformWindow, PeerType.EMBEDDED_FRAME);
+    }
+
+    LWWindowPeer createEmbeddedFrame(CViewEmbeddedFrame target) {
+        PlatformComponent platformComponent = createPlatformComponent();
+        PlatformWindow platformWindow = createPlatformWindow(PeerType.VIEW_EMBEDDED_FRAME);
+        return createDelegatedPeer(target, platformComponent, platformWindow, PeerType.VIEW_EMBEDDED_FRAME);
+    }
+
+    private CPrinterDialogPeer createCPrinterDialog(CPrinterDialog target) {
+        PlatformComponent platformComponent = createPlatformComponent();
+        PlatformWindow platformWindow = createPlatformWindow(PeerType.DIALOG);
+        CPrinterDialogPeer peer = new CPrinterDialogPeer(target, platformComponent, platformWindow);
+        targetCreatedPeer(target, peer);
+        return peer;
+    }
+
     @Override
-    protected SecurityWarningWindow createSecurityWarning(Window ownerWindow, LWWindowPeer ownerPeer) {
+    public DialogPeer createDialog(Dialog target) {
+        if (target instanceof CPrinterDialog) {
+            return createCPrinterDialog((CPrinterDialog)target);
+        }
+        return super.createDialog(target);
+    }
+
+    @Override
+    protected SecurityWarningWindow createSecurityWarning(Window ownerWindow,
+                                                          LWWindowPeer ownerPeer) {
         return new CWarningWindow(ownerWindow, ownerPeer);
     }
 
@@ -248,13 +273,11 @@
         PopupMenuPeer peer = new CPopupMenu(target);
         targetCreatedPeer(target, peer);
         return peer;
-
     }
 
     @Override
     public SystemTrayPeer createSystemTray(SystemTray target) {
-        SystemTrayPeer peer = new CSystemTray();
-        return peer;
+        return new CSystemTray();
     }
 
     @Override
@@ -265,56 +288,63 @@
     }
 
     @Override
+    protected DesktopPeer createDesktopPeer(Desktop target) {
+        return new CDesktopPeer();
+    }
+
+    @Override
     public LWCursorManager getCursorManager() {
         return CCursorManager.getInstance();
     }
 
     @Override
-    public Cursor createCustomCursor(final Image cursor, final Point hotSpot, final String name) throws IndexOutOfBoundsException, HeadlessException {
+    public Cursor createCustomCursor(final Image cursor, final Point hotSpot,
+                                     final String name)
+            throws IndexOutOfBoundsException, HeadlessException {
         return new CCustomCursor(cursor, hotSpot, name);
     }
 
     @Override
-    public Dimension getBestCursorSize(final int preferredWidth, final int preferredHeight) throws HeadlessException {
+    public Dimension getBestCursorSize(final int preferredWidth,
+                                       final int preferredHeight)
+            throws HeadlessException {
         return CCustomCursor.getBestCursorSize(preferredWidth, preferredHeight);
     }
 
     @Override
     protected void platformCleanup() {
         // TODO Auto-generated method stub
-
     }
 
     @Override
     protected void platformInit() {
         // TODO Auto-generated method stub
-
     }
 
     @Override
     protected void platformRunMessage() {
         // TODO Auto-generated method stub
-
     }
 
     @Override
     protected void platformShutdown() {
         // TODO Auto-generated method stub
-
     }
 
     class OSXPlatformFont extends sun.awt.PlatformFont
     {
-        public OSXPlatformFont(String name, int style)
+        OSXPlatformFont(String name, int style)
         {
             super(name, style);
         }
+        @Override
         protected char getMissingGlyphCharacter()
         {
             // Follow up for real implementation
             return (char)0xfff8; // see http://developer.apple.com/fonts/LastResortFont/
         }
     }
+    @Override
     public FontPeer getFontPeer(String name, int style) {
         return new OSXPlatformFont(name, style);
     }
@@ -334,7 +364,7 @@
     @Override
     protected void initializeDesktopProperties() {
         super.initializeDesktopProperties();
-        Map <Object, Object> fontHints = new HashMap<Object, Object>();
+        Map <Object, Object> fontHints = new HashMap<>();
         fontHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
         fontHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
         desktopProperties.put(SunToolkit.DESKTOPFONTHINTS, fontHints);
@@ -355,14 +385,8 @@
         desktopProperties.put("DnD.Cursor.CopyNoDrop", new NamedCursor("DnD.Cursor.CopyNoDrop"));
         desktopProperties.put("DnD.Cursor.MoveNoDrop", new NamedCursor("DnD.Cursor.MoveNoDrop"));
         desktopProperties.put("DnD.Cursor.LinkNoDrop", new NamedCursor("DnD.Cursor.LinkNoDrop"));
-
     }
 
-
-/*
- * The method returns true if some events were processed during that timeout.
- * @see sun.awt.SunToolkit#syncNativeQueue(long)
- */
     @Override
     protected boolean syncNativeQueue(long timeout) {
         return nativeSyncQueue(timeout);
@@ -386,7 +410,6 @@
     @Override
     public void sync() {
         // TODO Auto-generated method stub
-
     }
 
     @Override
@@ -406,6 +429,7 @@
      * as Num Lock on PC keyboards is called Clear, doesn't lock
      * anything and is used for entirely different purpose.
      */
+    @Override
     public boolean getLockingKeyState(int keyCode) throws UnsupportedOperationException {
         switch (keyCode) {
             case KeyEvent.VK_NUM_LOCK:
@@ -425,10 +449,12 @@
     //Set to true by default.
     private static boolean areExtraMouseButtonsEnabled = true;
 
+    @Override
     public boolean areExtraMouseButtonsEnabled() throws HeadlessException {
         return areExtraMouseButtonsEnabled;
     }
 
+    @Override
     public int getNumberOfButtons(){
         return BUTTONS;
     }
@@ -439,6 +465,11 @@
     }
 
     @Override
+    public DataTransferer getDataTransferer() {
+        return CDataTransferer.getInstanceImpl();
+    }
+
+    @Override
     public boolean isAlwaysOnTopSupported() {
         return true;
     }
@@ -482,6 +513,7 @@
      * @see       java.awt.MenuShortcut
      * @since     JDK1.1
      */
+    @Override
     public int getMenuShortcutKeyMask() {
         return Event.META_MASK;
     }
@@ -489,13 +521,34 @@
     @Override
     public Image getImage(final String filename) {
         final Image nsImage = checkForNSImage(filename);
-        if (nsImage != null) return nsImage;
+        if (nsImage != null) {
+            return nsImage;
+        }
 
-        return super.getImage(filename);
+        if (imageCached(filename)) {
+            return super.getImage(filename);
+        }
+
+        String fileneame2x = getScaledImageName(filename);
+        return (imageExists(fileneame2x))
+                ? getImageWithResolutionVariant(filename, fileneame2x)
+                : super.getImage(filename);
     }
 
-    static final String nsImagePrefix = "NSImage://";
-    protected Image checkForNSImage(final String imageName) {
+    @Override
+    public Image getImage(URL url) {
+
+        if (imageCached(url)) {
+            return super.getImage(url);
+        }
+
+        URL url2x = getScaledImageURL(url);
+        return (imageExists(url2x))
+                ? getImageWithResolutionVariant(url, url2x) : super.getImage(url);
+    }
+
+    private static final String nsImagePrefix = "NSImage://";
+    private Image checkForNSImage(final String imageName) {
         if (imageName == null) return null;
         if (!imageName.startsWith(nsImagePrefix)) return null;
         return CImage.getCreator().createImageFromName(imageName.substring(nsImagePrefix.length()));
@@ -514,8 +567,9 @@
         synchronized(ret) { return ret[0]; }
     }
 
-    public static <T> T invokeAndWait(final Callable<T> callable, Component component) throws Exception {
-        final CallableWrapper<T> wrapper = new CallableWrapper<T>(callable);
+    public static <T> T invokeAndWait(final Callable<T> callable,
+                                      Component component) throws Exception {
+        final CallableWrapper<T> wrapper = new CallableWrapper<>(callable);
         invokeAndWait(wrapper, component);
         return wrapper.getResult();
     }
@@ -525,10 +579,11 @@
         T object;
         Exception e;
 
-        public CallableWrapper(final Callable<T> callable) {
+        CallableWrapper(final Callable<T> callable) {
             this.callable = callable;
         }
 
+        @Override
         public void run() {
             try {
                 object = callable.call();
@@ -543,12 +598,16 @@
         }
     }
 
-    // Kicks an event over to the appropriate eventqueue and waits for it to finish
-    // To avoid deadlocking, we manually run the NSRunLoop while waiting
-    // Any selector invoked using ThreadUtilities performOnMainThread will be processed in doAWTRunLoop
-    // The InvocationEvent will call LWCToolkit.stopAWTRunLoop() when finished, which will stop our manual runloop
-    // Does not dispatch native events while in the loop
-    public static void invokeAndWait(Runnable runnable, Component component) throws InvocationTargetException {
+    /**
+     * Kicks an event over to the appropriate eventqueue and waits for it to
+     * finish To avoid deadlocking, we manually run the NSRunLoop while waiting
+     * Any selector invoked using ThreadUtilities performOnMainThread will be
+     * processed in doAWTRunLoop The InvocationEvent will call
+     * LWCToolkit.stopAWTRunLoop() when finished, which will stop our manual
+     * runloop Does not dispatch native events while in the loop
+     */
+    public static void invokeAndWait(Runnable runnable, Component component)
+            throws InvocationTargetException {
         final long mediator = createAWTRunLoopMediator();
 
         InvocationEvent invocationEvent =
@@ -583,7 +642,8 @@
         }
     }
 
-    public static void invokeLater(Runnable event, Component component) throws InvocationTargetException {
+    public static void invokeLater(Runnable event, Component component)
+            throws InvocationTargetException {
         final InvocationEvent invocationEvent =
                 new InvocationEvent(component != null ? component : Toolkit.getDefaultToolkit(), event);
 
@@ -612,16 +672,18 @@
         return getSystemEventQueueImpl();
     }
 
-
 // DnD support
 
-    public DragSourceContextPeer createDragSourceContextPeer(DragGestureEvent dge) throws InvalidDnDOperationException {
-        DragSourceContextPeer dscp = CDragSourceContextPeer.createDragSourceContextPeer(dge);
-
-        return dscp;
+    @Override
+    public DragSourceContextPeer createDragSourceContextPeer(
+            DragGestureEvent dge) throws InvalidDnDOperationException {
+        return CDragSourceContextPeer.createDragSourceContextPeer(dge);
     }
 
-    public <T extends DragGestureRecognizer> T createDragGestureRecognizer(Class<T> abstractRecognizerClass, DragSource ds, Component c, int srcActions, DragGestureListener dgl) {
+    @Override
+    public <T extends DragGestureRecognizer> T createDragGestureRecognizer(
+            Class<T> abstractRecognizerClass, DragSource ds, Component c,
+            int srcActions, DragGestureListener dgl) {
         DragGestureRecognizer dgr = null;
 
         // Create a new mouse drag gesture recognizer if we have a class match:
@@ -635,6 +697,7 @@
     /**
      * Returns the default keyboard locale of the underlying operating system
      */
+    @Override
     public Locale getDefaultKeyboardLocale() {
         Locale locale = CInputMethod.getNativeLocale();
 
@@ -645,7 +708,8 @@
         return locale;
     }
 
-    public java.awt.im.spi.InputMethodDescriptor getInputMethodAdapterDescriptor() {
+    @Override
+    public InputMethodDescriptor getInputMethodAdapterDescriptor() {
         if (sInputMethodDescriptor == null)
             sInputMethodDescriptor = new CInputMethodDescriptor();
 
@@ -661,12 +725,14 @@
      * @return style attribute map, or null
      * @since 1.3
      */
+    @Override
     public Map mapInputMethodHighlight(InputMethodHighlight highlight) {
         return CInputMethod.mapInputMethodHighlight(highlight);
     }
 
     /**
-     * Returns key modifiers used by Swing to set up a focus accelerator key stroke.
+     * Returns key modifiers used by Swing to set up a focus accelerator key
+     * stroke.
      */
     @Override
     public int getFocusAcceleratorKeyMask() {
@@ -674,8 +740,8 @@
     }
 
     /**
-     * Tests whether specified key modifiers mask can be used to enter a printable
-     * character.
+     * Tests whether specified key modifiers mask can be used to enter a
+     * printable character.
      */
     @Override
     public boolean isPrintableCharacterModifiersMask(int mods) {
@@ -696,19 +762,18 @@
      * Returns the value of "sun.awt.disableCALayers" property. Default
      * value is {@code false}.
      */
-    public synchronized static boolean getSunAwtDisableCALayers() {
+    public static synchronized boolean getSunAwtDisableCALayers() {
         if (sunAwtDisableCALayers == null) {
             sunAwtDisableCALayers = AccessController.doPrivileged(
                 new GetBooleanAction("sun.awt.disableCALayers"));
         }
-        return sunAwtDisableCALayers.booleanValue();
+        return sunAwtDisableCALayers;
     }
 
-
     /*
      * Returns true if the application (one of its windows) owns keyboard focus.
      */
-    public native boolean isApplicationActive();
+    native boolean isApplicationActive();
 
     /************************
      * Native methods section
@@ -729,7 +794,7 @@
     static void doAWTRunLoop(long mediator, boolean processEvents) {
         doAWTRunLoopImpl(mediator, processEvents, inAWT);
     }
-    static private native void doAWTRunLoopImpl(long mediator, boolean processEvents, boolean inAWT);
+    private static native void doAWTRunLoopImpl(long mediator, boolean processEvents, boolean inAWT);
     static native void stopAWTRunLoop(long mediator);
 
     private native boolean nativeSyncQueue(long timeout);
@@ -773,6 +838,7 @@
         return true;
     }
 
+    @Override
     public boolean isSwingBackbufferTranslucencySupported() {
         return true;
     }
@@ -781,4 +847,36 @@
     public boolean enableInputMethodsForTextComponent() {
         return true;
     }
+
+    private static URL getScaledImageURL(URL url) {
+        try {
+            String scaledImagePath = getScaledImageName(url.getPath());
+            return scaledImagePath == null ? null : new URL(url.getProtocol(),
+                    url.getHost(), url.getPort(), scaledImagePath);
+        } catch (MalformedURLException e) {
+            return null;
+        }
+    }
+
+    private static String getScaledImageName(String path) {
+        if (!isValidPath(path)) {
+            return null;
+        }
+
+        int slash = path.lastIndexOf('/');
+        String name = (slash < 0) ? path : path.substring(slash + 1);
+
+        if (name.contains("@2x")) {
+            return null;
+        }
+
+        int dot = name.lastIndexOf('.');
+        String name2x = (dot < 0) ? name + "@2x"
+                : name.substring(0, dot) + "@2x" + name.substring(dot);
+        return (slash < 0) ? name2x : path.substring(0, slash + 1) + name2x;
+    }
+
+    private static boolean isValidPath(String path) {
+        return !path.isEmpty() && !path.endsWith("/") && !path.endsWith(".");
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,261 @@
+/*
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.lwawt.macosx;
+
+import java.awt.event.*;
+
+/**
+ * A class representing Cocoa NSEvent class with the fields only necessary for
+ * JDK functionality.
+ */
+final class NSEvent {
+    private int type;
+    private int modifierFlags;
+
+    // Mouse event information
+    private int clickCount;
+    private int buttonNumber;
+    private int x;
+    private int y;
+    private double scrollDeltaY;
+    private double scrollDeltaX;
+    private int absX;
+    private int absY;
+
+    // Key event information
+    private short keyCode;
+    private String charactersIgnoringModifiers;
+
+    // Called from native
+    NSEvent(int type, int modifierFlags, short keyCode, String charactersIgnoringModifiers) {
+        this.type = type;
+        this.modifierFlags = modifierFlags;
+        this.keyCode = keyCode;
+        this.charactersIgnoringModifiers = charactersIgnoringModifiers;
+    }
+
+    // Called from native
+    NSEvent(int type, int modifierFlags, int clickCount, int buttonNumber,
+                   int x, int y, int absX, int absY,
+                   double scrollDeltaY, double scrollDeltaX) {
+        this.type = type;
+        this.modifierFlags = modifierFlags;
+        this.clickCount = clickCount;
+        this.buttonNumber = buttonNumber;
+        this.x = x;
+        this.y = y;
+        this.absX = absX;
+        this.absY = absY;
+        this.scrollDeltaY = scrollDeltaY;
+        this.scrollDeltaX = scrollDeltaX;
+    }
+
+    int getType() {
+        return type;
+    }
+
+    int getModifierFlags() {
+        return modifierFlags;
+    }
+
+    int getClickCount() {
+        return clickCount;
+    }
+
+    int getButtonNumber() {
+        return buttonNumber;
+    }
+
+    int getX() {
+        return x;
+    }
+
+    int getY() {
+        return y;
+    }
+
+    double getScrollDeltaY() {
+        return scrollDeltaY;
+    }
+
+    double getScrollDeltaX() {
+        return scrollDeltaX;
+    }
+
+    int getAbsX() {
+        return absX;
+    }
+
+    int getAbsY() {
+        return absY;
+    }
+
+    short getKeyCode() {
+        return keyCode;
+    }
+
+    String getCharactersIgnoringModifiers() {
+        return charactersIgnoringModifiers;
+    }
+
+    @Override
+    public String toString() {
+        return "NSEvent[" + getType() + " ," + getModifierFlags() + " ,"
+                + getClickCount() + " ," + getButtonNumber() + " ," + getX() + " ,"
+                + getY() + " ," + getAbsX() + " ," + getAbsY()+ " ," + getKeyCode() + " ,"
+                + getCharactersIgnoringModifiers() + "]";
+    }
+
+    /*
+     * Converts an NSEvent button number to a MouseEvent constant.
+     */
+    static int nsToJavaButton(int buttonNumber) {
+        int jbuttonNumber = buttonNumber + 1;
+        switch (buttonNumber) {
+            case CocoaConstants.kCGMouseButtonLeft:
+                jbuttonNumber = MouseEvent.BUTTON1;
+                break;
+            case CocoaConstants.kCGMouseButtonRight:
+                jbuttonNumber = MouseEvent.BUTTON3;
+                break;
+            case CocoaConstants.kCGMouseButtonCenter:
+                jbuttonNumber = MouseEvent.BUTTON2;
+                break;
+        }
+        return jbuttonNumber;
+    }
+
+    /*
+     * Converts NPCocoaEvent types to AWT event types.
+     */
+    static int npToJavaEventType(int npEventType) {
+        int jeventType = 0;
+        switch (npEventType) {
+            case CocoaConstants.NPCocoaEventMouseDown:
+                jeventType = MouseEvent.MOUSE_PRESSED;
+                break;
+            case CocoaConstants.NPCocoaEventMouseUp:
+                jeventType = MouseEvent.MOUSE_RELEASED;
+                break;
+            case CocoaConstants.NPCocoaEventMouseMoved:
+                jeventType = MouseEvent.MOUSE_MOVED;
+                break;
+            case CocoaConstants.NPCocoaEventMouseEntered:
+                jeventType = MouseEvent.MOUSE_ENTERED;
+                break;
+            case CocoaConstants.NPCocoaEventMouseExited:
+                jeventType = MouseEvent.MOUSE_EXITED;
+                break;
+            case CocoaConstants.NPCocoaEventMouseDragged:
+                jeventType = MouseEvent.MOUSE_DRAGGED;
+                break;
+            case CocoaConstants.NPCocoaEventKeyDown:
+                jeventType = KeyEvent.KEY_PRESSED;
+                break;
+            case CocoaConstants.NPCocoaEventKeyUp:
+                jeventType = KeyEvent.KEY_RELEASED;
+                break;
+        }
+        return jeventType;
+    }
+
+    /*
+     * Converts NSEvent types to AWT event types.
+     */
+    static int nsToJavaEventType(int nsEventType) {
+        int jeventType = 0;
+        switch (nsEventType) {
+            case CocoaConstants.NSLeftMouseDown:
+            case CocoaConstants.NSRightMouseDown:
+            case CocoaConstants.NSOtherMouseDown:
+                jeventType = MouseEvent.MOUSE_PRESSED;
+                break;
+            case CocoaConstants.NSLeftMouseUp:
+            case CocoaConstants.NSRightMouseUp:
+            case CocoaConstants.NSOtherMouseUp:
+                jeventType = MouseEvent.MOUSE_RELEASED;
+                break;
+            case CocoaConstants.NSMouseMoved:
+                jeventType = MouseEvent.MOUSE_MOVED;
+                break;
+            case CocoaConstants.NSLeftMouseDragged:
+            case CocoaConstants.NSRightMouseDragged:
+            case CocoaConstants.NSOtherMouseDragged:
+                jeventType = MouseEvent.MOUSE_DRAGGED;
+                break;
+            case CocoaConstants.NSMouseEntered:
+                jeventType = MouseEvent.MOUSE_ENTERED;
+                break;
+            case CocoaConstants.NSMouseExited:
+                jeventType = MouseEvent.MOUSE_EXITED;
+                break;
+            case CocoaConstants.NSScrollWheel:
+                jeventType = MouseEvent.MOUSE_WHEEL;
+                break;
+            case CocoaConstants.NSKeyDown:
+                jeventType = KeyEvent.KEY_PRESSED;
+                break;
+            case CocoaConstants.NSKeyUp:
+                jeventType = KeyEvent.KEY_RELEASED;
+                break;
+        }
+        return jeventType;
+    }
+
+    /*
+     * Converts NSEvent mouse modifiers to AWT mouse modifiers.
+     */
+    static native int nsToJavaMouseModifiers(int buttonNumber,
+                                                    int modifierFlags);
+
+    /*
+     * Converts NSEvent key modifiers to AWT key modifiers.
+     */
+    static native int nsToJavaKeyModifiers(int modifierFlags);
+
+    /*
+     * Converts NSEvent key info to AWT key info.
+     */
+    static native boolean nsToJavaKeyInfo(int[] in, int[] out);
+
+    /*
+     * Converts NSEvent key modifiers to AWT key info.
+     */
+    static native void nsKeyModifiersToJavaKeyInfo(int[] in, int[] out);
+
+    /*
+     * There is a small number of NS characters that need to be converted
+     * into other characters before we pass them to AWT.
+     */
+    static native char nsToJavaChar(char nsChar, int modifierFlags);
+
+    static boolean isPopupTrigger(int jmodifiers) {
+        final boolean isRightButtonDown = ((jmodifiers & InputEvent.BUTTON3_DOWN_MASK) != 0);
+        final boolean isLeftButtonDown = ((jmodifiers & InputEvent.BUTTON1_DOWN_MASK) != 0);
+        final boolean isControlDown = ((jmodifiers & InputEvent.CTRL_DOWN_MASK) != 0);
+        return isRightButtonDown || (isControlDown && isLeftButtonDown);
+    }
+}
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/event/NSEvent.java	Tue Mar 25 12:31:49 2014 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,260 +0,0 @@
-/*
- * Copyright (c) 2011, 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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.lwawt.macosx.event;
-
-import sun.lwawt.macosx.CocoaConstants;
-import java.awt.event.*;
-
-/**
- * A class representing Cocoa NSEvent class with the fields only necessary for
- * JDK functionality.
- */
-public final class NSEvent {
-    private int type;
-    private int modifierFlags;
-
-    // Mouse event information
-    private int clickCount;
-    private int buttonNumber;
-    private int x;
-    private int y;
-    private double scrollDeltaY;
-    private double scrollDeltaX;
-    private int absX;
-    private int absY;
-
-    // Key event information
-    private short keyCode;
-    private String charactersIgnoringModifiers;
-
-    public NSEvent(int type, int modifierFlags, short keyCode, String charactersIgnoringModifiers) {
-        this.type = type;
-        this.modifierFlags = modifierFlags;
-        this.keyCode = keyCode;
-        this.charactersIgnoringModifiers = charactersIgnoringModifiers;
-    }
-
-    public NSEvent(int type, int modifierFlags, int clickCount, int buttonNumber,
-                   int x, int y, int absX, int absY,
-                   double scrollDeltaY, double scrollDeltaX) {
-        this.type = type;
-        this.modifierFlags = modifierFlags;
-        this.clickCount = clickCount;
-        this.buttonNumber = buttonNumber;
-        this.x = x;
-        this.y = y;
-        this.absX = absX;
-        this.absY = absY;
-        this.scrollDeltaY = scrollDeltaY;
-        this.scrollDeltaX = scrollDeltaX;
-    }
-
-    public int getType() {
-        return type;
-    }
-
-    public int getModifierFlags() {
-        return modifierFlags;
-    }
-
-    public int getClickCount() {
-        return clickCount;
-    }
-
-    public int getButtonNumber() {
-        return buttonNumber;
-    }
-
-    public int getX() {
-        return x;
-    }
-
-    public int getY() {
-        return y;
-    }
-
-    public double getScrollDeltaY() {
-        return scrollDeltaY;
-    }
-
-    public double getScrollDeltaX() {
-        return scrollDeltaX;
-    }
-
-    public int getAbsX() {
-        return absX;
-    }
-
-    public int getAbsY() {
-        return absY;
-    }
-
-    public short getKeyCode() {
-        return keyCode;
-    }
-
-    public String getCharactersIgnoringModifiers() {
-        return charactersIgnoringModifiers;
-    }
-
-    @Override
-    public String toString() {
-        return "NSEvent[" + getType() + " ," + getModifierFlags() + " ,"
-                + getClickCount() + " ," + getButtonNumber() + " ," + getX() + " ,"
-                + getY() + " ," + getAbsX() + " ," + getAbsY()+ " ," + getKeyCode() + " ,"
-                + getCharactersIgnoringModifiers() + "]";
-    }
-
-    /*
-     * Converts an NSEvent button number to a MouseEvent constant.
-     */
-    public static int nsToJavaButton(int buttonNumber) {
-        int jbuttonNumber = buttonNumber + 1;
-        switch (buttonNumber) {
-            case CocoaConstants.kCGMouseButtonLeft:
-                jbuttonNumber = MouseEvent.BUTTON1;
-                break;
-            case CocoaConstants.kCGMouseButtonRight:
-                jbuttonNumber = MouseEvent.BUTTON3;
-                break;
-            case CocoaConstants.kCGMouseButtonCenter:
-                jbuttonNumber = MouseEvent.BUTTON2;
-                break;
-        }
-        return jbuttonNumber;
-    }
-
-    /*
-     * Converts NPCocoaEvent types to AWT event types.
-     */
-    public static int npToJavaEventType(int npEventType) {
-        int jeventType = 0;
-        switch (npEventType) {
-            case CocoaConstants.NPCocoaEventMouseDown:
-                jeventType = MouseEvent.MOUSE_PRESSED;
-                break;
-            case CocoaConstants.NPCocoaEventMouseUp:
-                jeventType = MouseEvent.MOUSE_RELEASED;
-                break;
-            case CocoaConstants.NPCocoaEventMouseMoved:
-                jeventType = MouseEvent.MOUSE_MOVED;
-                break;
-            case CocoaConstants.NPCocoaEventMouseEntered:
-                jeventType = MouseEvent.MOUSE_ENTERED;
-                break;
-            case CocoaConstants.NPCocoaEventMouseExited:
-                jeventType = MouseEvent.MOUSE_EXITED;
-                break;
-            case CocoaConstants.NPCocoaEventMouseDragged:
-                jeventType = MouseEvent.MOUSE_DRAGGED;
-                break;
-            case CocoaConstants.NPCocoaEventKeyDown:
-                jeventType = KeyEvent.KEY_PRESSED;
-                break;
-            case CocoaConstants.NPCocoaEventKeyUp:
-                jeventType = KeyEvent.KEY_RELEASED;
-                break;
-        }
-        return jeventType;
-    }
-
-    /*
-     * Converts NSEvent types to AWT event types.
-     */
-    public static int nsToJavaEventType(int nsEventType) {
-        int jeventType = 0;
-        switch (nsEventType) {
-            case CocoaConstants.NSLeftMouseDown:
-            case CocoaConstants.NSRightMouseDown:
-            case CocoaConstants.NSOtherMouseDown:
-                jeventType = MouseEvent.MOUSE_PRESSED;
-                break;
-            case CocoaConstants.NSLeftMouseUp:
-            case CocoaConstants.NSRightMouseUp:
-            case CocoaConstants.NSOtherMouseUp:
-                jeventType = MouseEvent.MOUSE_RELEASED;
-                break;
-            case CocoaConstants.NSMouseMoved:
-                jeventType = MouseEvent.MOUSE_MOVED;
-                break;
-            case CocoaConstants.NSLeftMouseDragged:
-            case CocoaConstants.NSRightMouseDragged:
-            case CocoaConstants.NSOtherMouseDragged:
-                jeventType = MouseEvent.MOUSE_DRAGGED;
-                break;
-            case CocoaConstants.NSMouseEntered:
-                jeventType = MouseEvent.MOUSE_ENTERED;
-                break;
-            case CocoaConstants.NSMouseExited:
-                jeventType = MouseEvent.MOUSE_EXITED;
-                break;
-            case CocoaConstants.NSScrollWheel:
-                jeventType = MouseEvent.MOUSE_WHEEL;
-                break;
-            case CocoaConstants.NSKeyDown:
-                jeventType = KeyEvent.KEY_PRESSED;
-                break;
-            case CocoaConstants.NSKeyUp:
-                jeventType = KeyEvent.KEY_RELEASED;
-                break;
-        }
-        return jeventType;
-    }
-
-    /*
-     * Converts NSEvent mouse modifiers to AWT mouse modifiers.
-     */
-    public static native int nsToJavaMouseModifiers(int buttonNumber,
-                                                    int modifierFlags);
-
-    /*
-     * Converts NSEvent key modifiers to AWT key modifiers.
-     */
-    public static native int nsToJavaKeyModifiers(int modifierFlags);
-
-    /*
-     * Converts NSEvent key info to AWT key info.
-     */
-    public static native boolean nsToJavaKeyInfo(int[] in, int[] out);
-
-    /*
-     * Converts NSEvent key modifiers to AWT key info.
-     */
-    public static native void nsKeyModifiersToJavaKeyInfo(int[] in, int[] out);
-
-    /*
-     * There is a small number of NS characters that need to be converted
-     * into other characters before we pass them to AWT.
-     */
-    public static native char nsToJavaChar(char nsChar, int modifierFlags);
-
-    public static boolean isPopupTrigger(int jmodifiers) {
-        final boolean isRightButtonDown = ((jmodifiers & InputEvent.BUTTON3_DOWN_MASK) != 0);
-        final boolean isLeftButtonDown = ((jmodifiers & InputEvent.BUTTON1_DOWN_MASK) != 0);
-        final boolean isControlDown = ((jmodifiers & InputEvent.CTRL_DOWN_MASK) != 0);
-        return isRightButtonDown || (isControlDown && isLeftButtonDown);
-    }
-}
--- a/jdk/src/macosx/lib/flavormap.properties	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/lib/flavormap.properties	Wed Jul 05 19:33:51 2017 +0200
@@ -79,3 +79,5 @@
 TIFF=image/x-java-image;class=java.awt.Image
 RICH_TEXT=text/rtf
 HTML=text/html;charset=utf-8;eoln="\r\n";terminators=1
+URL=application/x-java-url;class=java.net.URL
+URL=text/uri-list;eoln="\r\n";terminators=1
--- a/jdk/src/macosx/native/com/apple/laf/AquaFileView.m	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/com/apple/laf/AquaFileView.m	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,9 @@
  * questions.
  */
 
+
+#include <jni_util.h>
+
 #import "com_apple_laf_AquaFileView.h"
 
 #import <sys/param.h> // for MAXPATHLEN
@@ -98,6 +101,7 @@
 JNF_COCOA_ENTER(env);
 
     jbyte *byteArray = (*env)->GetByteArrayElements(env, absolutePath, NULL);
+    CHECK_NULL_RETURN(byteArray, returnValue);
     jsize length = (*env)->GetArrayLength(env, absolutePath);
 
     // Can't assume that byteArray is NULL terminated and FSPathMakeRef doesn't
@@ -138,6 +142,7 @@
 JNF_COCOA_ENTER(env);
 
     jbyte *byteArray = (*env)->GetByteArrayElements(env, absolutePath, NULL);
+    CHECK_NULL_RETURN(byteArray, returnValue);
     jsize length = (*env)->GetArrayLength(env, absolutePath);
 
     // Can't assume that byteArray is NULL terminated and FSPathMakeRef doesn't
@@ -153,7 +158,9 @@
     Boolean isDirectory = (isDir == JNI_TRUE ? true : false);
     FSRef ref;
 
-    OSErr theErr = FSPathMakeRefWithOptions((const UInt8 *)&arrayCopy, kFSPathMakeRefDoNotFollowLeafSymlink, &ref, &isDirectory);
+    OSErr theErr = FSPathMakeRefWithOptions((const UInt8 *)&arrayCopy,
+                                            kFSPathMakeRefDoNotFollowLeafSymlink,
+                                            &ref, &isDirectory);
     if (theErr == noErr) {
         CFStringRef displayName = NULL;
 
@@ -190,6 +197,7 @@
     size_t maxPathLen = sizeof(pathCString) - 1;
 
     jbyte *byteArray = (*env)->GetByteArrayElements(env, pathToAlias, NULL);
+    CHECK_NULL_RETURN(byteArray, returnValue);
     jsize length = (*env)->GetArrayLength(env, pathToAlias);
 
     if (length > maxPathLen) {
@@ -205,7 +213,8 @@
     OSErr theErr = FSPathMakeRef(pathCString, &fileRef, &isDirectory);
 
     Boolean ignored;
-    theErr = FSResolveAliasFileWithMountFlags(&fileRef, false, &ignored, &ignored, kResolveAliasFileNoUI);
+    theErr = FSResolveAliasFileWithMountFlags(&fileRef, false, &ignored,
+                                              &ignored, kResolveAliasFileNoUI);
     if (theErr == noErr) {
         UInt8 resolvedPath[MAXPATHLEN];
         theErr = FSRefMakePath(&fileRef, resolvedPath, MAXPATHLEN);
--- a/jdk/src/macosx/native/sun/awt/AWTEvent.m	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/AWTEvent.m	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -633,12 +633,12 @@
 }
 
 /*
- * Class:     sun_lwawt_macosx_event_NSEvent
+ * Class:     sun_lwawt_macosx_NSEvent
  * Method:    nsToJavaMouseModifiers
  * Signature: (II)I
  */
 JNIEXPORT jint JNICALL
-Java_sun_lwawt_macosx_event_NSEvent_nsToJavaMouseModifiers
+Java_sun_lwawt_macosx_NSEvent_nsToJavaMouseModifiers
 (JNIEnv *env, jclass cls, jint buttonNumber, jint modifierFlags)
 {
     jint jmodifiers = 0;
@@ -653,12 +653,12 @@
 }
 
 /*
- * Class:     sun_lwawt_macosx_event_NSEvent
+ * Class:     sun_lwawt_macosx_NSEvent
  * Method:    nsToJavaKeyModifiers
  * Signature: (I)I
  */
 JNIEXPORT jint JNICALL
-Java_sun_lwawt_macosx_event_NSEvent_nsToJavaKeyModifiers
+Java_sun_lwawt_macosx_NSEvent_nsToJavaKeyModifiers
 (JNIEnv *env, jclass cls, jint modifierFlags)
 {
     jint jmodifiers = 0;
@@ -673,12 +673,12 @@
 }
 
 /*
- * Class:     sun_lwawt_macosx_event_NSEvent
+ * Class:     sun_lwawt_macosx_NSEvent
  * Method:    nsToJavaKeyInfo
  * Signature: ([I[I)Z
  */
 JNIEXPORT jboolean JNICALL
-Java_sun_lwawt_macosx_event_NSEvent_nsToJavaKeyInfo
+Java_sun_lwawt_macosx_NSEvent_nsToJavaKeyInfo
 (JNIEnv *env, jclass cls, jintArray inData, jintArray outData)
 {
     BOOL postsTyped = NO;
@@ -715,12 +715,12 @@
 }
 
 /*
- * Class:     sun_lwawt_macosx_event_NSEvent
+ * Class:     sun_lwawt_macosx_NSEvent
  * Method:    nsKeyModifiersToJavaKeyInfo
  * Signature: ([I[I)V
  */
 JNIEXPORT void JNICALL
-Java_sun_lwawt_macosx_event_NSEvent_nsKeyModifiersToJavaKeyInfo
+Java_sun_lwawt_macosx_NSEvent_nsKeyModifiersToJavaKeyInfo
 (JNIEnv *env, jclass cls, jintArray inData, jintArray outData)
 {
 JNF_COCOA_ENTER(env);
@@ -753,12 +753,12 @@
 }
 
 /*
- * Class:     sun_lwawt_macosx_event_NSEvent
+ * Class:     sun_lwawt_macosx_NSEvent
  * Method:    nsToJavaChar
  * Signature: (CI)C
  */
 JNIEXPORT jint JNICALL
-Java_sun_lwawt_macosx_event_NSEvent_nsToJavaChar
+Java_sun_lwawt_macosx_NSEvent_nsToJavaChar
 (JNIEnv *env, jclass cls, jchar nsChar, jint modifierFlags)
 {
     jchar javaChar = 0;
--- a/jdk/src/macosx/native/sun/awt/AWTView.h	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/AWTView.h	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +29,7 @@
 #import "CDragSource.h"
 #import "CDropTarget.h"
 
-@interface AWTView : NSView<NSTextInputClient> {
+@interface AWTView : NSView<NSTextInputClient, CDragSourceHolder, CDropTargetHolder> {
 @private
     jobject m_cPlatformView;
 
@@ -61,14 +61,8 @@
 
 - (id) initWithRect:(NSRect) rect platformView:(jobject)cPlatformView windowLayer:(CALayer*)windowLayer;
 - (void) deliverJavaMouseEvent: (NSEvent *) event;
-- (void) resetTrackingArea;
-- (void) deliverJavaKeyEventHelper: (NSEvent *) event;
 - (jobject) awtComponent:(JNIEnv *)env;
 
-- (void) setDragSource:(CDragSource *)source;
-- (void) setDropTarget:(CDropTarget *)target;
-
-
 // Input method-related events
 - (void)setInputMethod:(jobject)inputMethod;
 - (void)abandonInput;
--- a/jdk/src/macosx/native/sun/awt/AWTView.m	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/AWTView.m	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,10 @@
 @interface AWTView()
 @property (retain) CDropTarget *_dropTarget;
 @property (retain) CDragSource *_dragSource;
+
+-(void) deliverResize: (NSRect) rect;
+-(void) resetTrackingArea;
+-(void) deliverJavaKeyEventHelper: (NSEvent*) event;
 @end
 
 // Uncomment this line to see fprintfs of each InputMethod API being called on this View
@@ -363,7 +367,7 @@
     // TODO: need consitent way for doing that both with global as well as with local coordinates.
     // The reason to do it here is one more native method for getting screen dimension otherwise.
 
-    NSRect screenRect = [[NSScreen mainScreen] frame];
+    NSRect screenRect = [[[NSScreen screens] objectAtIndex:0] frame];
     absP.y = screenRect.size.height - absP.y;
     jint clickCount;
 
@@ -376,7 +380,7 @@
         clickCount = [event clickCount];
     }
 
-    static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/event/NSEvent");
+    static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent");
     static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IIIIIIIIDD)V");
     jobject jEvent = JNFNewObject(env, jctor_NSEvent,
                                   [event type],
@@ -393,7 +397,7 @@
     }
 
     static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView");
-    static JNF_MEMBER_CACHE(jm_deliverMouseEvent, jc_PlatformView, "deliverMouseEvent", "(Lsun/lwawt/macosx/event/NSEvent;)V");
+    static JNF_MEMBER_CACHE(jm_deliverMouseEvent, jc_PlatformView, "deliverMouseEvent", "(Lsun/lwawt/macosx/NSEvent;)V");
     JNFCallVoidMethod(env, m_cPlatformView, jm_deliverMouseEvent, jEvent);
 }
 
@@ -441,7 +445,7 @@
         characters = JNFNSToJavaString(env, [event characters]);
     }
 
-    static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/event/NSEvent");
+    static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent");
     static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IISLjava/lang/String;)V");
     jobject jevent = JNFNewObject(env, jctor_NSEvent,
                                   [event type],
@@ -451,7 +455,7 @@
 
     static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView");
     static JNF_MEMBER_CACHE(jm_deliverKeyEvent, jc_PlatformView,
-                            "deliverKeyEvent", "(Lsun/lwawt/macosx/event/NSEvent;)V");
+                            "deliverKeyEvent", "(Lsun/lwawt/macosx/NSEvent;)V");
     JNFCallVoidMethod(env, m_cPlatformView, jm_deliverKeyEvent, jevent);
 
     if (characters != NULL) {
--- a/jdk/src/macosx/native/sun/awt/CDataTransferer.m	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/CDataTransferer.m	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 
 #import <AppKit/AppKit.h>
 #import <JavaNativeFoundation/JavaNativeFoundation.h>
+#import "jni_util.h"
 
 #include "ThreadUtilities.h"
 
@@ -172,7 +173,9 @@
         NSData *tiffImage = [imageRep TIFFRepresentation];
         jsize tiffSize = (jsize)[tiffImage length]; // #warning 64-bit: -length returns NSUInteger, but NewByteArray takes jsize
         returnValue = (*env)->NewByteArray(env, tiffSize);
+        CHECK_NULL_RETURN(returnValue, nil);
         jbyte *tiffData = (jbyte *)(*env)->GetPrimitiveArrayCritical(env, returnValue, 0);
+        CHECK_NULL_RETURN(tiffData, nil);
         [tiffImage getBytes:tiffData];
         (*env)->ReleasePrimitiveArrayCritical(env, returnValue, tiffData, 0); // Do not use JNI_COMMIT, as that will not free the buffer copy when +ProtectJavaHeap is on.
         [imageRep release];
@@ -184,12 +187,13 @@
 
 static jobject getImageForByteStream(JNIEnv *env, jbyteArray sourceData)
 {
-    if (sourceData == NULL) return NULL;
+    CHECK_NULL_RETURN(sourceData, NULL);
 
     jsize sourceSize = (*env)->GetArrayLength(env, sourceData);
     if (sourceSize == 0) return NULL;
 
     jbyte *sourceBytes = (*env)->GetPrimitiveArrayCritical(env, sourceData, NULL);
+    CHECK_NULL_RETURN(sourceBytes, NULL);
     NSData *rawData = [NSData dataWithBytes:sourceBytes length:sourceSize];
 
     NSImage *newImage = [[NSImage alloc] initWithData:rawData];
@@ -197,8 +201,7 @@
     [newImage release];
 
     (*env)->ReleasePrimitiveArrayCritical(env, sourceData, sourceBytes, JNI_ABORT);
-
-    if (newImage == nil) return NULL;
+    CHECK_NULL_RETURN(newImage, NULL);
 
     // The ownership of the NSImage is passed to the new CImage jobject. No need to release it.
     static JNF_CLASS_CACHE(jc_CImage, "sun/lwawt/macosx/CImage");
@@ -231,7 +234,8 @@
     if (filenameCount == 0) return nil;
 
     // Get the java.lang.String class object:
-    jclass stringClazz = (*env)->FindClass(env, "java/lang/String"); // can't be null
+    jclass stringClazz = (*env)->FindClass(env, "java/lang/String");
+    CHECK_NULL_RETURN(stringClazz, nil);
     jobject jfilenameArray = (*env)->NewObjectArray(env, filenameCount, stringClazz, NULL); // AWT_THREADING Safe (known object)
     if ((*env)->ExceptionOccurred(env)) {
         (*env)->ExceptionDescribe(env);
--- a/jdk/src/macosx/native/sun/awt/CDragSource.h	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/CDragSource.h	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,9 +29,15 @@
 #import <Cocoa/Cocoa.h>
 #include <jni.h>
 
+@class CDragSource;
+
+@protocol CDragSourceHolder
+- (void) setDragSource:(CDragSource *)source;
+@end
+
 @interface CDragSource : NSObject {
 @private
-    NSView*        fView;
+    NSView<CDragSourceHolder>* fView;
     jobject            fComponent;
     jobject            fDragSourceContextPeer;
 
@@ -53,8 +59,6 @@
     jint                     fDragMouseModifiers;
 }
 
-+ (CDragSource *) currentDragSource;
-
 // Common methods:
 - (id)        init:(jobject)jDragSourceContextPeer
          component:(jobject)jComponent
@@ -66,7 +70,7 @@
          modifiers:(jint)extModifiers
         clickCount:(jint)clickCount
          timeStamp:(jlong)timeStamp
-         dragImage:(jobject)jDragImage
+         dragImage:(jlong)nsDragImagePtr
   dragImageOffsetX:(jint)jDragImageOffsetX
   dragImageOffsetY:(jint)jDragImageOffsetY
      sourceActions:(jint)jSourceActions
@@ -84,13 +88,6 @@
 - (void)draggedImage:(NSImage *)image movedTo:(NSPoint)screenPoint;
 - (BOOL)ignoreModifierKeysWhileDragging;
 
-// Updates from the destination to the source
-- (void) postDragEnter;
-- (void) postDragExit;
-
-// Utility
-- (NSPoint) mapNSScreenPointToJavaWithOffset:(NSPoint) point;
-
 @end
 
 #endif // CDragSource_h
--- a/jdk/src/macosx/native/sun/awt/CDragSource.m	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/CDragSource.m	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -75,15 +75,18 @@
 static NSDragOperation    sDragOperation;
 static NSPoint            sDraggingLocation;
 
-static CDragSource*        sCurrentDragSource;
 static BOOL                sNeedsEnter;
 
+@interface CDragSource ()
+// Updates from the destination to the source
+- (void) postDragEnter;
+- (void) postDragExit;
+// Utility
+- (NSPoint) mapNSScreenPointToJavaWithOffset:(NSPoint) point;
+@end
+
 @implementation CDragSource
 
-+ (CDragSource *) currentDragSource {
-    return sCurrentDragSource;
-}
-
 - (id)        init:(jobject)jDragSourceContextPeer
          component:(jobject)jComponent
            control:(id)control
@@ -94,7 +97,7 @@
          modifiers:(jint)extModifiers
         clickCount:(jint)clickCount
          timeStamp:(jlong)timeStamp
-         dragImage:(jobject)jDragImage
+         dragImage:(jlong)nsDragImagePtr
   dragImageOffsetX:(jint)jDragImageOffsetX
   dragImageOffsetY:(jint)jDragImageOffsetY
      sourceActions:(jint)jSourceActions
@@ -109,26 +112,21 @@
 
     // Construct the object if we have a valid model for it:
     if (control != nil) {
-        JNIEnv *env = [ThreadUtilities getJNIEnv];
-        fComponent = JNFNewGlobalRef(env, jComponent);
-        fDragSourceContextPeer = JNFNewGlobalRef(env, jDragSourceContextPeer);
+        fComponent = jComponent;
+        fDragSourceContextPeer = jDragSourceContextPeer;
+        fTransferable = jTransferable;
+        fTriggerEvent = jTrigger;
 
-        fTransferable = JNFNewGlobalRef(env, jTransferable);
-        fTriggerEvent = JNFNewGlobalRef(env, jTrigger);
-
-        if (jDragImage) {
-            JNF_MEMBER_CACHE(nsImagePtr, CImageClass, "ptr", "J");
-            jlong imgPtr = JNFGetLongField(env, jDragImage, nsImagePtr);
-            fDragImage = (NSImage*) jlong_to_ptr(imgPtr); // Double-casting prevents compiler 'd$|//
-
+        if (nsDragImagePtr) {
+            fDragImage = (NSImage*) jlong_to_ptr(nsDragImagePtr);
             [fDragImage retain];
         }
 
         fDragImageOffset = NSMakePoint(jDragImageOffsetX, jDragImageOffsetY);
 
         fSourceActions = jSourceActions;
-        fFormats = JNFNewGlobalRef(env, jFormats);
-        fFormatMap = JNFNewGlobalRef(env, jFormatMap);
+        fFormats = jFormats;
+        fFormatMap = jFormatMap;
 
         fTriggerEventTimeStamp = timeStamp;
         fDragPos = NSMakePoint(dragPosX, dragPosY);
@@ -515,8 +513,6 @@
     fDragKeyModifiers = [DnDUtilities extractJavaExtKeyModifiersFromJavaExtModifiers:fModifiers];
     fDragMouseModifiers = [DnDUtilities extractJavaExtMouseModifiersFromJavaExtModifiers:fModifiers];
 
-    // Set the current DragSource
-    sCurrentDragSource = self;
     sNeedsEnter = YES;
 
     @try {
@@ -566,8 +562,6 @@
                 JNF_MEMBER_CACHE(resetHoveringMethod, CDragSourceContextPeerClass, "resetHovering", "()V");
         JNFCallVoidMethod(env, fDragSourceContextPeer, resetHoveringMethod); // Hust reset static variable
     } @finally {
-        // Clear the current DragSource
-        sCurrentDragSource = nil;
         sNeedsEnter = NO;
     }
 
--- a/jdk/src/macosx/native/sun/awt/CDragSourceContextPeer.m	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/CDragSourceContextPeer.m	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,30 +40,39 @@
 JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CDragSourceContextPeer_createNativeDragSource
   (JNIEnv *env, jobject jthis, jobject jcomponent, jlong jnativepeer, jobject jtransferable,
    jobject jtrigger, jint jdragposx, jint jdragposy, jint jextmodifiers, jint jclickcount, jlong jtimestamp,
-   jobject jnsdragimage, jint jdragimageoffsetx, jint jdragimageoffsety,
+   jlong nsdragimageptr, jint jdragimageoffsetx, jint jdragimageoffsety,
    jint jsourceactions, jlongArray jformats, jobject jformatmap)
 {
     id controlObj = (id) jlong_to_ptr(jnativepeer);
     __block CDragSource* dragSource = nil;
 
 JNF_COCOA_ENTER(env);
+
+    // Global references are disposed when the DragSource is removed
+    jobject gComponent = JNFNewGlobalRef(env, jcomponent);
+    jobject gDragSourceContextPeer = JNFNewGlobalRef(env, jthis);
+    jobject gTransferable = JNFNewGlobalRef(env, jtransferable);
+    jobject gTriggerEvent = JNFNewGlobalRef(env, jtrigger);
+    jlongArray gFormats = JNFNewGlobalRef(env, jformats);
+    jobject gFormatMap = JNFNewGlobalRef(env, jformatmap);
+
     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
-        dragSource = [[CDragSource alloc] init:jthis
-                                     component:jcomponent
+        dragSource = [[CDragSource alloc] init:gDragSourceContextPeer
+                                     component:gComponent
                                        control:controlObj
-                                  transferable:jtransferable
-                                  triggerEvent:jtrigger
+                                  transferable:gTransferable
+                                  triggerEvent:gTriggerEvent
                                       dragPosX:jdragposx
                                       dragPosY:jdragposy
                                      modifiers:jextmodifiers
                                     clickCount:jclickcount
                                      timeStamp:jtimestamp
-                                     dragImage:jnsdragimage
+                                     dragImage:nsdragimageptr
                               dragImageOffsetX:jdragimageoffsetx
                               dragImageOffsetY:jdragimageoffsety
                                  sourceActions:jsourceactions
-                                       formats:jformats
-                                     formatMap:jformatmap];
+                                       formats:gFormats
+                                     formatMap:gFormatMap];
     }];
 JNF_COCOA_EXIT(env);
 
--- a/jdk/src/macosx/native/sun/awt/CDropTarget.h	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/CDropTarget.h	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,9 +31,15 @@
 
 @class ControlModel;
 
+@class CDropTarget;
+
+@protocol CDropTargetHolder
+- (void) setDropTarget:(CDropTarget *)target;
+@end
+
 @interface CDropTarget : NSObject {
 @private
-    NSView*        fView;
+    NSView<CDropTargetHolder>* fView;
     jobject            fComponent;
     jobject            fDropTarget;
     jobject            fDropTargetContextPeer;
--- a/jdk/src/macosx/native/sun/awt/CImage.m	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/CImage.m	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -143,21 +143,23 @@
     NSMutableArray * reps = [NSMutableArray arrayWithCapacity: num];
 
     jint * ws = (*env)->GetIntArrayElements(env, widths, NULL);
-    jint * hs = (*env)->GetIntArrayElements(env, heights, NULL);
-
-    jsize i;
-    for (i = 0; i < num; i++) {
-        jintArray buffer = (*env)->GetObjectArrayElement(env, buffers, i);
+    if (ws != NULL) {
+        jint * hs = (*env)->GetIntArrayElements(env, heights, NULL);
+        if (hs != NULL) {
+            jsize i;
+            for (i = 0; i < num; i++) {
+                jintArray buffer = (*env)->GetObjectArrayElement(env, buffers, i);
 
-        NSBitmapImageRep* imageRep = CImage_CreateImageRep(env, buffer, ws[i], hs[i]);
-        if (imageRep) {
-            [reps addObject: imageRep];
+                NSBitmapImageRep* imageRep = CImage_CreateImageRep(env, buffer, ws[i], hs[i]);
+                if (imageRep) {
+                    [reps addObject: imageRep];
+                }
+            }
+
+            (*env)->ReleaseIntArrayElements(env, heights, hs, JNI_ABORT);
         }
+        (*env)->ReleaseIntArrayElements(env, widths, ws, JNI_ABORT);
     }
-
-    (*env)->ReleaseIntArrayElements(env, heights, hs, JNI_ABORT);
-    (*env)->ReleaseIntArrayElements(env, widths, ws, JNI_ABORT);
-
     if ([reps count]) {
         NSImage *nsImage = [[NSImage alloc] initWithSize:NSMakeSize(0, 0)];
         [nsImage addRepresentations: reps];
@@ -320,3 +322,26 @@
 
 JNF_COCOA_EXIT(env);
 }
+
+/*
+ * Class:     sun_lwawt_macosx_CImage
+ * Method:    nativeResizeNSImageRepresentations
+ * Signature: (JDD)V
+ */
+JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CImage_nativeResizeNSImageRepresentations
+(JNIEnv *env, jclass clazz, jlong image, jdouble w, jdouble h)
+{
+    if (!image) return;
+    NSImage *i = (NSImage *)jlong_to_ptr(image);
+    
+JNF_COCOA_ENTER(env);
+    
+    NSImageRep *imageRep = nil;
+    NSArray *imageRepresentations = [i representations];
+    NSEnumerator *imageEnumerator = [imageRepresentations objectEnumerator];
+    while ((imageRep = [imageEnumerator nextObject]) != nil) {
+        [imageRep setSize:NSMakeSize(w, h)];
+    }
+    
+JNF_COCOA_EXIT(env);
+}
--- a/jdk/src/macosx/native/sun/awt/CRobot.m	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/CRobot.m	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,9 @@
  * questions.
  */
 
+
+#import "jni_util.h"
+
 #import <JavaNativeFoundation/JavaNativeFoundation.h>
 #import <ApplicationServices/ApplicationServices.h>
 
@@ -187,9 +190,8 @@
     // volatile, otherwise it warns that it might be clobbered by 'longjmp'
     volatile CGPoint point;
 
-    // Translate the device relative point into a valid global CGPoint.
-    point.x = mouseLastX + globalDeviceBounds.origin.x;
-    point.y = mouseLastY + globalDeviceBounds.origin.y;
+    point.x = mouseLastX;
+    point.y = mouseLastY;
 
     __block CGMouseButton button = kCGMouseButtonLeft;
     __block CGEventType type = kCGEventMouseMoved;
@@ -343,6 +345,7 @@
 
     // get a pointer to the Java int array
     void *jPixelData = (*env)->GetPrimitiveArrayCritical(env, pixels, 0);
+    CHECK_NULL(jPixelData);
 
     // create a graphics context around the Java int array
     CGColorSpaceRef picColorSpace = CGColorSpaceCreateWithName(
--- a/jdk/src/macosx/native/sun/awt/CTrayIcon.m	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/CTrayIcon.m	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -135,7 +135,7 @@
 
     clickCount = [event clickCount];
 
-    static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/event/NSEvent");
+    static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent");
     static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IIIIIIIIDD)V");
     jobject jEvent = JNFNewObject(env, jctor_NSEvent,
                                   [event type],
@@ -152,7 +152,7 @@
     }
 
     static JNF_CLASS_CACHE(jc_TrayIcon, "sun/lwawt/macosx/CTrayIcon");
-    static JNF_MEMBER_CACHE(jm_handleMouseEvent, jc_TrayIcon, "handleMouseEvent", "(Lsun/lwawt/macosx/event/NSEvent;)V");
+    static JNF_MEMBER_CACHE(jm_handleMouseEvent, jc_TrayIcon, "handleMouseEvent", "(Lsun/lwawt/macosx/NSEvent;)V");
     JNFCallVoidMethod(env, peer, jm_handleMouseEvent, jEvent);
 }
 
--- a/jdk/src/macosx/native/sun/awt/CWrapper.h	Tue Mar 25 12:31:49 2014 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,24 +0,0 @@
-/*
- * Copyright (c) 2011, 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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.
- */
--- a/jdk/src/macosx/native/sun/awt/CWrapper.m	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/CWrapper.m	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,38 +23,11 @@
  * questions.
  */
 
-#import "CWrapper.h"
-
 #import <JavaNativeFoundation/JavaNativeFoundation.h>
-
-#import "AWTWindow.h"
-#import "LWCToolkit.h"
-#import "GeomUtilities.h"
 #import "ThreadUtilities.h"
-
 #import "sun_lwawt_macosx_CWrapper_NSWindow.h"
 
 /*
- * Class:     sun_lwawt_macosx_CWrapper$NSObject
- * Method:    release
- * Signature: (J)V
- */
-JNIEXPORT void JNICALL
-Java_sun_lwawt_macosx_CWrapper_00024NSObject_release
-(JNIEnv *env, jclass cls, jlong objectPtr)
-{
-JNF_COCOA_ENTER(env);
-
-    id obj = (id)jlong_to_ptr(objectPtr);
-    [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
-        CFRelease(obj);
-    }];
-
-JNF_COCOA_EXIT(env);
-}
-
-
-/*
  * Class:     sun_lwawt_macosx_CWrapper$NSWindow
  * Method:    makeKeyAndOrderFront
  * Signature: (J)V
@@ -249,6 +222,7 @@
     dispatch_once(&pred, ^{
         LEVELS[sun_lwawt_macosx_CWrapper_NSWindow_NSNormalWindowLevel] = NSNormalWindowLevel;
         LEVELS[sun_lwawt_macosx_CWrapper_NSWindow_NSFloatingWindowLevel] = NSFloatingWindowLevel;
+        LEVELS[sun_lwawt_macosx_CWrapper_NSWindow_NSPopUpMenuWindowLevel] = NSPopUpMenuWindowLevel;
     });
 }
 
@@ -308,8 +282,8 @@
 {
 JNF_COCOA_ENTER(env);
 
-    AWTWindow *parent = (AWTWindow *)jlong_to_ptr(parentPtr);
-    AWTWindow *child = (AWTWindow *)jlong_to_ptr(childPtr);
+    NSWindow *parent = (NSWindow *)jlong_to_ptr(parentPtr);
+    NSWindow *child = (NSWindow *)jlong_to_ptr(childPtr);
     [ThreadUtilities performOnMainThread:@selector(removeChildWindow:)
                                       on:parent
                               withObject:child
@@ -320,26 +294,6 @@
 
 /*
  * Class:     sun_lwawt_macosx_CWrapper$NSWindow
- * Method:    setFrame
- * Signature: (JIIIIZ)V
- */
-JNIEXPORT void JNICALL
-Java_sun_lwawt_macosx_CWrapper_00024NSWindow_setFrame
-(JNIEnv *env, jclass cls, jlong windowPtr, jint x, jint y, jint w, jint h, jboolean display)
-{
-JNF_COCOA_ENTER(env);
-
-    AWTWindow *window = (AWTWindow *)jlong_to_ptr(windowPtr);
-    NSRect frame = NSMakeRect(x, y, w, h);
-    [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
-        [window setFrame:frame display:display];
-    }];
-
-JNF_COCOA_EXIT(env);
-}
-
-/*
- * Class:     sun_lwawt_macosx_CWrapper$NSWindow
  * Method:    setAlphaValue
  * Signature: (JF)V
  */
@@ -349,7 +303,7 @@
 {
 JNF_COCOA_ENTER(env);
 
-    AWTWindow *window = (AWTWindow *)jlong_to_ptr(windowPtr);
+    NSWindow *window = (NSWindow *)jlong_to_ptr(windowPtr);
     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
         [window setAlphaValue:(CGFloat)alpha];
     }];
@@ -368,7 +322,7 @@
 {
 JNF_COCOA_ENTER(env);
 
-    AWTWindow *window = (AWTWindow *)jlong_to_ptr(windowPtr);
+    NSWindow *window = (NSWindow *)jlong_to_ptr(windowPtr);
     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
         [window setOpaque:(BOOL)opaque];
     }];
@@ -387,7 +341,7 @@
 {
 JNF_COCOA_ENTER(env);
 
-    AWTWindow *window = (AWTWindow *)jlong_to_ptr(windowPtr);
+    NSWindow *window = (NSWindow *)jlong_to_ptr(windowPtr);
     NSColor *color = (NSColor *)jlong_to_ptr(colorPtr);
     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
         [window setBackgroundColor:color];
@@ -397,6 +351,7 @@
 }
 
 /*
+ * Class:     sun_lwawt_macosx_CWrapper$NSWindow
  * Method:    miniaturize
  * Signature: (J)V
  */
@@ -560,33 +515,6 @@
 
 /*
  * Class:     sun_lwawt_macosx_CWrapper$NSView
- * Method:    frame
- * Signature: (J)Ljava/awt/Rectangle;
- */
-JNIEXPORT jobject JNICALL
-Java_sun_lwawt_macosx_CWrapper_00024NSView_frame
-(JNIEnv *env, jclass cls, jlong viewPtr)
-{
-    jobject jRect = NULL;
-
-JNF_COCOA_ENTER(env);
-
-    __block NSRect rect = NSZeroRect;
-
-    NSView *view = (NSView *)jlong_to_ptr(viewPtr);
-    [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
-        rect = [view frame];
-    }];
-
-    jRect = NSToJavaRect(env, rect);
-
-JNF_COCOA_EXIT(env);
-
-    return jRect;
-}
-
-/*
- * Class:     sun_lwawt_macosx_CWrapper$NSView
  * Method:    window
  * Signature: (J)J
  */
--- a/jdk/src/macosx/native/sun/awt/LWCToolkit.m	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/LWCToolkit.m	Wed Jul 05 19:33:51 2017 +0200
@@ -200,13 +200,17 @@
     gNumberOfButtons = sun_lwawt_macosx_LWCToolkit_BUTTONS;
 
     jclass inputEventClazz = (*env)->FindClass(env, "java/awt/event/InputEvent");
+    CHECK_NULL(inputEventClazz);
     jmethodID getButtonDownMasksID = (*env)->GetStaticMethodID(env, inputEventClazz, "getButtonDownMasks", "()[I");
+    CHECK_NULL(getButtonDownMasksID);
     jintArray obj = (jintArray)(*env)->CallStaticObjectMethod(env, inputEventClazz, getButtonDownMasksID);
     jint * tmp = (*env)->GetIntArrayElements(env, obj, JNI_FALSE);
+    CHECK_NULL(tmp);
 
     gButtonDownMasks = (jint*)SAFE_SIZE_ARRAY_ALLOC(malloc, sizeof(jint), gNumberOfButtons);
     if (gButtonDownMasks == NULL) {
         gNumberOfButtons = 0;
+        (*env)->ReleaseIntArrayElements(env, obj, tmp, JNI_ABORT);
         JNU_ThrowOutOfMemoryError(env, NULL);
         return;
     }
@@ -240,7 +244,7 @@
     return ((ia & 0xFF) << 24) | ((ir & 0xFF) << 16) | ((ig & 0xFF) << 8) | ((ib & 0xFF) << 0);
 }
 
-void doLoadNativeColors(JNIEnv *env, jintArray jColors, BOOL useAppleColors) {
+BOOL doLoadNativeColors(JNIEnv *env, jintArray jColors, BOOL useAppleColors) {
     jint len = (*env)->GetArrayLength(env, jColors);
 
     UInt32 colorsArray[len];
@@ -254,8 +258,12 @@
     }];
 
     jint *_colors = (*env)->GetPrimitiveArrayCritical(env, jColors, 0);
+    if (_colors == NULL) {
+        return NO;
+    }
     memcpy(_colors, colors, len * sizeof(UInt32));
     (*env)->ReleasePrimitiveArrayCritical(env, jColors, _colors, 0);
+    return YES;
 }
 
 /**
@@ -267,8 +275,9 @@
 (JNIEnv *env, jobject peer, jintArray jSystemColors, jintArray jAppleColors)
 {
 JNF_COCOA_ENTER(env);
-    doLoadNativeColors(env, jSystemColors, NO);
-    doLoadNativeColors(env, jAppleColors, YES);
+    if (doLoadNativeColors(env, jSystemColors, NO)) {
+        doLoadNativeColors(env, jAppleColors, YES);
+    }
 JNF_COCOA_EXIT(env);
 }
 
--- a/jdk/src/macosx/native/sun/awt/splashscreen/splashscreen_sys.m	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/awt/splashscreen/splashscreen_sys.m	Wed Jul 05 19:33:51 2017 +0200
@@ -142,10 +142,9 @@
     splash->screenFormat.byteOrder = 1 ?  BYTE_ORDER_LSBFIRST : BYTE_ORDER_MSBFIRST;
     splash->screenFormat.depthBytes = 4;
 
-    dispatch_async(dispatch_get_main_queue(), ^(void) {
-            NSApplication * app = [NSApplicationAWT sharedApplication];
-            [NSApplicationAWT runAWTLoopWithApp: app];
-    });
+    [JNFRunLoop performOnMainThreadWaiting:NO withBlock:^() {
+        [NSApplicationAWT runAWTLoopWithApp:[NSApplicationAWT sharedApplication]];
+    }];
 }
 
 void
--- a/jdk/src/macosx/native/sun/java2d/opengl/CGLGraphicsConfig.m	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/macosx/native/sun/java2d/opengl/CGLGraphicsConfig.m	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -433,18 +433,18 @@
 }
 
 JNIEXPORT jint JNICALL
-Java_sun_java2d_opengl_CGLGraphicsConfig_getMaxTextureSize
+Java_sun_java2d_opengl_CGLGraphicsConfig_nativeGetMaxTextureSize
     (JNIEnv *env, jclass cglgc)
 {
-    J2dTraceLn(J2D_TRACE_INFO, "CGLGraphicsConfig_getMaxTextureSize");
+    J2dTraceLn(J2D_TRACE_INFO, "CGLGraphicsConfig_nativeGetMaxTextureSize");
 
     __block int max = 0;
 
-    [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
+    [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
         [sharedContext makeCurrentContext];
         j2d_glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max);
+        [NSOpenGLContext clearCurrentContext];
     }];
 
     return (jint)max;
 }
-
--- a/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageReader.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageReader.java	Wed Jul 05 19:33:51 2017 +0200
@@ -680,7 +680,7 @@
         gotHeader = true;
     }
 
-    public Iterator getImageTypes(int imageIndex)
+    public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex)
       throws IOException {
         checkIndex(imageIndex);
         try {
@@ -688,7 +688,7 @@
         } catch (IllegalArgumentException e) {
             throw new IIOException(I18N.getString("BMPImageReader6"), e);
         }
-        ArrayList list = new ArrayList(1);
+        ArrayList<ImageTypeSpecifier> list = new ArrayList<>(1);
         list.add(new ImageTypeSpecifier(originalColorModel,
                                         originalSampleModel));
         return list.iterator();
@@ -912,6 +912,7 @@
                 throw new
                     IIOException(I18N.getString("BMPImageReader1"));
             }
+            break;
 
         case VERSION_4_8_BIT:
             switch((int)compression) {
--- a/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageReaderSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageReaderSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -51,7 +51,7 @@
               entensions,
               mimeType,
               "com.sun.imageio.plugins.bmp.BMPImageReader",
-              new Class[] { ImageInputStream.class },
+              new Class<?>[] { ImageInputStream.class },
               writerSpiNames,
               false,
               null, null, null, null,
--- a/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageWriter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageWriter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1325,10 +1325,11 @@
                                ImageWriteParam bmpParam) throws IOException {
         String format =
             compressionType == BI_JPEG ? "jpeg" : "png";
-        Iterator iterator = ImageIO.getImageWritersByFormatName(format);
+        Iterator<ImageWriter> iterator =
+               ImageIO.getImageWritersByFormatName(format);
         ImageWriter writer = null;
         if (iterator.hasNext())
-            writer = (ImageWriter)iterator.next();
+            writer = iterator.next();
         if (writer != null) {
             if (embedded_stream == null) {
                 throw new RuntimeException("No stream for writing embedded image!");
--- a/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageWriterSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageWriterSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -56,7 +56,7 @@
               entensions,
               mimeType,
               "com.sun.imageio.plugins.bmp.BMPImageWriter",
-              new Class[] { ImageOutputStream.class },
+              new Class<?>[] { ImageOutputStream.class },
               readerSpiNames,
               false,
               null, null, null, null,
--- a/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPMetadata.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPMetadata.java	Wed Jul 05 19:33:51 2017 +0200
@@ -91,10 +91,6 @@
     public int green;
     public int blue;
 
-    // Fields from CommentExtension
-    // List of byte[]
-    public List comments = null; // new ArrayList();
-
     public BMPMetadata() {
         super(true,
               nativeMetadataFormatName,
--- a/jdk/src/share/classes/com/sun/imageio/plugins/common/StandardMetadataFormat.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/common/StandardMetadataFormat.java	Wed Jul 05 19:33:51 2017 +0200
@@ -42,7 +42,7 @@
 
     public StandardMetadataFormat() {
         super(standardMetadataFormatName, CHILD_POLICY_SOME);
-        List values;
+        List<String> values;
 
         // root -> Chroma
         addElement("Chroma", standardMetadataFormatName,
@@ -52,7 +52,7 @@
         addElement("ColorSpaceType", "Chroma",
                    CHILD_POLICY_EMPTY);
 
-        values = new ArrayList();
+        values = new ArrayList<>();
         values.add("XYZ");
         values.add("Lab");
         values.add("Luv");
@@ -164,7 +164,7 @@
         // root -> Data -> PlanarConfiguration
         addElement("PlanarConfiguration", "Data", CHILD_POLICY_EMPTY);
 
-        values = new ArrayList();
+        values = new ArrayList<>();
         values.add("PixelInterleaved");
         values.add("PlaneInterleaved");
         values.add("LineInterleaved");
@@ -178,7 +178,7 @@
         // root -> Data -> SampleFormat
         addElement("SampleFormat", "Data", CHILD_POLICY_EMPTY);
 
-        values = new ArrayList();
+        values = new ArrayList<>();
         values.add("SignedIntegral");
         values.add("UnsignedIntegral");
         values.add("Real");
@@ -225,7 +225,7 @@
         addElement("ImageOrientation", "Dimension",
                    CHILD_POLICY_EMPTY);
 
-        values = new ArrayList();
+        values = new ArrayList<>();
         values.add("Normal");
         values.add("Rotate90");
         values.add("Rotate180");
@@ -306,7 +306,7 @@
         // root -> Document -> SubimageInterpretation
         addElement("SubimageInterpretation", "Document",
                    CHILD_POLICY_EMPTY);
-        values = new ArrayList();
+        values = new ArrayList<>();
         values.add("Standalone");
         values.add("SinglePage");
         values.add("FullResolution");
@@ -418,7 +418,7 @@
                      false,
                      null);
 
-        values = new ArrayList();
+        values = new ArrayList<>();
         values.add("none");
         values.add("lzw");
         values.add("zip");
@@ -437,7 +437,7 @@
         // root -> Transparency -> Alpha
         addElement("Alpha", "Transparency", CHILD_POLICY_EMPTY);
 
-        values = new ArrayList();
+        values = new ArrayList<>();
         values.add("none");
         values.add("premultiplied");
         values.add("nonpremultiplied");
--- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageMetadata.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageMetadata.java	Wed Jul 05 19:33:51 2017 +0200
@@ -84,17 +84,17 @@
 
     // Fields from ApplicationExtension
     // List of byte[]
-    public List applicationIDs = null; // new ArrayList();
+    public List<byte[]> applicationIDs = null;
 
     // List of byte[]
-    public List authenticationCodes = null; // new ArrayList();
+    public List<byte[]> authenticationCodes = null;
 
     // List of byte[]
-    public List applicationData = null; // new ArrayList();
+    public List<byte[]> applicationData = null;
 
     // Fields from CommentExtension
     // List of byte[]
-    public List comments = null; // new ArrayList();
+    public List<byte[]> comments = null;
 
     protected GIFImageMetadata(boolean standardMetadataFormatSupported,
                                String nativeMetadataFormatName,
@@ -225,13 +225,13 @@
             for (int i = 0; i < numAppExtensions; i++) {
                 IIOMetadataNode appExtNode =
                     new IIOMetadataNode("ApplicationExtension");
-                byte[] applicationID = (byte[])applicationIDs.get(i);
+                byte[] applicationID = applicationIDs.get(i);
                 appExtNode.setAttribute("applicationID",
                                         toISO8859(applicationID));
-                byte[] authenticationCode = (byte[])authenticationCodes.get(i);
+                byte[] authenticationCode = authenticationCodes.get(i);
                 appExtNode.setAttribute("authenticationCode",
                                         toISO8859(authenticationCode));
-                byte[] appData = (byte[])applicationData.get(i);
+                byte[] appData = applicationData.get(i);
                 appExtNode.setUserObject(appData.clone());
                 node.appendChild(appExtNode);
             }
@@ -246,7 +246,7 @@
             for (int i = 0; i < numComments; i++) {
                 IIOMetadataNode commentNode =
                     new IIOMetadataNode("CommentExtension");
-                byte[] comment = (byte[])comments.get(i);
+                byte[] comment = comments.get(i);
                 commentNode.setAttribute("value", toISO8859(comment));
                 node.appendChild(commentNode);
             }
@@ -374,7 +374,7 @@
         if (comments == null) {
             return null;
         }
-        Iterator commentIter = comments.iterator();
+        Iterator<byte[]> commentIter = comments.iterator();
         if (!commentIter.hasNext()) {
             return null;
         }
@@ -383,7 +383,7 @@
         IIOMetadataNode node = null; // scratch node
 
         while (commentIter.hasNext()) {
-            byte[] comment = (byte[])commentIter.next();
+            byte[] comment = commentIter.next();
             String s = null;
             try {
                 s = new String(comment, "ISO-8859-1");
--- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java	Wed Jul 05 19:33:51 2017 +0200
@@ -72,7 +72,7 @@
     // A List of Longs indicating the stream positions of the
     // start of the metadata for each image.  Entries are added
     // as needed.
-    List imageStartPosition = new ArrayList();
+    List<Long> imageStartPosition = new ArrayList<>();
 
     // Length of metadata for image at 'currIndex', valid only if
     // imageMetadata != null.
@@ -227,7 +227,8 @@
         return new ImageTypeSpecifier(colorModel, sampleModel);
     }
 
-    public Iterator getImageTypes(int imageIndex) throws IIOException {
+    public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex)
+            throws IIOException {
         checkIndex(imageIndex);
 
         int index = locateImage(imageIndex);
@@ -236,7 +237,7 @@
         }
         readMetadata();
 
-        List l = new ArrayList(1);
+        List<ImageTypeSpecifier> l = new ArrayList<>(1);
 
         byte[] colorTable;
         if (imageMetadata.localColorTable != null) {
@@ -605,7 +606,7 @@
             int index = Math.min(imageIndex, imageStartPosition.size() - 1);
 
             // Seek to that position
-            Long l = (Long)imageStartPosition.get(index);
+            Long l = imageStartPosition.get(index);
             stream.seek(l.longValue());
 
             // Skip images until at desired index or last image found
@@ -731,7 +732,7 @@
                     } else if (label == 0xfe) { // Comment extension
                         byte[] comment = concatenateBlocks();
                         if (imageMetadata.comments == null) {
-                            imageMetadata.comments = new ArrayList();
+                            imageMetadata.comments = new ArrayList<>();
                         }
                         imageMetadata.comments.add(comment);
                     } else if (label == 0xff) { // Application extension
@@ -762,10 +763,10 @@
 
                         // Init lists if necessary
                         if (imageMetadata.applicationIDs == null) {
-                            imageMetadata.applicationIDs = new ArrayList();
+                            imageMetadata.applicationIDs = new ArrayList<>();
                             imageMetadata.authenticationCodes =
-                                new ArrayList();
-                            imageMetadata.applicationData = new ArrayList();
+                                new ArrayList<>();
+                            imageMetadata.applicationData = new ArrayList<>();
                         }
                         imageMetadata.applicationIDs.add(applicationID);
                         imageMetadata.authenticationCodes.add(authCode);
@@ -868,7 +869,7 @@
         }
 
         // Initialize the destination image
-        Iterator imageTypes = getImageTypes(imageIndex);
+        Iterator<ImageTypeSpecifier> imageTypes = getImageTypes(imageIndex);
         this.theImage = getDestination(param,
                                        imageTypes,
                                        imageMetadata.imageWidth,
@@ -1031,7 +1032,7 @@
         streamMetadata = null;
         currIndex = -1;
         imageMetadata = null;
-        imageStartPosition = new ArrayList();
+        imageStartPosition = new ArrayList<>();
         numImages = -1;
 
         // No need to reinitialize 'block'
--- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReaderSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReaderSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -60,7 +60,7 @@
               suffixes,
               MIMETypes,
               readerClassName,
-              new Class[] { ImageInputStream.class },
+              new Class<?>[] { ImageInputStream.class },
               writerSpiNames,
               true,
               GIFStreamMetadata.nativeMetadataFormatName,
--- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageWriter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageWriter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1204,9 +1204,9 @@
     private void writeApplicationExtension(GIFWritableImageMetadata im)
       throws IOException {
         if (im.applicationIDs != null) {
-            Iterator iterIDs = im.applicationIDs.iterator();
-            Iterator iterCodes = im.authenticationCodes.iterator();
-            Iterator iterData = im.applicationData.iterator();
+            Iterator<byte[]> iterIDs = im.applicationIDs.iterator();
+            Iterator<byte[]> iterCodes = im.authenticationCodes.iterator();
+            Iterator<byte[]> iterData = im.applicationData.iterator();
 
             while (iterIDs.hasNext()) {
                 try {
@@ -1214,10 +1214,10 @@
                     stream.write(0xff);
 
                     stream.write(11);
-                    stream.write((byte[])iterIDs.next(), 0, 8);
-                    stream.write((byte[])iterCodes.next(), 0, 3);
+                    stream.write(iterIDs.next(), 0, 8);
+                    stream.write(iterCodes.next(), 0, 3);
 
-                    writeBlocks((byte[])iterData.next());
+                    writeBlocks(iterData.next());
 
                     stream.write(0x00);
                 } catch (IOException e) {
@@ -1231,11 +1231,11 @@
       throws IOException {
         if (im.comments != null) {
             try {
-                Iterator iter = im.comments.iterator();
+                Iterator<byte[]> iter = im.comments.iterator();
                 while (iter.hasNext()) {
                     stream.write(0x21);
                     stream.write(0xfe);
-                    writeBlocks((byte[])iter.next());
+                    writeBlocks(iter.next());
                     stream.write(0x00);
                 }
             } catch (IOException e) {
--- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageWriterSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageWriterSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -60,7 +60,7 @@
               suffixes,
               MIMETypes,
               writerClassName,
-              new Class[] { ImageOutputStream.class },
+              new Class<?>[] { ImageOutputStream.class },
               readerSpiNames,
               true,
               GIFWritableStreamMetadata.NATIVE_FORMAT_NAME,
--- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java	Wed Jul 05 19:33:51 2017 +0200
@@ -258,14 +258,14 @@
                 }
 
                 if (applicationIDs == null) {
-                    applicationIDs = new ArrayList();
-                    authenticationCodes = new ArrayList();
-                    applicationData = new ArrayList();
+                    applicationIDs = new ArrayList<>();
+                    authenticationCodes = new ArrayList<>();
+                    applicationData = new ArrayList<>();
                 }
 
                 applicationIDs.add(fromISO8859(applicationIDString));
                 authenticationCodes.add(fromISO8859(authenticationCodeString));
-                applicationData.add(applicationExtensionData);
+                applicationData.add((byte[]) applicationExtensionData);
             } else if (name.equals("CommentExtensions")) {
                 Node commentExtension = node.getFirstChild();
                 if (commentExtension != null) {
@@ -276,7 +276,7 @@
                         }
 
                         if (comments == null) {
-                            comments = new ArrayList();
+                            comments = new ArrayList<>();
                         }
 
                         String comment =
@@ -367,7 +367,7 @@
                         String value = getAttribute(childNode, "value");
                         byte[] comment = fromISO8859(value);
                         if (comments == null) {
-                            comments = new ArrayList();
+                            comments = new ArrayList<>();
                         }
                         comments.add(comment);
                     }
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/DHTMarkerSegment.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/DHTMarkerSegment.java	Wed Jul 05 19:33:51 2017 +0200
@@ -43,7 +43,7 @@
  * A DHT (Define Huffman Table) marker segment.
  */
 class DHTMarkerSegment extends MarkerSegment {
-    List tables = new ArrayList();
+    List<Htable> tables = new ArrayList<>();
 
     DHTMarkerSegment(boolean needFour) {
         super(JPEG.DHT);
@@ -93,11 +93,11 @@
 
     protected Object clone() {
         DHTMarkerSegment newGuy = (DHTMarkerSegment) super.clone();
-        newGuy.tables = new ArrayList(tables.size());
-        Iterator iter = tables.iterator();
+        newGuy.tables = new ArrayList<>(tables.size());
+        Iterator<Htable> iter = tables.iterator();
         while (iter.hasNext()) {
-            Htable table = (Htable) iter.next();
-            newGuy.tables.add(table.clone());
+            Htable table = iter.next();
+            newGuy.tables.add((Htable) table.clone());
         }
         return newGuy;
     }
@@ -105,7 +105,7 @@
     IIOMetadataNode getNativeNode() {
         IIOMetadataNode node = new IIOMetadataNode("dht");
         for (int i= 0; i<tables.size(); i++) {
-            Htable table = (Htable) tables.get(i);
+            Htable table = tables.get(i);
             node.appendChild(table.getNativeNode());
         }
         return node;
@@ -124,7 +124,7 @@
         System.out.println("Num tables: "
                            + Integer.toString(tables.size()));
         for (int i= 0; i<tables.size(); i++) {
-            Htable table = (Htable) tables.get(i);
+            Htable table = tables.get(i);
             table.print();
         }
         System.out.println();
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/DQTMarkerSegment.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/DQTMarkerSegment.java	Wed Jul 05 19:33:51 2017 +0200
@@ -44,7 +44,7 @@
  * A DQT (Define Quantization Table) marker segment.
  */
 class DQTMarkerSegment extends MarkerSegment {
-    List tables = new ArrayList();  // Could be 1 to 4
+    List<Qtable> tables = new ArrayList<>();  // Could be 1 to 4
 
     DQTMarkerSegment(float quality, boolean needTwo) {
         super(JPEG.DQT);
@@ -86,11 +86,11 @@
 
     protected Object clone() {
         DQTMarkerSegment newGuy = (DQTMarkerSegment) super.clone();
-        newGuy.tables = new ArrayList(tables.size());
-        Iterator iter = tables.iterator();
+        newGuy.tables = new ArrayList<>(tables.size());
+        Iterator<Qtable> iter = tables.iterator();
         while (iter.hasNext()) {
-            Qtable table = (Qtable) iter.next();
-            newGuy.tables.add(table.clone());
+            Qtable table = iter.next();
+            newGuy.tables.add((Qtable) table.clone());
         }
         return newGuy;
     }
@@ -98,7 +98,7 @@
     IIOMetadataNode getNativeNode() {
         IIOMetadataNode node = new IIOMetadataNode("dqt");
         for (int i= 0; i<tables.size(); i++) {
-            Qtable table = (Qtable) tables.get(i);
+            Qtable table = tables.get(i);
             node.appendChild(table.getNativeNode());
         }
         return node;
@@ -117,7 +117,7 @@
         System.out.println("Num tables: "
                            + Integer.toString(tables.size()));
         for (int i= 0; i<tables.size(); i++) {
-            Qtable table = (Qtable) tables.get(i);
+            Qtable table = tables.get(i);
             table.print();
         }
         System.out.println();
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java	Wed Jul 05 19:33:51 2017 +0200
@@ -76,7 +76,7 @@
     int thumbWidth;
     int thumbHeight;
     JFIFThumbRGB thumb = null;  // If present
-    ArrayList extSegments = new ArrayList();
+    ArrayList<JFIFExtensionMarkerSegment> extSegments = new ArrayList<>();
     ICCMarkerSegment iccSegment = null; // optional ICC
     private static final int THUMB_JPEG = 0x10;
     private static final int THUMB_PALETTE = 0x11;
@@ -157,11 +157,11 @@
     protected Object clone() {
         JFIFMarkerSegment newGuy = (JFIFMarkerSegment) super.clone();
         if (!extSegments.isEmpty()) { // Clone the list with a deep copy
-            newGuy.extSegments = new ArrayList();
-            for (Iterator iter = extSegments.iterator(); iter.hasNext();) {
-                JFIFExtensionMarkerSegment jfxx =
-                    (JFIFExtensionMarkerSegment) iter.next();
-                newGuy.extSegments.add(jfxx.clone());
+            newGuy.extSegments = new ArrayList<>();
+            for (Iterator<JFIFExtensionMarkerSegment> iter =
+                    extSegments.iterator(); iter.hasNext();) {
+                JFIFExtensionMarkerSegment jfxx = iter.next();
+                newGuy.extSegments.add((JFIFExtensionMarkerSegment) jfxx.clone());
             }
         }
         if (iccSegment != null) {
@@ -230,9 +230,9 @@
         if (!extSegments.isEmpty()) {
             IIOMetadataNode JFXXnode = new IIOMetadataNode("JFXX");
             node.appendChild(JFXXnode);
-            for (Iterator iter = extSegments.iterator(); iter.hasNext();) {
-                JFIFExtensionMarkerSegment seg =
-                    (JFIFExtensionMarkerSegment) iter.next();
+            for (Iterator<JFIFExtensionMarkerSegment> iter =
+                    extSegments.iterator(); iter.hasNext();) {
+                JFIFExtensionMarkerSegment seg = iter.next();
                 JFXXnode.appendChild(seg.getNativeNode());
             }
         }
@@ -312,8 +312,7 @@
             }
             index--;
         }
-        JFIFExtensionMarkerSegment jfxx =
-            (JFIFExtensionMarkerSegment) extSegments.get(index);
+        JFIFExtensionMarkerSegment jfxx = extSegments.get(index);
         return jfxx.thumb.getWidth();
     }
 
@@ -324,8 +323,7 @@
             }
             index--;
         }
-        JFIFExtensionMarkerSegment jfxx =
-            (JFIFExtensionMarkerSegment) extSegments.get(index);
+        JFIFExtensionMarkerSegment jfxx = extSegments.get(index);
         return jfxx.thumb.getHeight();
     }
 
@@ -340,8 +338,7 @@
             if (thumb != null) {
                 index--;
             }
-            JFIFExtensionMarkerSegment jfxx =
-                (JFIFExtensionMarkerSegment) extSegments.get(index);
+            JFIFExtensionMarkerSegment jfxx = extSegments.get(index);
             ret = jfxx.thumb.getThumbnail(iis, reader);
         }
         reader.thumbnailComplete();
@@ -436,13 +433,13 @@
      * default encoding is used for the extra thumbnails.
      */
     void writeWithThumbs(ImageOutputStream ios,
-                         List thumbnails,
+                         List<? extends BufferedImage> thumbnails,
                          JPEGImageWriter writer) throws IOException {
         if (thumbnails != null) {
             JFIFExtensionMarkerSegment jfxx = null;
             if (thumbnails.size() == 1) {
                 if (!extSegments.isEmpty()) {
-                    jfxx = (JFIFExtensionMarkerSegment) extSegments.get(0);
+                    jfxx = extSegments.get(0);
                 }
                 writeThumb(ios,
                            (BufferedImage) thumbnails.get(0),
@@ -456,7 +453,7 @@
                 for (int i = 0; i < thumbnails.size(); i++) {
                     jfxx = null;
                     if (i < extSegments.size()) {
-                        jfxx = (JFIFExtensionMarkerSegment) extSegments.get(i);
+                        jfxx = extSegments.get(i);
                     }
                     writeThumb(ios,
                                (BufferedImage) thumbnails.get(i),
@@ -605,7 +602,7 @@
      * marker segments as necessary.
      */
     static void writeDefaultJFIF(ImageOutputStream ios,
-                                 List thumbnails,
+                                 List<? extends BufferedImage> thumbnails,
                                  ICC_Profile iccProfile,
                                  JPEGImageWriter writer)
         throws IOException {
@@ -637,9 +634,9 @@
         System.out.print("Thumbnail Height: ");
         System.out.println(thumbHeight);
         if (!extSegments.isEmpty()) {
-            for (Iterator iter = extSegments.iterator(); iter.hasNext();) {
-                JFIFExtensionMarkerSegment extSegment =
-                    (JFIFExtensionMarkerSegment) iter.next();
+            for (Iterator<JFIFExtensionMarkerSegment> iter =
+                    extSegments.iterator(); iter.hasNext();) {
+                JFIFExtensionMarkerSegment extSegment = iter.next();
                 extSegment.print();
             }
         }
@@ -1373,7 +1370,7 @@
      * combining chunks as necessary.
      */
     class ICCMarkerSegment extends MarkerSegment {
-        ArrayList chunks = null;
+        ArrayList<byte[]> chunks = null;
         byte [] profile = null; // The complete profile when it's fully read
                          // May remain null when writing
         private static final int ID_SIZE = 12;
@@ -1428,7 +1425,7 @@
                 // two chunk numbering bytes
                 length -= 2;
                 buffer.readData(profileData);
-                chunks = new ArrayList();
+                chunks = new ArrayList<>();
                 chunks.add(profileData);
                 chunksRead = 1;
                 inICC = true;
@@ -1518,7 +1515,7 @@
                 for (int i = 1; i <= numChunks; i++) {
                     boolean foundIt = false;
                     for (int chunk = 0; chunk < chunks.size(); chunk++) {
-                        byte [] chunkData = (byte []) chunks.get(chunk);
+                        byte [] chunkData = chunks.get(chunk);
                         if (chunkData[0] == i) { // Right one
                             System.arraycopy(chunkData, 2,
                                              profile, index,
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageMetadataFormat.java	Wed Jul 05 19:33:51 2017 +0200
@@ -82,7 +82,7 @@
                      "2",
                      "0", "255",
                      true, true);
-        List resUnits = new ArrayList();
+        List<String> resUnits = new ArrayList<>();
         resUnits.add("0");
         resUnits.add("1");
         resUnits.add("2");
@@ -125,7 +125,7 @@
         addElement("JFIFthumbPalette", "app0JFXX", CHILD_POLICY_EMPTY);
         addElement("JFIFthumbRGB", "app0JFXX", CHILD_POLICY_EMPTY);
 
-        List codes = new ArrayList();
+        List<String> codes = new ArrayList<>();
         codes.add("16"); // Hex 10
         codes.add("17"); // Hex 11
         codes.add("19"); // Hex 13
@@ -192,7 +192,7 @@
                      "0", "65535",
                      true, true);
 
-        List transforms = new ArrayList();
+        List<String> transforms = new ArrayList<>();
         transforms.add("0");
         transforms.add("1");
         transforms.add("2");
@@ -205,7 +205,7 @@
 
         addElement("componentSpec", "sof", CHILD_POLICY_EMPTY);
 
-        List procs = new ArrayList();
+        List<String> procs = new ArrayList<>();
         procs.add("0");
         procs.add("1");
         procs.add("2");
@@ -234,7 +234,7 @@
                      null,
                      "0", "65535",
                      true, true);
-        List comps = new ArrayList();
+        List<String> comps = new ArrayList<>();
         comps.add("1");
         comps.add("2");
         comps.add("3");
@@ -267,7 +267,7 @@
                      null,
                      "1", "255",
                      true, true);
-        List tabids = new ArrayList();
+        List<String> tabids = new ArrayList<>();
         tabids.add("0");
         tabids.add("1");
         tabids.add("2");
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -78,7 +78,7 @@
      * List of stream positions for images, reinitialized every time
      * a new input source is set.
      */
-    private List imagePositions = null;
+    private List<Long> imagePositions = null;
 
     /**
      * The number of images in the stream, or 0.
@@ -223,9 +223,9 @@
     private DisposerRecord disposerRecord;
 
     /** Sets up static C structures. */
-    private static native void initReaderIDs(Class iisClass,
-                                             Class qTableClass,
-                                             Class huffClass);
+    private static native void initReaderIDs(Class<?> iisClass,
+                                             Class<?> qTableClass,
+                                             Class<?> huffClass);
 
     public JPEGImageReader(ImageReaderSpi originator) {
         super(originator);
@@ -375,7 +375,7 @@
             currentImage = 0;
         }
         if (seekForwardOnly) {
-            Long pos = (Long) imagePositions.get(imagePositions.size()-1);
+            Long pos = imagePositions.get(imagePositions.size()-1);
             iis.flushBefore(pos.longValue());
         }
         tablesOnlyChecked = true;
@@ -392,6 +392,7 @@
         }
     }
 
+    @SuppressWarnings("fallthrough")
     private int getNumImagesOnThread(boolean allowSearch)
       throws IOException {
         if (numImages != 0) {
@@ -481,12 +482,12 @@
             checkTablesOnly();
         }
         if (imageIndex < imagePositions.size()) {
-            iis.seek(((Long)(imagePositions.get(imageIndex))).longValue());
+            iis.seek(imagePositions.get(imageIndex).longValue());
         } else {
             // read to start of image, saving positions
             // First seek to the last position we already have, and skip the
             // entire image
-            Long pos = (Long) imagePositions.get(imagePositions.size()-1);
+            Long pos = imagePositions.get(imagePositions.size()-1);
             iis.seek(pos.longValue());
             skipImage();
             // Now add all intervening positions, skipping images
@@ -766,7 +767,7 @@
         }
     }
 
-    public Iterator getImageTypes(int imageIndex)
+    public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex)
         throws IOException {
         setThreadLock();
         try {
@@ -776,7 +777,7 @@
         }
     }
 
-    private Iterator getImageTypesOnThread(int imageIndex)
+    private Iterator<ImageTypeSpecifier> getImageTypesOnThread(int imageIndex)
         throws IOException {
         if (currentImage != imageIndex) {
             cbLock.check();
@@ -1063,7 +1064,7 @@
 
         if (!wantRaster){
             // Can we read this image?
-            Iterator imageTypes = getImageTypes(imageIndex);
+            Iterator<ImageTypeSpecifier> imageTypes = getImageTypes(imageIndex);
             if (imageTypes.hasNext() == false) {
                 throw new IIOException("Unsupported Image Type");
             }
@@ -1187,8 +1188,8 @@
         // and set knownPassCount
         if (imageIndex == imageMetadataIndex) { // We have metadata
             knownPassCount = 0;
-            for (Iterator iter = imageMetadata.markerSequence.iterator();
-                 iter.hasNext();) {
+            for (Iterator<MarkerSegment> iter =
+                    imageMetadata.markerSequence.iterator(); iter.hasNext();) {
                 if (iter.next() instanceof SOSMarkerSegment) {
                     knownPassCount++;
                 }
@@ -1565,7 +1566,7 @@
 
         // reset local Java structures
         numImages = 0;
-        imagePositions = new ArrayList();
+        imagePositions = new ArrayList<>();
         currentImage = -1;
         image = null;
         raster = null;
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReaderSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReaderSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -46,7 +46,7 @@
               JPEG.suffixes,
               JPEG.MIMETypes,
               "com.sun.imageio.plugins.jpeg.JPEGImageReader",
-              new Class[] { ImageInputStream.class },
+              new Class<?>[] { ImageInputStream.class },
               writerSpiNames,
               true,
               JPEG.nativeStreamMetadataFormatName,
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -107,7 +107,7 @@
     /**
      * If there are thumbnails to be written, this is the list.
      */
-    private List thumbnails = null;
+    private List<? extends BufferedImage> thumbnails = null;
 
     /**
      * If metadata should include an icc profile, store it here.
@@ -1394,14 +1394,14 @@
      */
     private int [] collectScans(JPEGMetadata metadata,
                                 SOFMarkerSegment sof) {
-        List segments = new ArrayList();
+        List<SOSMarkerSegment> segments = new ArrayList<>();
         int SCAN_SIZE = 9;
         int MAX_COMPS_PER_SCAN = 4;
-        for (Iterator iter = metadata.markerSequence.iterator();
+        for (Iterator<MarkerSegment> iter = metadata.markerSequence.iterator();
              iter.hasNext();) {
-            MarkerSegment seg = (MarkerSegment) iter.next();
+            MarkerSegment seg = iter.next();
             if (seg instanceof SOSMarkerSegment) {
-                segments.add(seg);
+                segments.add((SOSMarkerSegment) seg);
             }
         }
         int [] retval = null;
@@ -1411,7 +1411,7 @@
             retval = new int [numScans*SCAN_SIZE];
             int index = 0;
             for (int i = 0; i < numScans; i++) {
-                SOSMarkerSegment sos = (SOSMarkerSegment) segments.get(i);
+                SOSMarkerSegment sos = segments.get(i);
                 retval[index++] = sos.componentSpecs.length; // num comps
                 for (int j = 0; j < MAX_COMPS_PER_SCAN; j++) {
                     if (j < sos.componentSpecs.length) {
@@ -1441,10 +1441,10 @@
      */
     private JPEGQTable [] collectQTablesFromMetadata
         (JPEGMetadata metadata) {
-        ArrayList tables = new ArrayList();
-        Iterator iter = metadata.markerSequence.iterator();
+        ArrayList<DQTMarkerSegment.Qtable> tables = new ArrayList<>();
+        Iterator<MarkerSegment> iter = metadata.markerSequence.iterator();
         while (iter.hasNext()) {
-            MarkerSegment seg = (MarkerSegment) iter.next();
+            MarkerSegment seg = iter.next();
             if (seg instanceof DQTMarkerSegment) {
                 DQTMarkerSegment dqt =
                     (DQTMarkerSegment) seg;
@@ -1456,7 +1456,7 @@
             retval = new JPEGQTable[tables.size()];
             for (int i = 0; i < retval.length; i++) {
                 retval[i] =
-                    new JPEGQTable(((DQTMarkerSegment.Qtable)tables.get(i)).data);
+                    new JPEGQTable(tables.get(i).data);
             }
         }
         return retval;
@@ -1471,16 +1471,14 @@
      */
     private JPEGHuffmanTable[] collectHTablesFromMetadata
         (JPEGMetadata metadata, boolean wantDC) throws IIOException {
-        ArrayList tables = new ArrayList();
-        Iterator iter = metadata.markerSequence.iterator();
+        ArrayList<DHTMarkerSegment.Htable> tables = new ArrayList<>();
+        Iterator<MarkerSegment> iter = metadata.markerSequence.iterator();
         while (iter.hasNext()) {
-            MarkerSegment seg = (MarkerSegment) iter.next();
+            MarkerSegment seg = iter.next();
             if (seg instanceof DHTMarkerSegment) {
-                DHTMarkerSegment dht =
-                    (DHTMarkerSegment) seg;
+                DHTMarkerSegment dht = (DHTMarkerSegment) seg;
                 for (int i = 0; i < dht.tables.size(); i++) {
-                    DHTMarkerSegment.Htable htable =
-                        (DHTMarkerSegment.Htable) dht.tables.get(i);
+                    DHTMarkerSegment.Htable htable = dht.tables.get(i);
                     if (htable.tableClass == (wantDC ? 0 : 1)) {
                         tables.add(htable);
                     }
@@ -1553,6 +1551,7 @@
                         retval = JPEG.JCS_YCC;
                     }
                 }
+                break;
             case ColorSpace.TYPE_CMYK:
                 retval = JPEG.JCS_CMYK;
                 break;
@@ -1592,6 +1591,7 @@
                         retval = JPEG.JCS_YCC;
                     }
                 }
+                break;
             case ColorSpace.TYPE_CMYK:
                 retval = JPEG.JCS_CMYK;
                 break;
@@ -1638,6 +1638,7 @@
                         retval = JPEG.JCS_YCC;
                     }
                 }
+                break;
             case ColorSpace.TYPE_CMYK:
                 retval = JPEG.JCS_YCCK;
                 break;
@@ -1662,8 +1663,8 @@
     ////////////// Native methods and callbacks
 
     /** Sets up static native structures. */
-    private static native void initWriterIDs(Class qTableClass,
-                                             Class huffClass);
+    private static native void initWriterIDs(Class<?> qTableClass,
+                                             Class<?> huffClass);
 
     /** Sets up per-writer native structure and returns a pointer to it. */
     private native long initJPEGImageWriter();
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriterSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriterSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -50,7 +50,7 @@
               JPEG.suffixes,
               JPEG.MIMETypes,
               "com.sun.imageio.plugins.jpeg.JPEGImageWriter",
-              new Class[] { ImageOutputStream.class },
+              new Class<?>[] { ImageOutputStream.class },
               readerSpiNames,
               true,
               JPEG.nativeStreamMetadataFormatName,
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGMetadata.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGMetadata.java	Wed Jul 05 19:33:51 2017 +0200
@@ -52,6 +52,7 @@
 import java.awt.color.ICC_Profile;
 import java.awt.color.ICC_ColorSpace;
 import java.awt.color.ColorSpace;
+import java.awt.image.BufferedImage;
 import java.awt.image.ColorModel;
 import java.awt.Point;
 
@@ -69,7 +70,7 @@
      * <code>markerSequence</code> is modified.  This is used by reset
      * to restore the original state.
      */
-    private List resetSequence = null;
+    private List<MarkerSegment> resetSequence = null;
 
     /**
      * Set to <code>true</code> when reading a thumbnail stored as
@@ -100,7 +101,7 @@
      * list is package visible so that the writer can access it.
      * @see #MarkerSegment
      */
-    List markerSequence = new ArrayList();
+    List<MarkerSegment> markerSequence = new ArrayList<>();
 
     /**
      * Indicates whether this object represents stream or image
@@ -645,9 +646,9 @@
      * with the given tag, or null if none is found.
      */
     MarkerSegment findMarkerSegment(int tag) {
-        Iterator iter = markerSequence.iterator();
+        Iterator<MarkerSegment> iter = markerSequence.iterator();
         while (iter.hasNext()) {
-            MarkerSegment seg = (MarkerSegment)iter.next();
+            MarkerSegment seg = iter.next();
             if (seg.tag == tag) {
                 return seg;
             }
@@ -659,19 +660,20 @@
      * Returns the first or last MarkerSegment object in the list
      * of the given class, or null if none is found.
      */
-    MarkerSegment findMarkerSegment(Class cls, boolean first) {
+    MarkerSegment findMarkerSegment(Class<? extends MarkerSegment> cls, boolean first) {
         if (first) {
-            Iterator iter = markerSequence.iterator();
+            Iterator<MarkerSegment> iter = markerSequence.iterator();
             while (iter.hasNext()) {
-                MarkerSegment seg = (MarkerSegment)iter.next();
+                MarkerSegment seg = iter.next();
                 if (cls.isInstance(seg)) {
                     return seg;
                 }
             }
         } else {
-            ListIterator iter = markerSequence.listIterator(markerSequence.size());
+            ListIterator<MarkerSegment> iter =
+                markerSequence.listIterator(markerSequence.size());
             while (iter.hasPrevious()) {
-                MarkerSegment seg = (MarkerSegment)iter.previous();
+                MarkerSegment seg = iter.previous();
                 if (cls.isInstance(seg)) {
                     return seg;
                 }
@@ -684,19 +686,21 @@
      * Returns the index of the first or last MarkerSegment in the list
      * of the given class, or -1 if none is found.
      */
-    private int findMarkerSegmentPosition(Class cls, boolean first) {
+    private int findMarkerSegmentPosition(Class<? extends MarkerSegment> cls,
+                                          boolean first) {
         if (first) {
-            ListIterator iter = markerSequence.listIterator();
+            ListIterator<MarkerSegment> iter = markerSequence.listIterator();
             for (int i = 0; iter.hasNext(); i++) {
-                MarkerSegment seg = (MarkerSegment)iter.next();
+                MarkerSegment seg = iter.next();
                 if (cls.isInstance(seg)) {
                     return i;
                 }
             }
         } else {
-            ListIterator iter = markerSequence.listIterator(markerSequence.size());
+            ListIterator<MarkerSegment> iter =
+                    markerSequence.listIterator(markerSequence.size());
             for (int i = markerSequence.size()-1; iter.hasPrevious(); i--) {
-                MarkerSegment seg = (MarkerSegment)iter.previous();
+                MarkerSegment seg = iter.previous();
                 if (cls.isInstance(seg)) {
                     return i;
                 }
@@ -706,9 +710,10 @@
     }
 
     private int findLastUnknownMarkerSegmentPosition() {
-        ListIterator iter = markerSequence.listIterator(markerSequence.size());
+        ListIterator<MarkerSegment> iter =
+            markerSequence.listIterator(markerSequence.size());
         for (int i = markerSequence.size()-1; iter.hasPrevious(); i--) {
-            MarkerSegment seg = (MarkerSegment)iter.previous();
+            MarkerSegment seg = iter.previous();
             if (seg.unknown == true) {
                 return i;
             }
@@ -733,15 +738,15 @@
     /**
      * Returns a deep copy of the current marker sequence.
      */
-    private List cloneSequence() {
+    private List<MarkerSegment> cloneSequence() {
         if (markerSequence == null) {
             return null;
         }
-        List retval = new ArrayList(markerSequence.size());
-        Iterator iter = markerSequence.iterator();
+        List<MarkerSegment> retval = new ArrayList<>(markerSequence.size());
+        Iterator<MarkerSegment> iter = markerSequence.iterator();
         while(iter.hasNext()) {
-            MarkerSegment seg = (MarkerSegment)iter.next();
-            retval.add(seg.clone());
+            MarkerSegment seg = iter.next();
+            retval.add((MarkerSegment) seg.clone());
         }
 
         return retval;
@@ -774,7 +779,7 @@
     IIOMetadataNode getNativeTree() {
         IIOMetadataNode root;
         IIOMetadataNode top;
-        Iterator iter = markerSequence.iterator();
+        Iterator<MarkerSegment> iter = markerSequence.iterator();
         if (isStream) {
             root = new IIOMetadataNode(JPEG.nativeStreamMetadataFormatName);
             top = root;
@@ -797,7 +802,7 @@
             top = sequence;
         }
         while(iter.hasNext()) {
-            MarkerSegment seg = (MarkerSegment) iter.next();
+            MarkerSegment seg = iter.next();
             top.appendChild(seg.getNativeNode());
         }
         return root;
@@ -961,9 +966,9 @@
 
         // NumProgressiveScans - count sos segments
         int sosCount = 0;
-        Iterator iter = markerSequence.iterator();
+        Iterator<MarkerSegment> iter = markerSequence.iterator();
         while (iter.hasNext()) {
-            MarkerSegment ms = (MarkerSegment) iter.next();
+            MarkerSegment ms = iter.next();
             if (ms.tag == JPEG.SOS) {
                 sosCount++;
             }
@@ -1028,9 +1033,9 @@
         // Add a text entry for each COM Marker Segment
         if (findMarkerSegment(JPEG.COM) != null) {
             text = new IIOMetadataNode("Text");
-            Iterator iter = markerSequence.iterator();
+            Iterator<MarkerSegment> iter = markerSequence.iterator();
             while (iter.hasNext()) {
-                MarkerSegment seg = (MarkerSegment) iter.next();
+                MarkerSegment seg = iter.next();
                 if (seg.tag == JPEG.COM) {
                     COMMarkerSegment com = (COMMarkerSegment) seg;
                     IIOMetadataNode entry = new IIOMetadataNode("TextEntry");
@@ -1068,7 +1073,7 @@
         if (root == null) {
             throw new IllegalArgumentException("null root!");
         }
-        List copy = null;
+        List<MarkerSegment> copy = null;
         if (resetSequence == null) {
             resetSequence = cloneSequence();  // Deep copy
             copy = resetSequence;  // Avoid cloning twice
@@ -1181,12 +1186,12 @@
      */
     private void mergeDQTNode(Node node) throws IIOInvalidTreeException {
         // First collect any existing DQT nodes into a local list
-        ArrayList oldDQTs = new ArrayList();
-        Iterator iter = markerSequence.iterator();
+        ArrayList<DQTMarkerSegment> oldDQTs = new ArrayList<>();
+        Iterator<MarkerSegment> iter = markerSequence.iterator();
         while (iter.hasNext()) {
-            MarkerSegment seg = (MarkerSegment) iter.next();
+            MarkerSegment seg = iter.next();
             if (seg instanceof DQTMarkerSegment) {
-                oldDQTs.add(seg);
+                oldDQTs.add((DQTMarkerSegment) seg);
             }
         }
         if (!oldDQTs.isEmpty()) {
@@ -1201,10 +1206,9 @@
                 DQTMarkerSegment dqt = null;
                 int tableIndex = -1;
                 for (int j = 0; j < oldDQTs.size(); j++) {
-                    DQTMarkerSegment testDQT = (DQTMarkerSegment) oldDQTs.get(j);
+                    DQTMarkerSegment testDQT = oldDQTs.get(j);
                     for (int k = 0; k < testDQT.tables.size(); k++) {
-                        DQTMarkerSegment.Qtable testTable =
-                            (DQTMarkerSegment.Qtable) testDQT.tables.get(k);
+                        DQTMarkerSegment.Qtable testTable = testDQT.tables.get(k);
                         if (childID == testTable.tableID) {
                             dqt = testDQT;
                             tableIndex = k;
@@ -1216,7 +1220,7 @@
                 if (dqt != null) {
                     dqt.tables.set(tableIndex, dqt.getQtableFromNode(child));
                 } else {
-                    dqt = (DQTMarkerSegment) oldDQTs.get(oldDQTs.size()-1);
+                    dqt = oldDQTs.get(oldDQTs.size()-1);
                     dqt.tables.add(dqt.getQtableFromNode(child));
                 }
             }
@@ -1257,12 +1261,12 @@
      */
     private void mergeDHTNode(Node node) throws IIOInvalidTreeException {
         // First collect any existing DQT nodes into a local list
-        ArrayList oldDHTs = new ArrayList();
-        Iterator iter = markerSequence.iterator();
+        ArrayList<DHTMarkerSegment> oldDHTs = new ArrayList<>();
+        Iterator<MarkerSegment> iter = markerSequence.iterator();
         while (iter.hasNext()) {
-            MarkerSegment seg = (MarkerSegment) iter.next();
+            MarkerSegment seg = iter.next();
             if (seg instanceof DHTMarkerSegment) {
-                oldDHTs.add(seg);
+                oldDHTs.add((DHTMarkerSegment) seg);
             }
         }
         if (!oldDHTs.isEmpty()) {
@@ -1283,10 +1287,9 @@
                 DHTMarkerSegment dht = null;
                 int tableIndex = -1;
                 for (int j = 0; j < oldDHTs.size(); j++) {
-                    DHTMarkerSegment testDHT = (DHTMarkerSegment) oldDHTs.get(j);
+                    DHTMarkerSegment testDHT = oldDHTs.get(j);
                     for (int k = 0; k < testDHT.tables.size(); k++) {
-                        DHTMarkerSegment.Htable testTable =
-                            (DHTMarkerSegment.Htable) testDHT.tables.get(k);
+                        DHTMarkerSegment.Htable testTable = testDHT.tables.get(k);
                         if ((childID == testTable.tableID) &&
                             (childClass == testTable.tableClass)) {
                             dht = testDHT;
@@ -1299,7 +1302,7 @@
                 if (dht != null) {
                     dht.tables.set(tableIndex, dht.getHtableFromNode(child));
                 } else {
-                    dht = (DHTMarkerSegment) oldDHTs.get(oldDHTs.size()-1);
+                    dht = oldDHTs.get(oldDHTs.size()-1);
                     dht.tables.add(dht.getHtableFromNode(child));
                 }
             }
@@ -1735,8 +1738,9 @@
                 }
                 if (idsDiffer) {
                     // update the ids in each SOS marker segment
-                    for (Iterator iter = markerSequence.iterator(); iter.hasNext();) {
-                        MarkerSegment seg = (MarkerSegment) iter.next();
+                    for (Iterator<MarkerSegment> iter = markerSequence.iterator();
+                            iter.hasNext();) {
+                        MarkerSegment seg = iter.next();
                         if (seg instanceof SOSMarkerSegment) {
                             SOSMarkerSegment target = (SOSMarkerSegment) seg;
                             for (int i = 0; i < target.componentSpecs.length; i++) {
@@ -1788,11 +1792,12 @@
         }
 
         if (updateQtables) {
-            List tableSegments = new ArrayList();
-            for (Iterator iter = markerSequence.iterator(); iter.hasNext();) {
-                MarkerSegment seg = (MarkerSegment) iter.next();
+            List<DQTMarkerSegment> tableSegments = new ArrayList<>();
+            for (Iterator<MarkerSegment> iter = markerSequence.iterator();
+                    iter.hasNext();) {
+                MarkerSegment seg = iter.next();
                 if (seg instanceof DQTMarkerSegment) {
-                    tableSegments.add(seg);
+                    tableSegments.add((DQTMarkerSegment) seg);
                 }
             }
             // If there are no tables, don't add them, as the metadata encodes an
@@ -1806,12 +1811,12 @@
 
                 // Find the table with selector 1.
                 boolean found = false;
-                for (Iterator iter = tableSegments.iterator(); iter.hasNext();) {
-                    DQTMarkerSegment testdqt = (DQTMarkerSegment) iter.next();
-                    for (Iterator tabiter = testdqt.tables.iterator();
-                         tabiter.hasNext();) {
-                        DQTMarkerSegment.Qtable tab =
-                            (DQTMarkerSegment.Qtable) tabiter.next();
+                for (Iterator<DQTMarkerSegment> iter = tableSegments.iterator();
+                        iter.hasNext();) {
+                    DQTMarkerSegment testdqt = iter.next();
+                    for (Iterator<DQTMarkerSegment.Qtable> tabiter =
+                            testdqt.tables.iterator(); tabiter.hasNext();) {
+                        DQTMarkerSegment.Qtable tab = tabiter.next();
                         if (tab.tableID == 1) {
                             found = true;
                         }
@@ -1820,12 +1825,12 @@
                 if (!found) {
                     //    find the table with selector 0.  There should be one.
                     DQTMarkerSegment.Qtable table0 = null;
-                    for (Iterator iter = tableSegments.iterator(); iter.hasNext();) {
-                        DQTMarkerSegment testdqt = (DQTMarkerSegment) iter.next();
-                        for (Iterator tabiter = testdqt.tables.iterator();
-                             tabiter.hasNext();) {
-                            DQTMarkerSegment.Qtable tab =
-                                (DQTMarkerSegment.Qtable) tabiter.next();
+                    for (Iterator<DQTMarkerSegment> iter =
+                            tableSegments.iterator(); iter.hasNext();) {
+                        DQTMarkerSegment testdqt = iter.next();
+                        for (Iterator<DQTMarkerSegment.Qtable> tabiter =
+                                testdqt.tables.iterator(); tabiter.hasNext();) {
+                            DQTMarkerSegment.Qtable tab = tabiter.next();
                             if (tab.tableID == 0) {
                                 table0 = tab;
                             }
@@ -1835,19 +1840,19 @@
                     // Assuming that the table with id 0 is a luminance table,
                     // compute a new chrominance table of the same quality and
                     // add it to the last DQT segment
-                    DQTMarkerSegment dqt =
-                        (DQTMarkerSegment) tableSegments.get(tableSegments.size()-1);
+                    DQTMarkerSegment dqt = tableSegments.get(tableSegments.size()-1);
                     dqt.tables.add(dqt.getChromaForLuma(table0));
                 }
             }
         }
 
         if (updateHtables) {
-            List tableSegments = new ArrayList();
-            for (Iterator iter = markerSequence.iterator(); iter.hasNext();) {
-                MarkerSegment seg = (MarkerSegment) iter.next();
+            List<DHTMarkerSegment> tableSegments = new ArrayList<>();
+            for (Iterator<MarkerSegment> iter = markerSequence.iterator();
+                    iter.hasNext();) {
+                MarkerSegment seg = iter.next();
                 if (seg instanceof DHTMarkerSegment) {
-                    tableSegments.add(seg);
+                    tableSegments.add((DHTMarkerSegment) seg);
                 }
             }
             // If there are no tables, don't add them, as the metadata encodes an
@@ -1860,12 +1865,12 @@
 
                 // find a table with selector 1. AC/DC is irrelevant
                 boolean found = false;
-                for (Iterator iter = tableSegments.iterator(); iter.hasNext();) {
-                    DHTMarkerSegment testdht = (DHTMarkerSegment) iter.next();
-                    for (Iterator tabiter = testdht.tables.iterator();
-                         tabiter.hasNext();) {
-                        DHTMarkerSegment.Htable tab =
-                            (DHTMarkerSegment.Htable) tabiter.next();
+                for (Iterator<DHTMarkerSegment> iter = tableSegments.iterator();
+                        iter.hasNext();) {
+                    DHTMarkerSegment testdht = iter.next();
+                    for (Iterator<DHTMarkerSegment.Htable> tabiter =
+                            testdht.tables.iterator(); tabiter.hasNext();) {
+                        DHTMarkerSegment.Htable tab = tabiter.next();
                         if (tab.tableID == 1) {
                             found = true;
                         }
@@ -1875,7 +1880,7 @@
                     // Create new standard dc and ac chrominance tables and add them
                     // to the last DHT segment
                     DHTMarkerSegment lastDHT =
-                        (DHTMarkerSegment) tableSegments.get(tableSegments.size()-1);
+                        tableSegments.get(tableSegments.size()-1);
                     lastDHT.addHtable(JPEGHuffmanTable.StdDCLuminance, true, 1);
                     lastDHT.addHtable(JPEGHuffmanTable.StdACLuminance, true, 1);
                 }
@@ -2181,7 +2186,7 @@
         if (resetSequence == null) {
             resetSequence = markerSequence;
         }
-        markerSequence = new ArrayList();
+        markerSequence = new ArrayList<>();
 
         // Build a whole new marker sequence from the tree
 
@@ -2310,10 +2315,10 @@
      * segments, including 0 if there are no SOS marker segments.
      */
     private int countScanBands() {
-        List ids = new ArrayList();
-        Iterator iter = markerSequence.iterator();
+        List<Integer> ids = new ArrayList<>();
+        Iterator<MarkerSegment> iter = markerSequence.iterator();
         while(iter.hasNext()) {
-            MarkerSegment seg = (MarkerSegment)iter.next();
+            MarkerSegment seg = iter.next();
             if (seg instanceof SOSMarkerSegment) {
                 SOSMarkerSegment sos = (SOSMarkerSegment) seg;
                 SOSMarkerSegment.ScanComponentSpec [] specs = sos.componentSpecs;
@@ -2334,7 +2339,7 @@
     void writeToStream(ImageOutputStream ios,
                        boolean ignoreJFIF,
                        boolean forceJFIF,
-                       List thumbnails,
+                       List<? extends BufferedImage> thumbnails,
                        ICC_Profile iccProfile,
                        boolean ignoreAdobe,
                        int newAdobeTransform,
@@ -2360,9 +2365,9 @@
             }
         }
         // Iterate over each MarkerSegment
-        Iterator iter = markerSequence.iterator();
+        Iterator<MarkerSegment> iter = markerSequence.iterator();
         while(iter.hasNext()) {
-            MarkerSegment seg = (MarkerSegment)iter.next();
+            MarkerSegment seg = iter.next();
             if (seg instanceof JFIFMarkerSegment) {
                 if (ignoreJFIF == false) {
                     JFIFMarkerSegment jfif = (JFIFMarkerSegment) seg;
@@ -2409,7 +2414,7 @@
 
     public void print() {
         for (int i = 0; i < markerSequence.size(); i++) {
-            MarkerSegment seg = (MarkerSegment) markerSequence.get(i);
+            MarkerSegment seg = markerSequence.get(i);
             seg.print();
         }
     }
--- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGMetadataFormat.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGMetadataFormat.java	Wed Jul 05 19:33:51 2017 +0200
@@ -56,7 +56,7 @@
                      DATATYPE_INTEGER,
                      false,
                      "0");
-        List tabids = new ArrayList();
+        List<String> tabids = new ArrayList<>();
         tabids.add("0");
         tabids.add("1");
         tabids.add("2");
@@ -74,7 +74,7 @@
 
         addElement("dht", parentName, 1, 4);
         addElement("dhtable", "dht", CHILD_POLICY_EMPTY);
-        List classes = new ArrayList();
+        List<String> classes = new ArrayList<>();
         classes.add("0");
         classes.add("1");
         addAttribute("dhtable",
--- a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReaderSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReaderSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -60,7 +60,7 @@
               suffixes,
               MIMETypes,
               readerClassName,
-              new Class[] { ImageInputStream.class },
+              new Class<?>[] { ImageInputStream.class },
               writerSpiNames,
               false,
               null, null,
--- a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -656,16 +656,16 @@
     }
 
     private void write_tEXt() throws IOException {
-        Iterator keywordIter = metadata.tEXt_keyword.iterator();
-        Iterator textIter = metadata.tEXt_text.iterator();
+        Iterator<String> keywordIter = metadata.tEXt_keyword.iterator();
+        Iterator<String> textIter = metadata.tEXt_text.iterator();
 
         while (keywordIter.hasNext()) {
             ChunkStream cs = new ChunkStream(PNGImageReader.tEXt_TYPE, stream);
-            String keyword = (String)keywordIter.next();
+            String keyword = keywordIter.next();
             cs.writeBytes(keyword);
             cs.writeByte(0);
 
-            String text = (String)textIter.next();
+            String text = textIter.next();
             cs.writeBytes(text);
             cs.finish();
         }
@@ -717,33 +717,33 @@
     }
 
     private void write_zTXt() throws IOException {
-        Iterator keywordIter = metadata.zTXt_keyword.iterator();
-        Iterator methodIter = metadata.zTXt_compressionMethod.iterator();
-        Iterator textIter = metadata.zTXt_text.iterator();
+        Iterator<String> keywordIter = metadata.zTXt_keyword.iterator();
+        Iterator<Integer> methodIter = metadata.zTXt_compressionMethod.iterator();
+        Iterator<String> textIter = metadata.zTXt_text.iterator();
 
         while (keywordIter.hasNext()) {
             ChunkStream cs = new ChunkStream(PNGImageReader.zTXt_TYPE, stream);
-            String keyword = (String)keywordIter.next();
+            String keyword = keywordIter.next();
             cs.writeBytes(keyword);
             cs.writeByte(0);
 
-            int compressionMethod = ((Integer)methodIter.next()).intValue();
+            int compressionMethod = (methodIter.next()).intValue();
             cs.writeByte(compressionMethod);
 
-            String text = (String)textIter.next();
+            String text = textIter.next();
             cs.write(deflate(text.getBytes("ISO-8859-1")));
             cs.finish();
         }
     }
 
     private void writeUnknownChunks() throws IOException {
-        Iterator typeIter = metadata.unknownChunkType.iterator();
-        Iterator dataIter = metadata.unknownChunkData.iterator();
+        Iterator<String> typeIter = metadata.unknownChunkType.iterator();
+        Iterator<byte[]> dataIter = metadata.unknownChunkData.iterator();
 
         while (typeIter.hasNext() && dataIter.hasNext()) {
-            String type = (String)typeIter.next();
+            String type = typeIter.next();
             ChunkStream cs = new ChunkStream(chunkType(type), stream);
-            byte[] data = (byte[])dataIter.next();
+            byte[] data = dataIter.next();
             cs.write(data);
             cs.finish();
         }
--- a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageWriterSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageWriterSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -62,7 +62,7 @@
                 suffixes,
                 MIMETypes,
                 writerClassName,
-                new Class[] { ImageOutputStream.class },
+                new Class<?>[] { ImageOutputStream.class },
                 readerSpiNames,
                 false,
                 null, null,
--- a/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReader.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReader.java	Wed Jul 05 19:33:51 2017 +0200
@@ -152,14 +152,14 @@
         gotHeader = true;
     }
 
-    public Iterator getImageTypes(int imageIndex)
+    public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex)
         throws IOException {
         checkIndex(imageIndex);
         readHeader();
 
         BufferedImage bi =
             new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_BINARY);
-        ArrayList list = new ArrayList(1);
+        ArrayList<ImageTypeSpecifier> list = new ArrayList<>(1);
         list.add(new ImageTypeSpecifier(bi));
         return list.iterator();
     }
--- a/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReaderSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReaderSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -55,7 +55,7 @@
               entensions,
               mimeType,
               "com.sun.imageio.plugins.wbmp.WBMPImageReader",
-              new Class[] { ImageInputStream.class },
+              new Class<?>[] { ImageInputStream.class },
               writerSpiNames,
               true,
               null, null, null, null,
--- a/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageWriterSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageWriterSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -55,7 +55,7 @@
               entensions,
               mimeType,
               "com.sun.imageio.plugins.wbmp.WBMPImageWriter",
-              new Class[] { ImageOutputStream.class },
+              new Class<?>[] { ImageOutputStream.class },
               readerSpiNames,
               true,
               null, null, null, null,
--- a/jdk/src/share/classes/com/sun/imageio/spi/FileImageInputStreamSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/spi/FileImageInputStreamSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -37,7 +37,7 @@
 
     private static final String version = "1.0";
 
-    private static final Class inputClass = File.class;
+    private static final Class<?> inputClass = File.class;
 
     public FileImageInputStreamSpi() {
         super(vendorName, version, inputClass);
--- a/jdk/src/share/classes/com/sun/imageio/spi/FileImageOutputStreamSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/spi/FileImageOutputStreamSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -37,7 +37,7 @@
 
     private static final String version = "1.0";
 
-    private static final Class outputClass = File.class;
+    private static final Class<?> outputClass = File.class;
 
     public FileImageOutputStreamSpi() {
         super(vendorName, version, outputClass);
--- a/jdk/src/share/classes/com/sun/imageio/spi/InputStreamImageInputStreamSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/spi/InputStreamImageInputStreamSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -40,7 +40,7 @@
 
     private static final String version = "1.0";
 
-    private static final Class inputClass = InputStream.class;
+    private static final Class<?> inputClass = InputStream.class;
 
     public InputStreamImageInputStreamSpi() {
         super(vendorName, version, inputClass);
--- a/jdk/src/share/classes/com/sun/imageio/spi/OutputStreamImageOutputStreamSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/spi/OutputStreamImageOutputStreamSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -40,7 +40,7 @@
 
     private static final String version = "1.0";
 
-    private static final Class outputClass = OutputStream.class;
+    private static final Class<?> outputClass = OutputStream.class;
 
     public OutputStreamImageOutputStreamSpi() {
         super(vendorName, version, outputClass);
--- a/jdk/src/share/classes/com/sun/imageio/spi/RAFImageInputStreamSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/spi/RAFImageInputStreamSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -38,7 +38,7 @@
 
     private static final String version = "1.0";
 
-    private static final Class inputClass = RandomAccessFile.class;
+    private static final Class<?> inputClass = RandomAccessFile.class;
 
     public RAFImageInputStreamSpi() {
         super(vendorName, version, inputClass);
--- a/jdk/src/share/classes/com/sun/imageio/spi/RAFImageOutputStreamSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/spi/RAFImageOutputStreamSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -38,7 +38,7 @@
 
     private static final String version = "1.0";
 
-    private static final Class outputClass = RandomAccessFile.class;
+    private static final Class<?> outputClass = RandomAccessFile.class;
 
     public RAFImageOutputStreamSpi() {
         super(vendorName, version, outputClass);
--- a/jdk/src/share/classes/com/sun/imageio/stream/StreamCloser.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/imageio/stream/StreamCloser.java	Wed Jul 05 19:33:51 2017 +0200
@@ -82,7 +82,7 @@
                 };
 
                 java.security.AccessController.doPrivileged(
-                    new java.security.PrivilegedAction() {
+                    new java.security.PrivilegedAction<Object>() {
                         public Object run() {
                             /* The thread must be a member of a thread group
                              * which will not get GCed before VM exit.
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKFileChooserUI.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKFileChooserUI.java	Wed Jul 05 19:33:51 2017 +0200
@@ -41,7 +41,6 @@
 import javax.swing.table.*;
 import javax.accessibility.*;
 
-import sun.swing.AbstractFilterComboBoxModel;
 import sun.swing.SwingUtilities2;
 
 import sun.swing.plaf.synth.*;
@@ -1329,9 +1328,71 @@
     /**
      * Data model for filter combo-box.
      */
-    protected class FilterComboBoxModel extends AbstractFilterComboBoxModel {
-        protected JFileChooser getFileChooser() {
-            return GTKFileChooserUI.this.getFileChooser();
+    protected class FilterComboBoxModel extends AbstractListModel
+            implements ComboBoxModel, PropertyChangeListener {
+        protected FileFilter[] filters;
+
+        protected FilterComboBoxModel() {
+            super();
+            filters = getFileChooser().getChoosableFileFilters();
+        }
+
+        public void propertyChange(PropertyChangeEvent e) {
+            String prop = e.getPropertyName();
+            if (prop == JFileChooser.CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY) {
+                filters = (FileFilter[]) e.getNewValue();
+                fireContentsChanged(this, -1, -1);
+            } else if (prop == JFileChooser.FILE_FILTER_CHANGED_PROPERTY) {
+                fireContentsChanged(this, -1, -1);
+            }
+        }
+
+        public void setSelectedItem(Object filter) {
+            if (filter != null) {
+                getFileChooser().setFileFilter((FileFilter) filter);
+                fireContentsChanged(this, -1, -1);
+            }
+        }
+
+        public Object getSelectedItem() {
+            // Ensure that the current filter is in the list.
+            // NOTE: we shouldnt' have to do this, since JFileChooser adds
+            // the filter to the choosable filters list when the filter
+            // is set. Lets be paranoid just in case someone overrides
+            // setFileFilter in JFileChooser.
+            FileFilter currentFilter = getFileChooser().getFileFilter();
+            boolean found = false;
+            if (currentFilter != null) {
+                for (FileFilter filter : filters) {
+                    if (filter == currentFilter) {
+                        found = true;
+                    }
+                }
+                if (found == false) {
+                    getFileChooser().addChoosableFileFilter(currentFilter);
+                }
+            }
+            return getFileChooser().getFileFilter();
+        }
+
+        public int getSize() {
+            if (filters != null) {
+                return filters.length;
+            } else {
+                return 0;
+            }
+        }
+
+        public Object getElementAt(int index) {
+            if (index > getSize() - 1) {
+                // This shouldn't happen. Try to recover gracefully.
+                return getFileChooser().getFileFilter();
+            }
+            if (filters != null) {
+                return filters[index];
+            } else {
+                return null;
+            }
         }
     }
 }
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifFileChooserUI.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifFileChooserUI.java	Wed Jul 05 19:33:51 2017 +0200
@@ -38,7 +38,6 @@
 import java.io.IOException;
 import java.util.*;
 import sun.awt.shell.ShellFolder;
-import sun.swing.AbstractFilterComboBoxModel;
 import sun.swing.SwingUtilities2;
 
 /**
@@ -778,9 +777,70 @@
     /**
      * Data model for a type-face selection combo-box.
      */
-    protected class FilterComboBoxModel extends AbstractFilterComboBoxModel {
-        protected JFileChooser getFileChooser() {
-            return MotifFileChooserUI.this.getFileChooser();
+    protected class FilterComboBoxModel extends AbstractListModel<FileFilter> implements ComboBoxModel<FileFilter>,
+            PropertyChangeListener {
+        protected FileFilter[] filters;
+        protected FilterComboBoxModel() {
+            super();
+            filters = getFileChooser().getChoosableFileFilters();
+        }
+
+        public void propertyChange(PropertyChangeEvent e) {
+            String prop = e.getPropertyName();
+            if(prop.equals(JFileChooser.CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY)) {
+                filters = (FileFilter[]) e.getNewValue();
+                fireContentsChanged(this, -1, -1);
+            } else if (prop.equals(JFileChooser.FILE_FILTER_CHANGED_PROPERTY)) {
+                fireContentsChanged(this, -1, -1);
+            }
+        }
+
+        public void setSelectedItem(Object filter) {
+            if(filter != null) {
+                getFileChooser().setFileFilter((FileFilter) filter);
+                fireContentsChanged(this, -1, -1);
+            }
+        }
+
+        public Object getSelectedItem() {
+            // Ensure that the current filter is in the list.
+            // NOTE: we shouldnt' have to do this, since JFileChooser adds
+            // the filter to the choosable filters list when the filter
+            // is set. Lets be paranoid just in case someone overrides
+            // setFileFilter in JFileChooser.
+            FileFilter currentFilter = getFileChooser().getFileFilter();
+            boolean found = false;
+            if(currentFilter != null) {
+                for (FileFilter filter : filters) {
+                    if (filter == currentFilter) {
+                        found = true;
+                    }
+                }
+                if (!found) {
+                    getFileChooser().addChoosableFileFilter(currentFilter);
+                }
+            }
+            return getFileChooser().getFileFilter();
+        }
+
+        public int getSize() {
+            if(filters != null) {
+                return filters.length;
+            } else {
+                return 0;
+            }
+        }
+
+        public FileFilter getElementAt(int index) {
+            if(index > getSize() - 1) {
+                // This shouldn't happen. Try to recover gracefully.
+                return getFileChooser().getFileFilter();
+            }
+            if(filters != null) {
+                return filters[index];
+            } else {
+                return null;
+            }
         }
     }
 
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1193,9 +1193,70 @@
     /**
      * Data model for a type-face selection combo-box.
      */
-    protected class FilterComboBoxModel extends AbstractFilterComboBoxModel {
-        protected JFileChooser getFileChooser() {
-            return WindowsFileChooserUI.this.getFileChooser();
+    protected class FilterComboBoxModel extends AbstractListModel<FileFilter> implements ComboBoxModel<FileFilter>,
+            PropertyChangeListener {
+        protected FileFilter[] filters;
+        protected FilterComboBoxModel() {
+            super();
+            filters = getFileChooser().getChoosableFileFilters();
+        }
+
+        public void propertyChange(PropertyChangeEvent e) {
+            String prop = e.getPropertyName();
+            if(prop == JFileChooser.CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY) {
+                filters = (FileFilter[]) e.getNewValue();
+                fireContentsChanged(this, -1, -1);
+            } else if (prop == JFileChooser.FILE_FILTER_CHANGED_PROPERTY) {
+                fireContentsChanged(this, -1, -1);
+            }
+        }
+
+        public void setSelectedItem(Object filter) {
+            if(filter != null) {
+                getFileChooser().setFileFilter((FileFilter) filter);
+                fireContentsChanged(this, -1, -1);
+            }
+        }
+
+        public Object getSelectedItem() {
+            // Ensure that the current filter is in the list.
+            // NOTE: we shouldnt' have to do this, since JFileChooser adds
+            // the filter to the choosable filters list when the filter
+            // is set. Lets be paranoid just in case someone overrides
+            // setFileFilter in JFileChooser.
+            FileFilter currentFilter = getFileChooser().getFileFilter();
+            boolean found = false;
+            if(currentFilter != null) {
+                for (FileFilter filter : filters) {
+                    if (filter == currentFilter) {
+                        found = true;
+                    }
+                }
+                if(found == false) {
+                    getFileChooser().addChoosableFileFilter(currentFilter);
+                }
+            }
+            return getFileChooser().getFileFilter();
+        }
+
+        public int getSize() {
+            if(filters != null) {
+                return filters.length;
+            } else {
+                return 0;
+            }
+        }
+
+        public FileFilter getElementAt(int index) {
+            if(index > getSize() - 1) {
+                // This shouldn't happen. Try to recover gracefully.
+                return getFileChooser().getFileFilter();
+            }
+            if(filters != null) {
+                return filters[index];
+            } else {
+                return null;
+            }
         }
     }
 
--- a/jdk/src/share/classes/com/sun/tracing/ProviderFactory.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/com/sun/tracing/ProviderFactory.java	Wed Jul 05 19:33:51 2017 +0200
@@ -5,9 +5,9 @@
 import java.io.PrintStream;
 import java.lang.reflect.Field;
 import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.security.PrivilegedActionException;
 import java.security.PrivilegedExceptionAction;
-import sun.security.action.GetPropertyAction;
 
 import sun.tracing.NullProviderFactory;
 import sun.tracing.PrintStreamProviderFactory;
@@ -56,7 +56,7 @@
 
         // Try to instantiate a DTraceProviderFactory
         String prop = AccessController.doPrivileged(
-            new GetPropertyAction("com.sun.tracing.dtrace"));
+            (PrivilegedAction<String>) () -> System.getProperty("com.sun.tracing.dtrace"));
 
         if ( (prop == null || !prop.equals("disable")) &&
              DTraceProviderFactory.isSupported() ) {
@@ -65,7 +65,7 @@
 
         // Try to instantiate an output stream factory
         prop = AccessController.doPrivileged(
-            new GetPropertyAction("sun.tracing.stream"));
+            (PrivilegedAction<String>) () -> System.getProperty("sun.tracing.stream"));
         if (prop != null) {
             for (String spec : prop.split(",")) {
                 PrintStream ps = getPrintStreamFromSpec(spec);
--- a/jdk/src/share/classes/java/awt/Component.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/Component.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,10 @@
 
 import java.io.PrintStream;
 import java.io.PrintWriter;
+import java.util.Objects;
 import java.util.Vector;
 import java.util.Locale;
 import java.util.EventListener;
-import java.util.Iterator;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
@@ -50,8 +50,6 @@
 import java.beans.PropertyChangeListener;
 import java.beans.PropertyChangeSupport;
 import java.beans.Transient;
-import java.awt.event.InputMethodListener;
-import java.awt.event.InputMethodEvent;
 import java.awt.im.InputContext;
 import java.awt.im.InputMethodRequests;
 import java.awt.dnd.DropTarget;
@@ -976,6 +974,17 @@
             public void revalidateSynchronously(Component comp) {
                 comp.revalidateSynchronously();
             }
+
+            @Override
+            public void createBufferStrategy(Component comp, int numBuffers,
+                    BufferCapabilities caps) throws AWTException {
+                comp.createBufferStrategy(numBuffers, caps);
+            }
+
+            @Override
+            public BufferStrategy getBufferStrategy(Component comp) {
+                return comp.getBufferStrategy();
+            }
         });
     }
 
@@ -8120,18 +8129,12 @@
      * @since     JDK1.0
      */
     protected String paramString() {
-        String thisName = getName();
-        String str = (thisName != null? thisName : "") + "," + x + "," + y + "," + width + "x" + height;
-        if (!isValid()) {
-            str += ",invalid";
-        }
-        if (!visible) {
-            str += ",hidden";
-        }
-        if (!enabled) {
-            str += ",disabled";
-        }
-        return str;
+        final String thisName = Objects.toString(getName(), "");
+        final String invalid = isValid() ? "" : ",invalid";
+        final String hidden = visible ? "" : ",hidden";
+        final String disabled = enabled ? "" : ",disabled";
+        return thisName + ',' + x + ',' + y + ',' + width + 'x' + height
+                + invalid + hidden + disabled;
     }
 
     /**
@@ -8140,7 +8143,7 @@
      * @since     JDK1.0
      */
     public String toString() {
-        return getClass().getName() + "[" + paramString() + "]";
+        return getClass().getName() + '[' + paramString() + ']';
     }
 
     /**
--- a/jdk/src/share/classes/java/awt/DefaultKeyboardFocusManager.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/DefaultKeyboardFocusManager.java	Wed Jul 05 19:33:51 2017 +0200
@@ -287,7 +287,7 @@
         synchronized (this) {
             KeyEvent ke = enqueuedKeyEvents.isEmpty() ? null : enqueuedKeyEvents.getFirst();
             if (ke != null && time >= ke.getWhen()) {
-                TypeAheadMarker marker = typeAheadMarkers.getFirst();
+                TypeAheadMarker marker = typeAheadMarkers.isEmpty() ? null : typeAheadMarkers.getFirst();
                 if (marker != null) {
                     Window toplevel = marker.untilFocused.getContainingWindow();
                     // Check that the component awaiting focus belongs to
--- a/jdk/src/share/classes/java/awt/EventQueue.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/EventQueue.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1093,6 +1093,13 @@
                 dispatchThread = null;
             }
             AWTAutoShutdown.getInstance().notifyThreadFree(edt);
+            /*
+             * Event was posted after EDT events pumping had stopped, so start
+             * another EDT to handle this event
+             */
+            if (peekEvent() != null) {
+                initDispatchThread();
+            }
         } finally {
             pushPopLock.unlock();
         }
--- a/jdk/src/share/classes/java/awt/Label.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/Label.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -272,13 +272,13 @@
      * @return     the parameter string of this label
      */
     protected String paramString() {
-        String str = ",align=";
+        String align = "";
         switch (alignment) {
-          case LEFT:   str += "left"; break;
-          case CENTER: str += "center"; break;
-          case RIGHT:  str += "right"; break;
+            case LEFT:   align = "left"; break;
+            case CENTER: align = "center"; break;
+            case RIGHT:  align = "right"; break;
         }
-        return super.paramString() + str + ",text=" + text;
+        return super.paramString() + ",align=" + align + ",text=" + text;
     }
 
     /**
--- a/jdk/src/share/classes/java/awt/MediaTracker.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/MediaTracker.java	Wed Jul 05 19:33:51 2017 +0200
@@ -28,6 +28,7 @@
 import java.awt.Component;
 import java.awt.Image;
 import java.awt.image.ImageObserver;
+import sun.awt.image.MultiResolutionToolkitImage;
 
 /**
  * The <code>MediaTracker</code> class is a utility class to track
@@ -222,10 +223,17 @@
      * @param     h    the height at which the image is rendered
      */
     public synchronized void addImage(Image image, int id, int w, int h) {
+        addImageImpl(image, id, w, h);
+        Image rvImage = getResolutionVariant(image);
+        if (rvImage != null) {
+            addImageImpl(rvImage, id, 2 * w, 2 * h);
+        }
+    }
+
+    private void addImageImpl(Image image, int id, int w, int h) {
         head = MediaEntry.insert(head,
                                  new ImageMediaEntry(this, image, id, w, h));
     }
-
     /**
      * Flag indicating that media is currently being loaded.
      * @see         java.awt.MediaTracker#statusAll
@@ -719,6 +727,15 @@
      * @since   JDK1.1
      */
     public synchronized void removeImage(Image image) {
+        removeImageImpl(image);
+        Image rvImage = getResolutionVariant(image);
+        if (rvImage != null) {
+            removeImageImpl(rvImage);
+        }
+        notifyAll();    // Notify in case remaining images are "done".
+    }
+
+    private void removeImageImpl(Image image) {
         MediaEntry cur = head;
         MediaEntry prev = null;
         while (cur != null) {
@@ -735,7 +752,6 @@
             }
             cur = next;
         }
-        notifyAll();    // Notify in case remaining images are "done".
     }
 
     /**
@@ -750,6 +766,15 @@
      * @since      JDK1.1
      */
     public synchronized void removeImage(Image image, int id) {
+        removeImageImpl(image, id);
+        Image rvImage = getResolutionVariant(image);
+        if (rvImage != null) {
+            removeImageImpl(rvImage, id);
+        }
+        notifyAll();    // Notify in case remaining images are "done".
+    }
+
+    private void removeImageImpl(Image image, int id) {
         MediaEntry cur = head;
         MediaEntry prev = null;
         while (cur != null) {
@@ -766,7 +791,6 @@
             }
             cur = next;
         }
-        notifyAll();    // Notify in case remaining images are "done".
     }
 
     /**
@@ -783,6 +807,16 @@
      */
     public synchronized void removeImage(Image image, int id,
                                          int width, int height) {
+        removeImageImpl(image, id, width, height);
+        Image rvImage = getResolutionVariant(image);
+        if (rvImage != null) {
+            removeImageImpl(rvImage, id, 2 * width, 2 * height);
+
+        }
+        notifyAll();    // Notify in case remaining images are "done".
+    }
+
+    private void removeImageImpl(Image image, int id, int width, int height) {
         MediaEntry cur = head;
         MediaEntry prev = null;
         while (cur != null) {
@@ -801,12 +835,18 @@
             }
             cur = next;
         }
-        notifyAll();    // Notify in case remaining images are "done".
     }
 
     synchronized void setDone() {
         notifyAll();
     }
+
+    private static Image getResolutionVariant(Image image) {
+        if (image instanceof MultiResolutionToolkitImage) {
+            return ((MultiResolutionToolkitImage) image).getResolutionVariant();
+        }
+        return null;
+    }
 }
 
 abstract class MediaEntry {
--- a/jdk/src/share/classes/java/awt/Robot.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/Robot.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -72,9 +72,6 @@
     private int autoDelay = 0;
     private static int LEGAL_BUTTON_MASK = 0;
 
-    // location of robot's GC, used in mouseMove(), getPixelColor() and captureScreenImage()
-    private Point gdLoc;
-
     private DirectColorModel screenCapCM = null;
 
     /**
@@ -132,7 +129,6 @@
 
     private void init(GraphicsDevice screen) throws AWTException {
         checkRobotAllowed();
-        gdLoc = screen.getDefaultConfiguration().getBounds().getLocation();
         Toolkit toolkit = Toolkit.getDefaultToolkit();
         if (toolkit instanceof ComponentFactory) {
             peer = ((ComponentFactory)toolkit).createRobot(this, screen);
@@ -200,7 +196,7 @@
      * @param y         Y position
      */
     public synchronized void mouseMove(int x, int y) {
-        peer.mouseMove(gdLoc.x + x, gdLoc.y + y);
+        peer.mouseMove(x, y);
         afterEvent();
     }
 
@@ -395,7 +391,7 @@
      * @return  Color of the pixel
      */
     public synchronized Color getPixelColor(int x, int y) {
-        Color color = new Color(peer.getRGBPixel(gdLoc.x + x, gdLoc.y + y));
+        Color color = new Color(peer.getRGBPixel(x, y));
         return color;
     }
 
@@ -412,10 +408,7 @@
     public synchronized BufferedImage createScreenCapture(Rectangle screenRect) {
         checkScreenCaptureAllowed();
 
-        // according to the spec, screenRect is relative to robot's GD
-        Rectangle translatedRect = new Rectangle(screenRect);
-        translatedRect.translate(gdLoc.x, gdLoc.y);
-        checkValidRect(translatedRect);
+        checkValidRect(screenRect);
 
         BufferedImage image;
         DataBufferInt buffer;
@@ -441,14 +434,14 @@
         int pixels[];
         int[] bandmasks = new int[3];
 
-        pixels = peer.getRGBPixels(translatedRect);
+        pixels = peer.getRGBPixels(screenRect);
         buffer = new DataBufferInt(pixels, pixels.length);
 
         bandmasks[0] = screenCapCM.getRedMask();
         bandmasks[1] = screenCapCM.getGreenMask();
         bandmasks[2] = screenCapCM.getBlueMask();
 
-        raster = Raster.createPackedRaster(buffer, translatedRect.width, translatedRect.height, translatedRect.width, bandmasks, null);
+        raster = Raster.createPackedRaster(buffer, screenRect.width, screenRect.height, screenRect.width, bandmasks, null);
         SunWritableRaster.makeTrackable(buffer);
 
         image = new BufferedImage(screenCapCM, raster, false, null);
--- a/jdk/src/share/classes/java/awt/SystemColor.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/SystemColor.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,8 @@
  */
 package java.awt;
 
+import sun.awt.AWTAccessor;
+
 import java.io.ObjectStreamException;
 
 import java.lang.annotation.Native;
@@ -459,7 +461,8 @@
     };
 
     static {
-      updateSystemColors();
+        AWTAccessor.setSystemColorAccessor(SystemColor::updateSystemColors);
+        updateSystemColors();
     }
 
     /**
--- a/jdk/src/share/classes/java/awt/Toolkit.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/Toolkit.java	Wed Jul 05 19:33:51 2017 +0200
@@ -26,10 +26,6 @@
 package java.awt;
 
 import java.beans.PropertyChangeEvent;
-import java.util.MissingResourceException;
-import java.util.Properties;
-import java.util.ResourceBundle;
-import java.util.StringTokenizer;
 import java.awt.event.*;
 import java.awt.peer.*;
 import java.awt.im.InputMethodHighlight;
@@ -855,50 +851,39 @@
      */
     public static synchronized Toolkit getDefaultToolkit() {
         if (toolkit == null) {
-            try {
-                // We disable the JIT during toolkit initialization.  This
-                // tends to touch lots of classes that aren't needed again
-                // later and therefore JITing is counter-productiive.
-                java.lang.Compiler.disable();
-
-                java.security.AccessController.doPrivileged(
-                        new java.security.PrivilegedAction<Void>() {
-                    public Void run() {
-                        String nm = null;
-                        Class<?> cls = null;
-                        try {
-                            nm = System.getProperty("awt.toolkit");
+            java.security.AccessController.doPrivileged(
+                    new java.security.PrivilegedAction<Void>() {
+                public Void run() {
+                    Class<?> cls = null;
+                    String nm = System.getProperty("awt.toolkit");
+                    try {
+                        cls = Class.forName(nm);
+                    } catch (ClassNotFoundException e) {
+                        ClassLoader cl = ClassLoader.getSystemClassLoader();
+                        if (cl != null) {
                             try {
-                                cls = Class.forName(nm);
-                            } catch (ClassNotFoundException e) {
-                                ClassLoader cl = ClassLoader.getSystemClassLoader();
-                                if (cl != null) {
-                                    try {
-                                        cls = cl.loadClass(nm);
-                                    } catch (ClassNotFoundException ee) {
-                                        throw new AWTError("Toolkit not found: " + nm);
-                                    }
-                                }
+                                cls = cl.loadClass(nm);
+                            } catch (final ClassNotFoundException ignored) {
+                                throw new AWTError("Toolkit not found: " + nm);
                             }
-                            if (cls != null) {
-                                toolkit = (Toolkit)cls.newInstance();
-                                if (GraphicsEnvironment.isHeadless()) {
-                                    toolkit = new HeadlessToolkit(toolkit);
-                                }
+                        }
+                    }
+                    try {
+                        if (cls != null) {
+                            toolkit = (Toolkit)cls.newInstance();
+                            if (GraphicsEnvironment.isHeadless()) {
+                                toolkit = new HeadlessToolkit(toolkit);
                             }
-                        } catch (InstantiationException e) {
-                            throw new AWTError("Could not instantiate Toolkit: " + nm);
-                        } catch (IllegalAccessException e) {
-                            throw new AWTError("Could not access Toolkit: " + nm);
                         }
-                        return null;
+                    } catch (final InstantiationException ignored) {
+                        throw new AWTError("Could not instantiate Toolkit: " + nm);
+                    } catch (final IllegalAccessException ignored) {
+                        throw new AWTError("Could not access Toolkit: " + nm);
                     }
-                });
-                loadAssistiveTechnologies();
-            } finally {
-                // Make sure to always re-enable the JIT.
-                java.lang.Compiler.enable();
-            }
+                    return null;
+                }
+            });
+            loadAssistiveTechnologies();
         }
         return toolkit;
     }
--- a/jdk/src/share/classes/java/awt/datatransfer/DataFlavor.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/datatransfer/DataFlavor.java	Wed Jul 05 19:33:51 2017 +0200
@@ -570,7 +570,7 @@
         if (DataTransferer.isFlavorCharsetTextType(this) &&
             (isRepresentationClassInputStream() ||
              isRepresentationClassByteBuffer() ||
-             DataTransferer.byteArrayClass.equals(representationClass)))
+             byte[].class.equals(representationClass)))
         {
             params += ";charset=" + DataTransferer.getTextCharset(this);
         }
@@ -743,7 +743,7 @@
     private static Comparator<DataFlavor> textFlavorComparator;
 
     static class TextFlavorComparator
-        extends DataTransferer.DataFlavorComparator {
+            extends DataTransferer.DataFlavorComparator {
 
         /**
          * Compares two <code>DataFlavor</code> objects. Returns a negative
@@ -754,8 +754,8 @@
          * <code>DataFlavor</code>s are ordered according to the rules outlined
          * for <code>selectBestTextFlavor</code>.
          *
-         * @param obj1 the first <code>DataFlavor</code> to be compared
-         * @param obj2 the second <code>DataFlavor</code> to be compared
+         * @param flavor1 the first <code>DataFlavor</code> to be compared
+         * @param flavor2 the second <code>DataFlavor</code> to be compared
          * @return a negative integer, zero, or a positive integer as the first
          *         argument is worse, equal to, or better than the second
          * @throws ClassCastException if either of the arguments is not an
@@ -765,13 +765,10 @@
          *
          * @see #selectBestTextFlavor
          */
-        public int compare(Object obj1, Object obj2) {
-            DataFlavor flavor1 = (DataFlavor)obj1;
-            DataFlavor flavor2 = (DataFlavor)obj2;
-
+        public int compare(DataFlavor flavor1, DataFlavor flavor2) {
             if (flavor1.isFlavorTextType()) {
                 if (flavor2.isFlavorTextType()) {
-                    return super.compare(obj1, obj2);
+                    return super.compare(flavor1, flavor2);
                 } else {
                     return 1;
                 }
@@ -1014,7 +1011,7 @@
                     !(isRepresentationClassReader() ||
                         String.class.equals(representationClass) ||
                         isRepresentationClassCharBuffer() ||
-                        DataTransferer.charArrayClass.equals(representationClass)))
+                        char[].class.equals(representationClass)))
                 {
                     String thisCharset =
                         DataTransferer.canonicalName(getParameter("charset"));
@@ -1099,8 +1096,7 @@
                 !(isRepresentationClassReader() ||
                   String.class.equals(representationClass) ||
                   isRepresentationClassCharBuffer() ||
-                  DataTransferer.charArrayClass.equals
-                  (representationClass)))
+                  char[].class.equals(representationClass)))
             {
                 String charset =
                     DataTransferer.canonicalName(getParameter("charset"));
--- a/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java	Wed Jul 05 19:33:51 2017 +0200
@@ -544,7 +544,7 @@
             DataTransferer transferer = DataTransferer.getInstance();
             if (transferer != null) {
                 List<DataFlavor> platformFlavors =
-                    transferer.getPlatformMappingsForNative(nat);
+                        transferer.getPlatformMappingsForNative(nat);
                 if (!platformFlavors.isEmpty()) {
                     if (flavors != null) {
                         platformFlavors.removeAll(new HashSet<>(flavors));
--- a/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java	Wed Jul 05 19:33:51 2017 +0200
@@ -36,6 +36,7 @@
 
 import java.awt.datatransfer.Transferable;
 
+import java.io.InvalidObjectException;
 import java.util.EventObject;
 
 import java.util.Collections;
@@ -329,22 +330,50 @@
     {
         ObjectInputStream.GetField f = s.readFields();
 
-        dragSource = (DragSource)f.get("dragSource", null);
-        component = (Component)f.get("component", null);
-        origin = (Point)f.get("origin", null);
-        action = f.get("action", 0);
+        DragSource newDragSource = (DragSource)f.get("dragSource", null);
+        if (newDragSource == null) {
+            throw new InvalidObjectException("null DragSource");
+        }
+        dragSource = newDragSource;
+
+        Component newComponent = (Component)f.get("component", null);
+        if (newComponent == null) {
+            throw new InvalidObjectException("null component");
+        }
+        component = newComponent;
+
+        Point newOrigin = (Point)f.get("origin", null);
+        if (newOrigin == null) {
+            throw new InvalidObjectException("null origin");
+        }
+        origin = newOrigin;
+
+        int newAction = f.get("action", 0);
+        if (newAction != DnDConstants.ACTION_COPY &&
+                newAction != DnDConstants.ACTION_MOVE &&
+                newAction != DnDConstants.ACTION_LINK) {
+            throw new InvalidObjectException("bad action");
+        }
+        action = newAction;
+
         // Pre-1.4 support. 'events' was previously non-transient
+        List newEvents;
         try {
-            events = (List)f.get("events", null);
+            newEvents = (List)f.get("events", null);
         } catch (IllegalArgumentException e) {
             // 1.4-compatible byte stream. 'events' was written explicitly
-            events = (List)s.readObject();
+            newEvents = (List)s.readObject();
         }
 
         // Implementation assumes 'events' is never null.
-        if (events == null) {
-            events = Collections.EMPTY_LIST;
+        if (newEvents != null && newEvents.isEmpty()) {
+            // Constructor treats empty events list as invalid value
+            // Throw exception if serialized list is empty
+            throw new InvalidObjectException("empty list of events");
+        } else if (newEvents == null) {
+            newEvents = Collections.emptyList();
         }
+        events = newEvents;
     }
 
     /*
--- a/jdk/src/share/classes/java/awt/dnd/DragGestureRecognizer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/dnd/DragGestureRecognizer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -29,6 +29,8 @@
 import java.awt.Component;
 import java.awt.Point;
 
+import java.io.InvalidObjectException;
+import java.util.Collections;
 import java.util.TooManyListenersException;
 import java.util.ArrayList;
 
@@ -411,10 +413,21 @@
      *
      * @since 1.4
      */
+    @SuppressWarnings("unchecked")
     private void readObject(ObjectInputStream s)
         throws ClassNotFoundException, IOException
     {
-        s.defaultReadObject();
+        ObjectInputStream.GetField f = s.readFields();
+
+        DragSource newDragSource = (DragSource)f.get("dragSource", null);
+        if (newDragSource == null) {
+            throw new InvalidObjectException("null DragSource");
+        }
+        dragSource = newDragSource;
+
+        component = (Component)f.get("component", null);
+        sourceActions = f.get("sourceActions", 0) & (DnDConstants.ACTION_COPY_OR_MOVE | DnDConstants.ACTION_LINK);
+        events = (ArrayList<InputEvent>)f.get("events", new ArrayList<>(1));
 
         dragGestureListener = (DragGestureListener)s.readObject();
     }
--- a/jdk/src/share/classes/java/awt/dnd/DragSourceContext.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/dnd/DragSourceContext.java	Wed Jul 05 19:33:51 2017 +0200
@@ -37,6 +37,7 @@
 import java.awt.dnd.peer.DragSourceContextPeer;
 
 import java.io.IOException;
+import java.io.InvalidObjectException;
 import java.io.ObjectOutputStream;
 import java.io.ObjectInputStream;
 import java.io.Serializable;
@@ -562,7 +563,36 @@
     private void readObject(ObjectInputStream s)
         throws ClassNotFoundException, IOException
     {
-        s.defaultReadObject();
+        ObjectInputStream.GetField f = s.readFields();
+
+        DragGestureEvent newTrigger = (DragGestureEvent)f.get("trigger", null);
+        if (newTrigger == null) {
+            throw new InvalidObjectException("Null trigger");
+        }
+        if (newTrigger.getDragSource() == null) {
+            throw new InvalidObjectException("Null DragSource");
+        }
+        if (newTrigger.getComponent() == null) {
+            throw new InvalidObjectException("Null trigger component");
+        }
+
+        int DGRActions = newTrigger.getSourceAsDragGestureRecognizer().getSourceActions()
+                & (DnDConstants.ACTION_COPY_OR_MOVE | DnDConstants.ACTION_LINK);
+        if (DGRActions == DnDConstants.ACTION_NONE) {
+            throw new InvalidObjectException("Invalid source actions");
+        }
+        int triggerActions = newTrigger.getDragAction();
+        if (triggerActions != DnDConstants.ACTION_COPY &&
+                triggerActions != DnDConstants.ACTION_MOVE &&
+                triggerActions != DnDConstants.ACTION_LINK) {
+            throw new InvalidObjectException("No drag action");
+        }
+        trigger = newTrigger;
+
+        cursor = (Cursor)f.get("cursor", null);
+        useCustomCursor = f.get("useCustomCursor", false);
+        sourceActions = f.get("sourceActions", 0)
+                & (DnDConstants.ACTION_COPY_OR_MOVE | DnDConstants.ACTION_LINK);
 
         transferable = (Transferable)s.readObject();
         listener = (DragSourceListener)s.readObject();
@@ -630,5 +660,5 @@
      *
      * @serial
      */
-    private final int sourceActions;
+    private int sourceActions;
 }
--- a/jdk/src/share/classes/java/awt/event/InputEvent.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/awt/event/InputEvent.java	Wed Jul 05 19:33:51 2017 +0200
@@ -298,6 +298,10 @@
                 public int[] getButtonDownMasks() {
                     return InputEvent.getButtonDownMasks();
                 }
+
+                public boolean canAccessSystemClipboard(InputEvent event) {
+                    return event.canAccessSystemClipboard;
+                }
             });
     }
 
--- a/jdk/src/share/classes/java/beans/Introspector.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/beans/Introspector.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -729,27 +729,53 @@
             if (igpd != null && ispd != null) {
                 // Complete indexed properties set
                 // Merge any classic property descriptors
-                if (gpd != null) {
-                    PropertyDescriptor tpd = mergePropertyDescriptor(igpd, gpd);
-                    if (tpd instanceof IndexedPropertyDescriptor) {
-                        igpd = (IndexedPropertyDescriptor)tpd;
+                if ((gpd == spd) || (gpd == null)) {
+                    pd = spd;
+                } else if (spd == null) {
+                    pd = gpd;
+                } else if (spd instanceof IndexedPropertyDescriptor) {
+                    pd = mergePropertyWithIndexedProperty(gpd, (IndexedPropertyDescriptor) spd);
+                } else if (gpd instanceof IndexedPropertyDescriptor) {
+                    pd = mergePropertyWithIndexedProperty(spd, (IndexedPropertyDescriptor) gpd);
+                } else {
+                    pd = mergePropertyDescriptor(gpd, spd);
+                }
+                if (igpd == ispd) {
+                    ipd = igpd;
+                } else {
+                    ipd = mergePropertyDescriptor(igpd, ispd);
+                }
+                if (pd == null) {
+                    pd = ipd;
+                } else {
+                    Class<?> propType = pd.getPropertyType();
+                    Class<?> ipropType = ipd.getIndexedPropertyType();
+                    if (propType.isArray() && propType.getComponentType() == ipropType) {
+                        pd = pd.getClass0().isAssignableFrom(ipd.getClass0())
+                                ? new IndexedPropertyDescriptor(pd, ipd)
+                                : new IndexedPropertyDescriptor(ipd, pd);
+                    } else if (pd.getClass0().isAssignableFrom(ipd.getClass0())) {
+                        pd = pd.getClass0().isAssignableFrom(ipd.getClass0())
+                                ? new PropertyDescriptor(pd, ipd)
+                                : new PropertyDescriptor(ipd, pd);
+                    } else {
+                        pd = ipd;
                     }
                 }
-                if (spd != null) {
-                    PropertyDescriptor tpd = mergePropertyDescriptor(ispd, spd);
-                    if (tpd instanceof IndexedPropertyDescriptor) {
-                        ispd = (IndexedPropertyDescriptor)tpd;
-                    }
+            } else if (gpd != null && spd != null) {
+                if (igpd != null) {
+                    gpd = mergePropertyWithIndexedProperty(gpd, igpd);
                 }
-                if (igpd == ispd) {
-                    pd = igpd;
-                } else {
-                    pd = mergePropertyDescriptor(igpd, ispd);
+                if (ispd != null) {
+                    spd = mergePropertyWithIndexedProperty(spd, ispd);
                 }
-            } else if (gpd != null && spd != null) {
                 // Complete simple properties set
                 if (gpd == spd) {
                     pd = gpd;
+                } else if (spd instanceof IndexedPropertyDescriptor) {
+                    pd = mergePropertyWithIndexedProperty(gpd, (IndexedPropertyDescriptor) spd);
+                } else if (gpd instanceof IndexedPropertyDescriptor) {
+                    pd = mergePropertyWithIndexedProperty(spd, (IndexedPropertyDescriptor) gpd);
                 } else {
                     pd = mergePropertyDescriptor(gpd, spd);
                 }
@@ -809,6 +835,16 @@
         return current == null ? candidate == null : current.isAssignableFrom(candidate);
     }
 
+    private PropertyDescriptor mergePropertyWithIndexedProperty(PropertyDescriptor pd, IndexedPropertyDescriptor ipd) {
+        Class<?> type = pd.getPropertyType();
+        if (type.isArray() && (type.getComponentType() == ipd.getIndexedPropertyType())) {
+            return pd.getClass0().isAssignableFrom(ipd.getClass0())
+                    ? new IndexedPropertyDescriptor(pd, ipd)
+                    : new IndexedPropertyDescriptor(ipd, pd);
+        }
+        return pd;
+    }
+
     /**
      * Adds the property descriptor to the indexedproperty descriptor only if the
      * types are the same.
@@ -828,6 +864,12 @@
             } else {
                 result = new IndexedPropertyDescriptor(ipd, pd);
             }
+        } else if ((ipd.getReadMethod() == null) && (ipd.getWriteMethod() == null)) {
+            if (pd.getClass0().isAssignableFrom(ipd.getClass0())) {
+                result = new PropertyDescriptor(pd, ipd);
+            } else {
+                result = new PropertyDescriptor(ipd, pd);
+            }
         } else {
             // Cannot merge the pd because of type mismatch
             // Return the most specific pd
@@ -879,7 +921,7 @@
     }
 
     // Handle regular ipd merge
-    private PropertyDescriptor mergePropertyDescriptor(IndexedPropertyDescriptor ipd1,
+    private IndexedPropertyDescriptor mergePropertyDescriptor(IndexedPropertyDescriptor ipd1,
                                                        IndexedPropertyDescriptor ipd2) {
         if (ipd1.getClass0().isAssignableFrom(ipd2.getClass0())) {
             return new IndexedPropertyDescriptor(ipd1, ipd2);
--- a/jdk/src/share/classes/java/io/SequenceInputStream.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/io/SequenceInputStream.java	Wed Jul 05 19:33:51 2017 +0200
@@ -135,7 +135,7 @@
      * @since   JDK1.1
      */
     public int available() throws IOException {
-        if(in == null) {
+        if (in == null) {
             return 0; // no way to signal EOF from available()
         }
         return in.available();
@@ -160,15 +160,14 @@
      * @exception  IOException  if an I/O error occurs.
      */
     public int read() throws IOException {
-        if (in == null) {
-            return -1;
+        while (in != null) {
+            int c = in.read();
+            if (c != -1) {
+                return c;
+            }
+            nextStream();
         }
-        int c = in.read();
-        if (c == -1) {
-            nextStream();
-            return read();
-        }
-        return c;
+        return -1;
     }
 
     /**
@@ -204,13 +203,14 @@
         } else if (len == 0) {
             return 0;
         }
-
-        int n = in.read(b, off, len);
-        if (n <= 0) {
+        do {
+            int n = in.read(b, off, len);
+            if (n > 0) {
+                return n;
+            }
             nextStream();
-            return read(b, off, len);
-        }
-        return n;
+        } while (in != null);
+        return -1;
     }
 
     /**
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java	Wed Jul 05 19:33:51 2017 +0200
@@ -736,16 +736,17 @@
     @LambdaForm.Hidden
     static Object guardWithCatch(MethodHandle target, Class<? extends Throwable> exType, MethodHandle catcher,
                                  Object... av) throws Throwable {
+        // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
         try {
-            return target.invokeWithArguments(av);
+            return target.asFixedArity().invokeWithArguments(av);
         } catch (Throwable t) {
             if (!exType.isInstance(t)) throw t;
-            Object[] args = prepend(t, av);
-            return catcher.invokeWithArguments(args);
+            return catcher.asFixedArity().invokeWithArguments(prepend(t, av));
         }
     }
 
     /** Prepend an element {@code elem} to an {@code array}. */
+    @LambdaForm.Hidden
     private static Object[] prepend(Object elem, Object[] array) {
         Object[] newArray = new Object[array.length+1];
         newArray[0] = elem;
--- a/jdk/src/share/classes/java/math/BigInteger.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/math/BigInteger.java	Wed Jul 05 19:33:51 2017 +0200
@@ -126,8 +126,6 @@
      * 1 for positive.  Note that the BigInteger zero <i>must</i> have
      * a signum of 0.  This is necessary to ensures that there is exactly one
      * representation for each BigInteger value.
-     *
-     * @serial
      */
     final int signum;
 
@@ -142,55 +140,43 @@
      */
     final int[] mag;
 
-    // These "redundant fields" are initialized with recognizable nonsense
-    // values, and cached the first time they are needed (or never, if they
-    // aren't needed).
-
-     /**
-     * One plus the bitCount of this BigInteger. Zeros means unitialized.
-     *
-     * @serial
-     * @see #bitCount
-     * @deprecated Deprecated since logical value is offset from stored
-     * value and correction factor is applied in accessor method.
-     */
-    @Deprecated
-    private int bitCount;
+    // The following fields are stable variables. A stable variable's value
+    // changes at most once from the default zero value to a non-zero stable
+    // value. A stable value is calculated lazily on demand.
 
     /**
-     * One plus the bitLength of this BigInteger. Zeros means unitialized.
+     * One plus the bitCount of this BigInteger. This is a stable variable.
+     *
+     * @see #bitCount
+     */
+    private int bitCountPlusOne;
+
+    /**
+     * One plus the bitLength of this BigInteger. This is a stable variable.
      * (either value is acceptable).
      *
-     * @serial
      * @see #bitLength()
-     * @deprecated Deprecated since logical value is offset from stored
-     * value and correction factor is applied in accessor method.
      */
-    @Deprecated
-    private int bitLength;
+    private int bitLengthPlusOne;
 
     /**
-     * Two plus the lowest set bit of this BigInteger, as returned by
-     * getLowestSetBit().
+     * Two plus the lowest set bit of this BigInteger. This is a stable variable.
      *
-     * @serial
      * @see #getLowestSetBit
-     * @deprecated Deprecated since logical value is offset from stored
-     * value and correction factor is applied in accessor method.
      */
-    @Deprecated
-    private int lowestSetBit;
+    private int lowestSetBitPlusTwo;
 
     /**
      * Two plus the index of the lowest-order int in the magnitude of this
-     * BigInteger that contains a nonzero int, or -2 (either value is acceptable).
-     * The least significant int has int-number 0, the next int in order of
+     * BigInteger that contains a nonzero int. This is a stable variable. The
+     * least significant int has int-number 0, the next int in order of
      * increasing significance has int-number 1, and so forth.
-     * @deprecated Deprecated since logical value is offset from stored
-     * value and correction factor is applied in accessor method.
+     *
+     * <p>Note: never used for a BigInteger with a magnitude of zero.
+     *
+     * @see #firstNonzeroIntNum()
      */
-    @Deprecated
-    private int firstNonzeroIntNum;
+    private int firstNonzeroIntNumPlusTwo;
 
     /**
      * This mask is used to obtain the value of an int as if it were unsigned.
@@ -3240,7 +3226,7 @@
      * @return index of the rightmost one bit in this BigInteger.
      */
     public int getLowestSetBit() {
-        @SuppressWarnings("deprecation") int lsb = lowestSetBit - 2;
+        int lsb = lowestSetBitPlusTwo - 2;
         if (lsb == -2) {  // lowestSetBit not initialized yet
             lsb = 0;
             if (signum == 0) {
@@ -3252,7 +3238,7 @@
                     ;
                 lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
             }
-            lowestSetBit = lsb + 2;
+            lowestSetBitPlusTwo = lsb + 2;
         }
         return lsb;
     }
@@ -3271,7 +3257,7 @@
      *         representation of this BigInteger, <i>excluding</i> a sign bit.
      */
     public int bitLength() {
-        @SuppressWarnings("deprecation") int n = bitLength - 1;
+        int n = bitLengthPlusOne - 1;
         if (n == -1) { // bitLength not initialized yet
             int[] m = mag;
             int len = m.length;
@@ -3291,7 +3277,7 @@
                      n = magBitLength;
                  }
             }
-            bitLength = n + 1;
+            bitLengthPlusOne = n + 1;
         }
         return n;
     }
@@ -3305,7 +3291,7 @@
      *         of this BigInteger that differ from its sign bit.
      */
     public int bitCount() {
-        @SuppressWarnings("deprecation") int bc = bitCount - 1;
+        int bc = bitCountPlusOne - 1;
         if (bc == -1) {  // bitCount not initialized yet
             bc = 0;      // offset by one to initialize
             // Count the bits in the magnitude
@@ -3319,7 +3305,7 @@
                 magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
                 bc += magTrailingZeroCount - 1;
             }
-            bitCount = bc + 1;
+            bitCountPlusOne = bc + 1;
         }
         return bc;
     }
@@ -3622,16 +3608,16 @@
      */
     private static void toString(BigInteger u, StringBuilder sb, int radix,
                                  int digits) {
-        /* If we're smaller than a certain threshold, use the smallToString
-           method, padding with leading zeroes when necessary. */
+        // If we're smaller than a certain threshold, use the smallToString
+        // method, padding with leading zeroes when necessary.
         if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) {
             String s = u.smallToString(radix);
 
             // Pad with internal zeros if necessary.
             // Don't pad if we're at the beginning of the string.
             if ((s.length() < digits) && (sb.length() > 0)) {
-                for (int i=s.length(); i < digits; i++) { // May be a faster way to
-                    sb.append('0');                    // do this?
+                for (int i=s.length(); i < digits; i++) {
+                    sb.append('0');
                 }
             }
 
@@ -4185,22 +4171,23 @@
     }
 
     /**
-     * Returns the index of the int that contains the first nonzero int in the
-     * little-endian binary representation of the magnitude (int 0 is the
-     * least significant). If the magnitude is zero, return value is undefined.
-     */
+    * Returns the index of the int that contains the first nonzero int in the
+    * little-endian binary representation of the magnitude (int 0 is the
+    * least significant). If the magnitude is zero, return value is undefined.
+    *
+    * <p>Note: never used for a BigInteger with a magnitude of zero.
+    * @see #getInt.
+    */
     private int firstNonzeroIntNum() {
-        int fn = firstNonzeroIntNum - 2;
+        int fn = firstNonzeroIntNumPlusTwo - 2;
         if (fn == -2) { // firstNonzeroIntNum not initialized yet
-            fn = 0;
-
             // Search for the first nonzero int
             int i;
             int mlen = mag.length;
             for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
                 ;
             fn = mlen - i - 1;
-            firstNonzeroIntNum = fn + 2; // offset by two to initialize
+            firstNonzeroIntNumPlusTwo = fn + 2; // offset by two to initialize
         }
         return fn;
     }
@@ -4212,16 +4199,17 @@
      * Serializable fields for BigInteger.
      *
      * @serialField signum  int
-     *              signum of this BigInteger.
-     * @serialField magnitude int[]
-     *              magnitude array of this BigInteger.
+     *              signum of this BigInteger
+     * @serialField magnitude byte[]
+     *              magnitude array of this BigInteger
      * @serialField bitCount  int
-     *              number of bits in this BigInteger
+     *              appears in the serialized form for backward compatibility
      * @serialField bitLength int
-     *              the number of bits in the minimal two's-complement
-     *              representation of this BigInteger
+     *              appears in the serialized form for backward compatibility
+     * @serialField firstNonzeroByteNum int
+     *              appears in the serialized form for backward compatibility
      * @serialField lowestSetBit int
-     *              lowest set bit in the twos complement representation
+     *              appears in the serialized form for backward compatibility
      */
     private static final ObjectStreamField[] serialPersistentFields = {
         new ObjectStreamField("signum", Integer.TYPE),
@@ -4238,22 +4226,14 @@
      * for historical reasons, but it is converted to an array of ints
      * and the byte array is discarded.
      * Note:
-     * The current convention is to initialize the cache fields, bitCount,
-     * bitLength and lowestSetBit, to 0 rather than some other marker value.
-     * Therefore, no explicit action to set these fields needs to be taken in
-     * readObject because those fields already have a 0 value be default since
-     * defaultReadObject is not being used.
+     * The current convention is to initialize the cache fields, bitCountPlusOne,
+     * bitLengthPlusOne and lowestSetBitPlusTwo, to 0 rather than some other
+     * marker value. Therefore, no explicit action to set these fields needs to
+     * be taken in readObject because those fields already have a 0 value by
+     * default since defaultReadObject is not being used.
      */
     private void readObject(java.io.ObjectInputStream s)
         throws java.io.IOException, ClassNotFoundException {
-        /*
-         * In order to maintain compatibility with previous serialized forms,
-         * the magnitude of a BigInteger is serialized as an array of bytes.
-         * The magnitude field is used as a temporary store for the byte array
-         * that is deserialized. The cached computation fields should be
-         * transient but are serialized for compatibility reasons.
-         */
-
         // prepare to read the alternate persistent fields
         ObjectInputStream.GetField fields = s.readFields();
 
@@ -4317,12 +4297,14 @@
     }
 
     /**
-     * Save the {@code BigInteger} instance to a stream.
-     * The magnitude of a BigInteger is serialized as a byte array for
-     * historical reasons.
-     *
-     * @serialData two necessary fields are written as well as obsolete
-     *             fields for compatibility with older versions.
+     * Save the {@code BigInteger} instance to a stream.  The magnitude of a
+     * {@code BigInteger} is serialized as a byte array for historical reasons.
+     * To maintain compatibility with older implementations, the integers
+     * -1, -1, -2, and -2 are written as the values of the obsolete fields
+     * {@code bitCount}, {@code bitLength}, {@code lowestSetBit}, and
+     * {@code firstNonzeroByteNum}, respectively.  These values are compatible
+     * with older implementations, but will be ignored by current
+     * implementations.
      */
     private void writeObject(ObjectOutputStream s) throws IOException {
         // set the values of the Serializable fields
@@ -4338,7 +4320,7 @@
 
         // save them
         s.writeFields();
-}
+    }
 
     /**
      * Returns the mag array as an array of bytes.
--- a/jdk/src/share/classes/java/rmi/activation/ActivationGroup.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/rmi/activation/ActivationGroup.java	Wed Jul 05 19:33:51 2017 +0200
@@ -36,7 +36,7 @@
 import java.rmi.server.RMIClassLoader;
 import java.rmi.server.UnicastRemoteObject;
 import java.security.AccessController;
-import sun.security.action.GetIntegerAction;
+import java.security.PrivilegedAction;
 
 /**
  * An <code>ActivationGroup</code> is responsible for creating new
@@ -446,9 +446,8 @@
     {
         if (currSystem == null) {
             try {
-                int port = AccessController.doPrivileged(
-                    new GetIntegerAction("java.rmi.activation.port",
-                                         ActivationSystem.SYSTEM_PORT));
+                int port = AccessController.doPrivileged((PrivilegedAction<Integer>) () ->
+                    Integer.getInteger("java.rmi.activation.port", ActivationSystem.SYSTEM_PORT));
                 currSystem = (ActivationSystem)
                     Naming.lookup("//:" + port +
                                   "/java.rmi.activation.ActivationSystem");
--- a/jdk/src/share/classes/java/rmi/server/ObjID.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/rmi/server/ObjID.java	Wed Jul 05 19:33:51 2017 +0200
@@ -31,9 +31,9 @@
 import java.io.ObjectOutput;
 import java.io.Serializable;
 import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.security.SecureRandom;
 import java.util.concurrent.atomic.AtomicLong;
-import sun.security.action.GetPropertyAction;
 
 /**
  * An <code>ObjID</code> is used to identify a remote object exported
@@ -242,7 +242,7 @@
 
     private static boolean useRandomIDs() {
         String value = AccessController.doPrivileged(
-            new GetPropertyAction("java.rmi.server.randomIDs"));
+            (PrivilegedAction<String>) () -> System.getProperty("java.rmi.server.randomIDs"));
         return value == null ? true : Boolean.parseBoolean(value);
     }
 }
--- a/jdk/src/share/classes/java/util/Arrays.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/util/Arrays.java	Wed Jul 05 19:33:51 2017 +0200
@@ -28,6 +28,7 @@
 import java.lang.reflect.Array;
 import java.util.concurrent.ForkJoinPool;
 import java.util.function.BinaryOperator;
+import java.util.function.Consumer;
 import java.util.function.DoubleBinaryOperator;
 import java.util.function.IntBinaryOperator;
 import java.util.function.IntFunction;
@@ -35,6 +36,7 @@
 import java.util.function.IntToLongFunction;
 import java.util.function.IntUnaryOperator;
 import java.util.function.LongBinaryOperator;
+import java.util.function.UnaryOperator;
 import java.util.stream.DoubleStream;
 import java.util.stream.IntStream;
 import java.util.stream.LongStream;
@@ -3848,12 +3850,13 @@
 
         @Override
         public int indexOf(Object o) {
-            if (o==null) {
-                for (int i=0; i<a.length; i++)
-                    if (a[i]==null)
+            E[] a = this.a;
+            if (o == null) {
+                for (int i = 0; i < a.length; i++)
+                    if (a[i] == null)
                         return i;
             } else {
-                for (int i=0; i<a.length; i++)
+                for (int i = 0; i < a.length; i++)
                     if (o.equals(a[i]))
                         return i;
             }
@@ -3869,6 +3872,28 @@
         public Spliterator<E> spliterator() {
             return Spliterators.spliterator(a, Spliterator.ORDERED);
         }
+
+        @Override
+        public void forEach(Consumer<? super E> action) {
+            Objects.requireNonNull(action);
+            for (E e : a) {
+                action.accept(e);
+            }
+        }
+
+        @Override
+        public void replaceAll(UnaryOperator<E> operator) {
+            Objects.requireNonNull(operator);
+            E[] a = this.a;
+            for (int i = 0; i < a.length; i++) {
+                a[i] = operator.apply(a[i]);
+            }
+        }
+
+        @Override
+        public void sort(Comparator<? super E> c) {
+            Arrays.sort(a, c);
+        }
     }
 
     /**
--- a/jdk/src/share/classes/java/util/logging/LogManager.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/java/util/logging/LogManager.java	Wed Jul 05 19:33:51 2017 +0200
@@ -570,7 +570,7 @@
         // the context requires default loggers, will be added to the context
         // logger's tree.
         final Logger getGlobalLogger() {
-            @SuppressWarnings("deprecated") // avoids initialization cycles.
+            @SuppressWarnings("deprecation") // avoids initialization cycles.
             final Logger global = Logger.global;
             return global;
         }
@@ -642,7 +642,7 @@
             // method be called for anything else than Logger.global
             // or owner.rootLogger.
             if (!requiresDefaultLoggers() || logger == null
-                    || logger != Logger.global && logger != LogManager.this.rootLogger) {
+                    || logger != getGlobalLogger() && logger != LogManager.this.rootLogger ) {
 
                 // the case where we have a non null logger which is neither
                 // Logger.global nor manager.rootLogger indicates a serious
--- a/jdk/src/share/classes/javax/imageio/ImageIO.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/ImageIO.java	Wed Jul 05 19:33:51 2017 +0200
@@ -339,7 +339,7 @@
             throw new IllegalArgumentException("input == null!");
         }
 
-        Iterator iter;
+        Iterator<ImageInputStreamSpi> iter;
         // Ensure category is present
         try {
             iter = theRegistry.getServiceProviders(ImageInputStreamSpi.class,
@@ -351,7 +351,7 @@
         boolean usecache = getUseCache() && hasCachePermission();
 
         while (iter.hasNext()) {
-            ImageInputStreamSpi spi = (ImageInputStreamSpi)iter.next();
+            ImageInputStreamSpi spi = iter.next();
             if (spi.getInputClass().isInstance(input)) {
                 try {
                     return spi.createInputStreamInstance(input,
@@ -401,7 +401,7 @@
             throw new IllegalArgumentException("output == null!");
         }
 
-        Iterator iter;
+        Iterator<ImageOutputStreamSpi> iter;
         // Ensure category is present
         try {
             iter = theRegistry.getServiceProviders(ImageOutputStreamSpi.class,
@@ -413,7 +413,7 @@
         boolean usecache = getUseCache() && hasCachePermission();
 
         while (iter.hasNext()) {
-            ImageOutputStreamSpi spi = (ImageOutputStreamSpi)iter.next();
+            ImageOutputStreamSpi spi = iter.next();
             if (spi.getOutputClass().isInstance(output)) {
                 try {
                     return spi.createOutputStreamInstance(output,
@@ -512,9 +512,9 @@
 
     static class ImageReaderIterator implements Iterator<ImageReader> {
         // Contains ImageReaderSpis
-        public Iterator iter;
+        private Iterator<ImageReaderSpi> iter;
 
-        public ImageReaderIterator(Iterator iter) {
+        public ImageReaderIterator(Iterator<ImageReaderSpi> iter) {
             this.iter = iter;
         }
 
@@ -525,7 +525,7 @@
         public ImageReader next() {
             ImageReaderSpi spi = null;
             try {
-                spi = (ImageReaderSpi)iter.next();
+                spi = iter.next();
                 return spi.createReaderInstance();
             } catch (IOException e) {
                 // Deregister the spi in this case, but only as
@@ -640,7 +640,7 @@
         if (input == null) {
             throw new IllegalArgumentException("input == null!");
         }
-        Iterator iter;
+        Iterator<ImageReaderSpi> iter;
         // Ensure category is present
         try {
             iter = theRegistry.getServiceProviders(ImageReaderSpi.class,
@@ -702,7 +702,7 @@
         if (formatName == null) {
             throw new IllegalArgumentException("formatName == null!");
         }
-        Iterator iter;
+        Iterator<ImageReaderSpi> iter;
         // Ensure category is present
         try {
             iter = theRegistry.getServiceProviders(ImageReaderSpi.class,
@@ -738,7 +738,7 @@
             throw new IllegalArgumentException("fileSuffix == null!");
         }
         // Ensure category is present
-        Iterator iter;
+        Iterator<ImageReaderSpi> iter;
         try {
             iter = theRegistry.getServiceProviders(ImageReaderSpi.class,
                                    new ContainsFilter(readerFileSuffixesMethod,
@@ -773,7 +773,7 @@
             throw new IllegalArgumentException("MIMEType == null!");
         }
         // Ensure category is present
-        Iterator iter;
+        Iterator<ImageReaderSpi> iter;
         try {
             iter = theRegistry.getServiceProviders(ImageReaderSpi.class,
                                       new ContainsFilter(readerMIMETypesMethod,
@@ -826,9 +826,9 @@
 
     static class ImageWriterIterator implements Iterator<ImageWriter> {
         // Contains ImageWriterSpis
-        public Iterator iter;
+        private Iterator<ImageWriterSpi> iter;
 
-        public ImageWriterIterator(Iterator iter) {
+        public ImageWriterIterator(Iterator<ImageWriterSpi> iter) {
             this.iter = iter;
         }
 
@@ -839,7 +839,7 @@
         public ImageWriter next() {
             ImageWriterSpi spi = null;
             try {
-                spi = (ImageWriterSpi)iter.next();
+                spi = iter.next();
                 return spi.createWriterInstance();
             } catch (IOException e) {
                 // Deregister the spi in this case, but only as a writerSpi
@@ -885,7 +885,7 @@
         if (formatName == null) {
             throw new IllegalArgumentException("formatName == null!");
         }
-        Iterator iter;
+        Iterator<ImageWriterSpi> iter;
         // Ensure category is present
         try {
             iter = theRegistry.getServiceProviders(ImageWriterSpi.class,
@@ -919,7 +919,7 @@
         if (fileSuffix == null) {
             throw new IllegalArgumentException("fileSuffix == null!");
         }
-        Iterator iter;
+        Iterator<ImageWriterSpi> iter;
         // Ensure category is present
         try {
             iter = theRegistry.getServiceProviders(ImageWriterSpi.class,
@@ -953,7 +953,7 @@
         if (MIMEType == null) {
             throw new IllegalArgumentException("MIMEType == null!");
         }
-        Iterator iter;
+        Iterator<ImageWriterSpi> iter;
         // Ensure category is present
         try {
             iter = theRegistry.getServiceProviders(ImageWriterSpi.class,
@@ -1002,7 +1002,7 @@
 
         ImageReaderSpi readerSpi = reader.getOriginatingProvider();
         if (readerSpi == null) {
-            Iterator readerSpiIter;
+            Iterator<ImageReaderSpi> readerSpiIter;
             // Ensure category is present
             try {
                 readerSpiIter =
@@ -1013,7 +1013,7 @@
             }
 
             while (readerSpiIter.hasNext()) {
-                ImageReaderSpi temp = (ImageReaderSpi) readerSpiIter.next();
+                ImageReaderSpi temp = readerSpiIter.next();
                 if (temp.isOwnReader(reader)) {
                     readerSpi = temp;
                     break;
@@ -1029,7 +1029,7 @@
             return null;
         }
 
-        Class writerSpiClass = null;
+        Class<?> writerSpiClass = null;
         try {
             writerSpiClass = Class.forName(writerNames[0], true,
                                            ClassLoader.getSystemClassLoader());
@@ -1082,7 +1082,7 @@
 
         ImageWriterSpi writerSpi = writer.getOriginatingProvider();
         if (writerSpi == null) {
-            Iterator writerSpiIter;
+            Iterator<ImageWriterSpi> writerSpiIter;
             // Ensure category is present
             try {
                 writerSpiIter =
@@ -1093,7 +1093,7 @@
             }
 
             while (writerSpiIter.hasNext()) {
-                ImageWriterSpi temp = (ImageWriterSpi) writerSpiIter.next();
+                ImageWriterSpi temp = writerSpiIter.next();
                 if (temp.isOwnWriter(writer)) {
                     writerSpi = temp;
                     break;
@@ -1109,7 +1109,7 @@
             return null;
         }
 
-        Class readerSpiClass = null;
+        Class<?> readerSpiClass = null;
         try {
             readerSpiClass = Class.forName(readerNames[0], true,
                                            ClassLoader.getSystemClassLoader());
@@ -1160,7 +1160,7 @@
             throw new IllegalArgumentException("formatName == null!");
         }
 
-        Iterator iter;
+        Iterator<ImageWriterSpi> iter;
         // Ensure category is present
         try {
             iter = theRegistry.getServiceProviders(ImageWriterSpi.class,
@@ -1178,9 +1178,9 @@
         implements Iterator<ImageTranscoder>
     {
         // Contains ImageTranscoderSpis
-        public Iterator iter;
+        public Iterator<ImageTranscoderSpi> iter;
 
-        public ImageTranscoderIterator(Iterator iter) {
+        public ImageTranscoderIterator(Iterator<ImageTranscoderSpi> iter) {
             this.iter = iter;
         }
 
@@ -1190,7 +1190,7 @@
 
         public ImageTranscoder next() {
             ImageTranscoderSpi spi = null;
-            spi = (ImageTranscoderSpi)iter.next();
+            spi = iter.next();
             return spi.createTranscoderInstance();
         }
 
@@ -1249,7 +1249,7 @@
         ServiceRegistry.Filter filter =
             new TranscoderFilter(readerSpi, writerSpi);
 
-        Iterator iter;
+        Iterator<ImageTranscoderSpi> iter;
         // Ensure category is present
         try {
             iter = theRegistry.getServiceProviders(ImageTranscoderSpi.class,
@@ -1435,12 +1435,12 @@
             throw new IllegalArgumentException("stream == null!");
         }
 
-        Iterator iter = getImageReaders(stream);
+        Iterator<ImageReader> iter = getImageReaders(stream);
         if (!iter.hasNext()) {
             return null;
         }
 
-        ImageReader reader = (ImageReader)iter.next();
+        ImageReader reader = iter.next();
         ImageReadParam param = reader.getDefaultReadParam();
         reader.setInput(stream, true, true);
         BufferedImage bi;
--- a/jdk/src/share/classes/javax/imageio/ImageReader.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/ImageReader.java	Wed Jul 05 19:33:51 2017 +0200
@@ -291,7 +291,7 @@
         if (input != null) {
             boolean found = false;
             if (originatingProvider != null) {
-                Class[] classes = originatingProvider.getInputTypes();
+                Class<?>[] classes = originatingProvider.getInputTypes();
                 for (int i = 0; i < classes.length; i++) {
                     if (classes[i].isInstance(input)) {
                         found = true;
@@ -793,7 +793,7 @@
     }
 
     private IIOMetadata getMetadata(String formatName,
-                                    Set nodeNames,
+                                    Set<String> nodeNames,
                                     boolean wantStream,
                                     int imageIndex) throws IOException {
         if (formatName == null) {
@@ -1065,10 +1065,10 @@
 
         BufferedImage im = read(imageIndex, param);
 
-        ArrayList thumbnails = null;
+        ArrayList<BufferedImage> thumbnails = null;
         int numThumbnails = getNumThumbnails(imageIndex);
         if (numThumbnails > 0) {
-            thumbnails = new ArrayList();
+            thumbnails = new ArrayList<>();
             for (int j = 0; j < numThumbnails; j++) {
                 thumbnails.add(readThumbnail(imageIndex, j));
             }
@@ -1156,7 +1156,7 @@
         readAll(Iterator<? extends ImageReadParam> params)
         throws IOException
     {
-        List output = new ArrayList();
+        List<IIOImage> output = new ArrayList<>();
 
         int imageIndex = getMinIndex();
 
@@ -1187,10 +1187,10 @@
                 break;
             }
 
-            ArrayList thumbnails = null;
+            ArrayList<BufferedImage> thumbnails = null;
             int numThumbnails = getNumThumbnails(imageIndex);
             if (numThumbnails > 0) {
-                thumbnails = new ArrayList();
+                thumbnails = new ArrayList<>();
                 for (int j = 0; j < numThumbnails; j++) {
                     thumbnails.add(readThumbnail(imageIndex, j));
                 }
@@ -1797,9 +1797,9 @@
 
     // Add an element to a list, creating a new list if the
     // existing list is null, and return the list.
-    static List addToList(List l, Object elt) {
+    static <T> List<T> addToList(List<T> l, T elt) {
         if (l == null) {
-            l = new ArrayList();
+            l = new ArrayList<>();
         }
         l.add(elt);
         return l;
@@ -1808,7 +1808,7 @@
 
     // Remove an element from a list, discarding the list if the
     // resulting list is empty, and return the list or null.
-    static List removeFromList(List l, Object elt) {
+    static <T> List<T> removeFromList(List<T> l, T elt) {
         if (l == null) {
             return l;
         }
@@ -2461,10 +2461,10 @@
              * If that throws MissingResourceException, then try the
              * system class loader.
              */
-            ClassLoader loader = (ClassLoader)
+            ClassLoader loader =
                 java.security.AccessController.doPrivileged(
-                   new java.security.PrivilegedAction() {
-                      public Object run() {
+                   new java.security.PrivilegedAction<ClassLoader>() {
+                      public ClassLoader run() {
                         return Thread.currentThread().getContextClassLoader();
                       }
                 });
--- a/jdk/src/share/classes/javax/imageio/ImageTypeSpecifier.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/ImageTypeSpecifier.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1075,7 +1075,7 @@
                                             new Point(0, 0));
             return new BufferedImage(colorModel, raster,
                                      colorModel.isAlphaPremultiplied(),
-                                     new Hashtable());
+                                     new Hashtable<>());
         } catch (NegativeArraySizeException e) {
             // Exception most likely thrown from a DataBuffer constructor
             throw new IllegalArgumentException
--- a/jdk/src/share/classes/javax/imageio/ImageWriter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/ImageWriter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -205,7 +205,7 @@
         if (output != null) {
             ImageWriterSpi provider = getOriginatingProvider();
             if (provider != null) {
-                Class[] classes = provider.getOutputTypes();
+                Class<?>[] classes = provider.getOutputTypes();
                 boolean found = false;
                 for (int i = 0; i < classes.length; i++) {
                     if (classes[i].isInstance(output)) {
@@ -1964,10 +1964,10 @@
              * If that throws MissingResourceException, then try the
              * system class loader.
              */
-            ClassLoader loader = (ClassLoader)
+            ClassLoader loader =
                 java.security.AccessController.doPrivileged(
-                   new java.security.PrivilegedAction() {
-                      public Object run() {
+                   new java.security.PrivilegedAction<ClassLoader>() {
+                      public ClassLoader run() {
                         return Thread.currentThread().getContextClassLoader();
                       }
                 });
--- a/jdk/src/share/classes/javax/imageio/metadata/IIOMetadata.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/metadata/IIOMetadata.java	Wed Jul 05 19:33:51 2017 +0200
@@ -395,15 +395,15 @@
             throw new IllegalArgumentException("Unsupported format name");
         }
         try {
-            Class cls = null;
+            Class<?> cls = null;
             final Object o = this;
 
             // firstly we try to use classloader used for loading
             // the IIOMetadata implemantation for this plugin.
-            ClassLoader loader = (ClassLoader)
+            ClassLoader loader =
                 java.security.AccessController.doPrivileged(
-                    new java.security.PrivilegedAction() {
-                            public Object run() {
+                    new java.security.PrivilegedAction<ClassLoader>() {
+                            public ClassLoader run() {
                                 return o.getClass().getClassLoader();
                             }
                         });
@@ -415,10 +415,10 @@
                 // we failed to load IIOMetadataFormat class by
                 // using IIOMetadata classloader.Next try is to
                 // use thread context classloader.
-                loader = (ClassLoader)
+                loader =
                     java.security.AccessController.doPrivileged(
-                        new java.security.PrivilegedAction() {
-                                public Object run() {
+                        new java.security.PrivilegedAction<ClassLoader>() {
+                                public ClassLoader run() {
                                     return Thread.currentThread().getContextClassLoader();
                                 }
                         });
--- a/jdk/src/share/classes/javax/imageio/metadata/IIOMetadataFormatImpl.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/metadata/IIOMetadataFormatImpl.java	Wed Jul 05 19:33:51 2017 +0200
@@ -90,7 +90,7 @@
     private String rootName;
 
     // Element name (String) -> Element
-    private HashMap elementMap = new HashMap();
+    private HashMap<String, Element> elementMap = new HashMap<>();
 
     class Element {
         String elementName;
@@ -100,17 +100,17 @@
         int maxChildren = 0;
 
         // Child names (Strings)
-        List childList = new ArrayList();
+        List<String> childList = new ArrayList<>();
 
         // Parent names (Strings)
-        List parentList = new ArrayList();
+        List<String> parentList = new ArrayList<>();
 
         // List of attribute names in the order they were added
-        List attrList = new ArrayList();
+        List<String> attrList = new ArrayList<>();
         // Attr name (String) -> Attribute
-        Map attrMap = new HashMap();
+        Map<String, Attribute> attrMap = new HashMap<>();
 
-        ObjectValue objectValue;
+        ObjectValue<?> objectValue;
     }
 
     class Attribute {
@@ -122,7 +122,7 @@
         String defaultValue = null;
 
         // enumeration
-        List enumeratedValues;
+        List<String> enumeratedValues;
 
         // range
         String minValue;
@@ -133,17 +133,18 @@
         int listMaxLength;
     }
 
-    class ObjectValue {
+    class ObjectValue<T> {
         int valueType = VALUE_NONE;
-        Class classType = null;
-        Object defaultValue = null;
+        // ? extends T So that ObjectValue<Object> can take Class<?>
+        Class<? extends T> classType = null;
+        T defaultValue = null;
 
         // Meaningful only if valueType == VALUE_ENUMERATION
-        List enumeratedValues = null;
+        List<? extends T> enumeratedValues = null;
 
         // Meaningful only if valueType == VALUE_RANGE
-        Comparable minValue = null;
-        Comparable maxValue = null;
+        Comparable<? super T> minValue = null;
+        Comparable<? super T> maxValue = null;
 
         // Meaningful only if valueType == VALUE_LIST
         int arrayMinLength = 0;
@@ -272,7 +273,7 @@
         if (mustAppear && (elementName == null)) {
             throw new IllegalArgumentException("element name is null!");
         }
-        Element element = (Element)elementMap.get(elementName);
+        Element element = elementMap.get(elementName);
         if (mustAppear && (element == null)) {
             throw new IllegalArgumentException("No such element: " +
                                                elementName);
@@ -287,7 +288,7 @@
     // Utility method for locating an attribute
     private Attribute getAttribute(String elementName, String attrName) {
         Element element = getElement(elementName);
-        Attribute attr = (Attribute)element.attrMap.get(attrName);
+        Attribute attr = element.attrMap.get(attrName);
         if (attr == null) {
             throw new IllegalArgumentException("No such attribute \"" +
                                                attrName + "\"!");
@@ -408,9 +409,9 @@
     protected void removeElement(String elementName) {
         Element element = getElement(elementName, false);
         if (element != null) {
-            Iterator iter = element.parentList.iterator();
+            Iterator<String> iter = element.parentList.iterator();
             while (iter.hasNext()) {
-                String parentName = (String)iter.next();
+                String parentName = iter.next();
                 Element parent = getElement(parentName, false);
                 if (parent != null) {
                     parent.childList.remove(elementName);
@@ -514,7 +515,7 @@
         if (enumeratedValues.size() == 0) {
             throw new IllegalArgumentException("enumeratedValues is empty!");
         }
-        Iterator iter = enumeratedValues.iterator();
+        Iterator<String> iter = enumeratedValues.iterator();
         while (iter.hasNext()) {
             Object o = iter.next();
             if (o == null) {
@@ -681,7 +682,7 @@
                                        String attrName,
                                        boolean hasDefaultValue,
                                        boolean defaultValue) {
-        List values = new ArrayList();
+        List<String> values = new ArrayList<>();
         values.add("TRUE");
         values.add("FALSE");
 
@@ -740,7 +741,7 @@
                                       T defaultValue)
     {
         Element element = getElement(elementName);
-        ObjectValue obj = new ObjectValue();
+        ObjectValue<T> obj = new ObjectValue<>();
         obj.valueType = VALUE_ARBITRARY;
         obj.classType = classType;
         obj.defaultValue = defaultValue;
@@ -793,7 +794,7 @@
         if (enumeratedValues.size() == 0) {
             throw new IllegalArgumentException("enumeratedValues is empty!");
         }
-        Iterator iter = enumeratedValues.iterator();
+        Iterator<? extends T> iter = enumeratedValues.iterator();
         while (iter.hasNext()) {
             Object o = iter.next();
             if (o == null) {
@@ -804,7 +805,7 @@
             }
         }
 
-        ObjectValue obj = new ObjectValue();
+        ObjectValue<T> obj = new ObjectValue<>();
         obj.valueType = VALUE_ENUMERATION;
         obj.classType = classType;
         obj.defaultValue = defaultValue;
@@ -854,7 +855,7 @@
                        boolean maxInclusive)
     {
         Element element = getElement(elementName);
-        ObjectValue obj = new ObjectValue();
+        ObjectValue<T> obj = new ObjectValue<>();
         obj.valueType = VALUE_RANGE;
         if (minInclusive) {
             obj.valueType |= VALUE_RANGE_MIN_INCLUSIVE_MASK;
@@ -895,7 +896,7 @@
                                   int arrayMinLength,
                                   int arrayMaxLength) {
         Element element = getElement(elementName);
-        ObjectValue obj = new ObjectValue();
+        ObjectValue<Object> obj = new ObjectValue<>();
         obj.valueType = VALUE_LIST;
         obj.classType = classType;
         obj.arrayMinLength = arrayMinLength;
@@ -962,10 +963,10 @@
          * If that throws MissingResourceException, then try the
          * system class loader.
          */
-        ClassLoader loader = (ClassLoader)
+        ClassLoader loader =
             java.security.AccessController.doPrivileged(
-                new java.security.PrivilegedAction() {
-                   public Object run() {
+                new java.security.PrivilegedAction<ClassLoader>() {
+                   public ClassLoader run() {
                        return Thread.currentThread().getContextClassLoader();
                    }
             });
@@ -1037,17 +1038,17 @@
         if (element.childPolicy == CHILD_POLICY_EMPTY) {
             return null;
         }
-        return (String[])element.childList.toArray(new String[0]);
+        return element.childList.toArray(new String[0]);
     }
 
     // Attributes
 
     public String[] getAttributeNames(String elementName) {
         Element element = getElement(elementName);
-        List names = element.attrList;
+        List<String> names = element.attrList;
 
         String[] result = new String[names.size()];
-        return (String[])names.toArray(result);
+        return names.toArray(result);
     }
 
     public int getAttributeValueType(String elementName, String attrName) {
@@ -1079,10 +1080,9 @@
                 ("Attribute not an enumeration!");
         }
 
-        List values = attr.enumeratedValues;
-        Iterator iter = values.iterator();
+        List<String> values = attr.enumeratedValues;
         String[] result = new String[values.size()];
-        return (String[])values.toArray(result);
+        return values.toArray(result);
     }
 
     public String getAttributeMinValue(String elementName, String attrName) {
@@ -1170,7 +1170,7 @@
         if (attrName == null) {
             throw new IllegalArgumentException("attrName == null!");
         }
-        Attribute attr = (Attribute)element.attrMap.get(attrName);
+        Attribute attr = element.attrMap.get(attrName);
         if (attr == null) {
             throw new IllegalArgumentException("No such attribute!");
         }
@@ -1179,9 +1179,9 @@
         return getResource(key, locale);
     }
 
-    private ObjectValue getObjectValue(String elementName) {
+    private ObjectValue<?> getObjectValue(String elementName) {
         Element element = getElement(elementName);
-        ObjectValue objv = element.objectValue;
+        ObjectValue<?> objv = element.objectValue;
         if (objv == null) {
             throw new IllegalArgumentException("No object within element " +
                                                elementName + "!");
@@ -1191,7 +1191,7 @@
 
     public int getObjectValueType(String elementName) {
         Element element = getElement(elementName);
-        ObjectValue objv = element.objectValue;
+        ObjectValue<?> objv = element.objectValue;
         if (objv == null) {
             return VALUE_NONE;
         }
@@ -1199,27 +1199,27 @@
     }
 
     public Class<?> getObjectClass(String elementName) {
-        ObjectValue objv = getObjectValue(elementName);
+        ObjectValue<?> objv = getObjectValue(elementName);
         return objv.classType;
     }
 
     public Object getObjectDefaultValue(String elementName) {
-        ObjectValue objv = getObjectValue(elementName);
+        ObjectValue<?> objv = getObjectValue(elementName);
         return objv.defaultValue;
     }
 
     public Object[] getObjectEnumerations(String elementName) {
-        ObjectValue objv = getObjectValue(elementName);
+        ObjectValue<?> objv = getObjectValue(elementName);
         if (objv.valueType != VALUE_ENUMERATION) {
             throw new IllegalArgumentException("Not an enumeration!");
         }
-        List vlist = objv.enumeratedValues;
+        List<?> vlist = objv.enumeratedValues;
         Object[] values = new Object[vlist.size()];
         return vlist.toArray(values);
     }
 
     public Comparable<?> getObjectMinValue(String elementName) {
-        ObjectValue objv = getObjectValue(elementName);
+        ObjectValue<?> objv = getObjectValue(elementName);
         if ((objv.valueType & VALUE_RANGE) != VALUE_RANGE) {
             throw new IllegalArgumentException("Not a range!");
         }
@@ -1227,7 +1227,7 @@
     }
 
     public Comparable<?> getObjectMaxValue(String elementName) {
-        ObjectValue objv = getObjectValue(elementName);
+        ObjectValue<?> objv = getObjectValue(elementName);
         if ((objv.valueType & VALUE_RANGE) != VALUE_RANGE) {
             throw new IllegalArgumentException("Not a range!");
         }
@@ -1235,7 +1235,7 @@
     }
 
     public int getObjectArrayMinLength(String elementName) {
-        ObjectValue objv = getObjectValue(elementName);
+        ObjectValue<?> objv = getObjectValue(elementName);
         if (objv.valueType != VALUE_LIST) {
             throw new IllegalArgumentException("Not a list!");
         }
@@ -1243,7 +1243,7 @@
     }
 
     public int getObjectArrayMaxLength(String elementName) {
-        ObjectValue objv = getObjectValue(elementName);
+        ObjectValue<?> objv = getObjectValue(elementName);
         if (objv.valueType != VALUE_LIST) {
             throw new IllegalArgumentException("Not a list!");
         }
--- a/jdk/src/share/classes/javax/imageio/metadata/IIOMetadataNode.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/metadata/IIOMetadataNode.java	Wed Jul 05 19:33:51 2017 +0200
@@ -50,9 +50,9 @@
 
 class IIONamedNodeMap implements NamedNodeMap {
 
-    List nodes;
+    List<? extends Node> nodes;
 
-    public IIONamedNodeMap(List nodes) {
+    public IIONamedNodeMap(List<? extends Node> nodes) {
         this.nodes = nodes;
     }
 
@@ -61,9 +61,9 @@
     }
 
     public Node getNamedItem(String name) {
-        Iterator iter = nodes.iterator();
+        Iterator<? extends Node> iter = nodes.iterator();
         while (iter.hasNext()) {
-            Node node = (Node)iter.next();
+            Node node = iter.next();
             if (name.equals(node.getNodeName())) {
                 return node;
             }
@@ -73,7 +73,7 @@
     }
 
     public Node item(int index) {
-        Node node = (Node)nodes.get(index);
+        Node node = nodes.get(index);
         return node;
     }
 
@@ -111,9 +111,9 @@
 
 class IIONodeList implements NodeList {
 
-    List nodes;
+    List<? extends Node> nodes;
 
-    public IIONodeList(List nodes) {
+    public IIONodeList(List<? extends Node> nodes) {
         this.nodes = nodes;
     }
 
@@ -125,7 +125,7 @@
         if (index < 0 || index > nodes.size()) {
             return null;
         }
-        return (Node)nodes.get(index);
+        return nodes.get(index);
     }
 }
 
@@ -285,7 +285,7 @@
      * A <code>List</code> of <code>IIOAttr</code> nodes representing
      * attributes.
      */
-    private List attributes = new ArrayList();
+    private List<IIOAttr> attributes = new ArrayList<>();
 
     /**
      * Constructs an empty <code>IIOMetadataNode</code>.
@@ -789,7 +789,7 @@
     private void removeAttribute(String name, boolean checkPresent) {
         int numAttributes = attributes.size();
         for (int i = 0; i < numAttributes; i++) {
-            IIOAttr attr = (IIOAttr)attributes.get(i);
+            IIOAttr attr = attributes.get(i);
             if (name.equals(attr.getName())) {
                 attr.setOwnerElement(null);
                 attributes.remove(i);
@@ -873,12 +873,12 @@
     }
 
     public NodeList getElementsByTagName(String name) {
-        List l = new ArrayList();
+        List<Node> l = new ArrayList<>();
         getElementsByTagName(name, l);
         return new IIONodeList(l);
     }
 
-    private void getElementsByTagName(String name, List l) {
+    private void getElementsByTagName(String name, List<Node> l) {
         if (nodeName.equals(name)) {
             l.add(this);
         }
--- a/jdk/src/share/classes/javax/imageio/spi/DigraphNode.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/spi/DigraphNode.java	Wed Jul 05 19:33:51 2017 +0200
@@ -39,17 +39,17 @@
  * the current node) may be queried.
  *
  */
-class DigraphNode implements Cloneable, Serializable {
+class DigraphNode<E> implements Cloneable, Serializable {
     private static final long serialVersionUID = 5308261378582246841L;
 
     /** The data associated with this node. */
-    protected Object data;
+    protected E data;
 
     /**
      * A <code>Set</code> of neighboring nodes pointed to by this
      * node.
      */
-    protected Set outNodes = new HashSet();
+    protected Set<DigraphNode<E>> outNodes = new HashSet<>();
 
     /** The in-degree of the node. */
     protected int inDegree = 0;
@@ -58,14 +58,14 @@
      * A <code>Set</code> of neighboring nodes that point to this
      * node.
      */
-    private Set inNodes = new HashSet();
+    private Set<DigraphNode<E>> inNodes = new HashSet<>();
 
-    public DigraphNode(Object data) {
+    public DigraphNode(E data) {
         this.data = data;
     }
 
     /** Returns the <code>Object</code> referenced by this node. */
-    public Object getData() {
+    public E getData() {
         return data;
     }
 
@@ -73,7 +73,7 @@
      * Returns an <code>Iterator</code> containing the nodes pointed
      * to by this node.
      */
-    public Iterator getOutNodes() {
+    public Iterator<DigraphNode<E>> getOutNodes() {
         return outNodes.iterator();
     }
 
@@ -86,7 +86,7 @@
      * @return <code>true</code> if the node was not previously the
      * target of an edge.
      */
-    public boolean addEdge(DigraphNode node) {
+    public boolean addEdge(DigraphNode<E> node) {
         if (outNodes.contains(node)) {
             return false;
         }
@@ -105,7 +105,7 @@
      *
      * @return <code>true</code> if the node is the target of an edge.
      */
-    public boolean hasEdge(DigraphNode node) {
+    public boolean hasEdge(DigraphNode<E> node) {
         return outNodes.contains(node);
     }
 
@@ -116,7 +116,7 @@
      * @return <code>true</code> if the node was previously the target
      * of an edge.
      */
-    public boolean removeEdge(DigraphNode node) {
+    public boolean removeEdge(DigraphNode<E> node) {
         if (!outNodes.contains(node)) {
             return false;
         }
@@ -132,15 +132,17 @@
      * appropriately.
      */
     public void dispose() {
-        Object[] inNodesArray = inNodes.toArray();
+        @SuppressWarnings("unchecked")
+        DigraphNode<E>[] inNodesArray = (DigraphNode<E>[])inNodes.toArray();
         for(int i=0; i<inNodesArray.length; i++) {
-            DigraphNode node = (DigraphNode) inNodesArray[i];
+            DigraphNode<E> node = inNodesArray[i];
             node.removeEdge(this);
         }
 
-        Object[] outNodesArray = outNodes.toArray();
+        @SuppressWarnings("unchecked")
+        DigraphNode<E>[] outNodesArray = (DigraphNode<E>[])outNodes.toArray();
         for(int i=0; i<outNodesArray.length; i++) {
-            DigraphNode node = (DigraphNode) outNodesArray[i];
+            DigraphNode<E> node = outNodesArray[i];
             removeEdge(node);
         }
     }
--- a/jdk/src/share/classes/javax/imageio/spi/IIORegistry.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/spi/IIORegistry.java	Wed Jul 05 19:33:51 2017 +0200
@@ -115,7 +115,7 @@
      * A <code>Vector</code> containing the valid IIO registry
      * categories (superinterfaces) to be used in the constructor.
      */
-    private static final Vector initialCategories = new Vector(5);
+    private static final Vector<Class<?>> initialCategories = new Vector<>(5);
 
     static {
         initialCategories.add(ImageReaderSpi.class);
@@ -198,9 +198,10 @@
 
         ClassLoader loader = Thread.currentThread().getContextClassLoader();
 
-        Iterator categories = getCategories();
+        Iterator<Class<?>> categories = getCategories();
         while (categories.hasNext()) {
-            Class<IIOServiceProvider> c = (Class)categories.next();
+            @SuppressWarnings("unchecked")
+            Class<IIOServiceProvider> c = (Class<IIOServiceProvider>)categories.next();
             Iterator<IIOServiceProvider> riter =
                     ServiceLoader.load(c, loader).iterator();
             while (riter.hasNext()) {
@@ -234,12 +235,13 @@
           file read capability is restricted (like the
           applet context case).
          */
-        PrivilegedAction doRegistration =
-            new PrivilegedAction() {
+        PrivilegedAction<Object> doRegistration =
+            new PrivilegedAction<Object>() {
                 public Object run() {
-                    Iterator categories = getCategories();
+                    Iterator<Class<?>> categories = getCategories();
                     while (categories.hasNext()) {
-                        Class<IIOServiceProvider> c = (Class)categories.next();
+                        @SuppressWarnings("unchecked")
+                        Class<IIOServiceProvider> c = (Class<IIOServiceProvider>)categories.next();
                         for (IIOServiceProvider p : ServiceLoader.loadInstalled(c)) {
                             registerServiceProvider(p);
                         }
--- a/jdk/src/share/classes/javax/imageio/spi/ImageReaderSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/spi/ImageReaderSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -81,14 +81,14 @@
      * the equivalent array <code>{ ImageInputStream.class }</code>.
      */
     @Deprecated
-    public static final Class[] STANDARD_INPUT_TYPE =
+    public static final Class<?>[] STANDARD_INPUT_TYPE =
         { ImageInputStream.class };
 
     /**
      * An array of <code>Class</code> objects to be returned from
      * <code>getInputTypes</code>, initially <code>null</code>.
      */
-    protected Class[] inputTypes = null;
+    protected Class<?>[] inputTypes = null;
 
     /**
      * An array of strings to be returned from
@@ -101,7 +101,7 @@
      * The <code>Class</code> of the reader, initially
      * <code>null</code>.
      */
-    private Class readerClass = null;
+    private Class<?> readerClass = null;
 
     /**
      * Constructs a blank <code>ImageReaderSpi</code>.  It is up to
@@ -197,7 +197,7 @@
                           String[] suffixes,
                           String[] MIMETypes,
                           String readerClassName,
-                          Class[] inputTypes,
+                          Class<?>[] inputTypes,
                           String[] writerSpiNames,
                           boolean supportsStandardStreamMetadataFormat,
                           String nativeStreamMetadataFormatName,
@@ -252,9 +252,9 @@
      * returned.
      *
      * @return a non-<code>null</code> array of
-     * <code>Class</code>objects of length at least 1.
+     * <code>Class</code> objects of length at least 1.
      */
-    public Class[] getInputTypes() {
+    public Class<?>[] getInputTypes() {
         return inputTypes.clone();
     }
 
--- a/jdk/src/share/classes/javax/imageio/spi/ImageReaderWriterSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/spi/ImageReaderWriterSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -587,7 +587,7 @@
             throw new IllegalArgumentException("Unsupported format name");
         }
         try {
-            Class cls = Class.forName(formatClassName, true,
+            Class<?> cls = Class.forName(formatClassName, true,
                                       ClassLoader.getSystemClassLoader());
             Method meth = cls.getMethod("getInstance");
             return (IIOMetadataFormat) meth.invoke(null);
--- a/jdk/src/share/classes/javax/imageio/spi/ImageWriterSpi.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/spi/ImageWriterSpi.java	Wed Jul 05 19:33:51 2017 +0200
@@ -83,14 +83,14 @@
      * the equivalent array <code>{ ImageOutputStream.class }</code>.
      */
     @Deprecated
-    public static final Class[] STANDARD_OUTPUT_TYPE =
+    public static final Class<?>[] STANDARD_OUTPUT_TYPE =
         { ImageOutputStream.class };
 
     /**
      * An array of <code>Class</code> objects to be returned from
      * <code>getOutputTypes</code>, initially <code>null</code>.
      */
-    protected Class[] outputTypes = null;
+    protected Class<?>[] outputTypes = null;
 
     /**
      * An array of strings to be returned from
@@ -103,7 +103,7 @@
      * The <code>Class</code> of the writer, initially
      * <code>null</code>.
      */
-    private Class writerClass = null;
+    private Class<?> writerClass = null;
 
     /**
      * Constructs a blank <code>ImageWriterSpi</code>.  It is up to
@@ -198,7 +198,7 @@
                           String[] suffixes,
                           String[] MIMETypes,
                           String writerClassName,
-                          Class[] outputTypes,
+                          Class<?>[] outputTypes,
                           String[] readerSpiNames,
                           boolean supportsStandardStreamMetadataFormat,
                           String nativeStreamMetadataFormatName,
@@ -265,9 +265,9 @@
      * returned.
      *
      * @return a non-<code>null</code> array of
-     * <code>Class</code>objects of length at least 1.
+     * <code>Class</code> objects of length at least 1.
      */
-    public Class[] getOutputTypes() {
+    public Class<?>[] getOutputTypes() {
         return outputTypes.clone();
     }
 
--- a/jdk/src/share/classes/javax/imageio/spi/PartiallyOrderedSet.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/spi/PartiallyOrderedSet.java	Wed Jul 05 19:33:51 2017 +0200
@@ -51,17 +51,17 @@
  * supplied by a trusted vendor over those supplied by another.
  *
  */
-class PartiallyOrderedSet extends AbstractSet {
+class PartiallyOrderedSet<E> extends AbstractSet<E> {
 
     // The topological sort (roughly) follows the algorithm described in
     // Horowitz and Sahni, _Fundamentals of Data Structures_ (1976),
     // p. 315.
 
     // Maps Objects to DigraphNodes that contain them
-    private Map poNodes = new HashMap();
+    private Map<E, DigraphNode<E>> poNodes = new HashMap<>();
 
     // The set of Objects
-    private Set nodes = poNodes.keySet();
+    private Set<E> nodes = poNodes.keySet();
 
     /**
      * Constructs a <code>PartiallyOrderedSet</code>.
@@ -81,20 +81,20 @@
      * collection, with an ordering that respects the orderings set
      * by the <code>setOrdering</code> method.
      */
-    public Iterator iterator() {
-        return new PartialOrderIterator(poNodes.values().iterator());
+    public Iterator<E> iterator() {
+        return new PartialOrderIterator<>(poNodes.values().iterator());
     }
 
     /**
      * Adds an <code>Object</code> to this
      * <code>PartiallyOrderedSet</code>.
      */
-    public boolean add(Object o) {
+    public boolean add(E o) {
         if (nodes.contains(o)) {
             return false;
         }
 
-        DigraphNode node = new DigraphNode(o);
+        DigraphNode<E> node = new DigraphNode<>(o);
         poNodes.put(o, node);
         return true;
     }
@@ -104,7 +104,7 @@
      * <code>PartiallyOrderedSet</code>.
      */
     public boolean remove(Object o) {
-        DigraphNode node = (DigraphNode)poNodes.get(o);
+        DigraphNode<E> node = poNodes.get(o);
         if (node == null) {
             return false;
         }
@@ -127,11 +127,9 @@
      * @return <code>true</code> if no prior ordering existed
      * between the nodes, <code>false</code>otherwise.
      */
-    public boolean setOrdering(Object first, Object second) {
-        DigraphNode firstPONode =
-            (DigraphNode)poNodes.get(first);
-        DigraphNode secondPONode =
-            (DigraphNode)poNodes.get(second);
+    public boolean setOrdering(E first, E second) {
+        DigraphNode<E> firstPONode = poNodes.get(first);
+        DigraphNode<E> secondPONode = poNodes.get(second);
 
         secondPONode.removeEdge(firstPONode);
         return firstPONode.addEdge(secondPONode);
@@ -142,11 +140,9 @@
      *
      * @return true if a prior prefence existed between the nodes.
      */
-    public boolean unsetOrdering(Object first, Object second) {
-        DigraphNode firstPONode =
-            (DigraphNode)poNodes.get(first);
-        DigraphNode secondPONode =
-            (DigraphNode)poNodes.get(second);
+    public boolean unsetOrdering(E first, E second) {
+        DigraphNode<E> firstPONode = poNodes.get(first);
+        DigraphNode<E> secondPONode = poNodes.get(second);
 
         return firstPONode.removeEdge(secondPONode) ||
             secondPONode.removeEdge(firstPONode);
@@ -156,25 +152,23 @@
      * Returns <code>true</code> if an ordering exists between two
      * nodes.
      */
-    public boolean hasOrdering(Object preferred, Object other) {
-        DigraphNode preferredPONode =
-            (DigraphNode)poNodes.get(preferred);
-        DigraphNode otherPONode =
-            (DigraphNode)poNodes.get(other);
+    public boolean hasOrdering(E preferred, E other) {
+        DigraphNode<E> preferredPONode = poNodes.get(preferred);
+        DigraphNode<E> otherPONode = poNodes.get(other);
 
         return preferredPONode.hasEdge(otherPONode);
     }
 }
 
-class PartialOrderIterator implements Iterator {
+class PartialOrderIterator<E> implements Iterator<E> {
 
-    LinkedList zeroList = new LinkedList();
-    Map inDegrees = new HashMap(); // DigraphNode -> Integer
+    LinkedList<DigraphNode<E>> zeroList = new LinkedList<>();
+    Map<DigraphNode<E>, Integer> inDegrees = new HashMap<>();
 
-    public PartialOrderIterator(Iterator iter) {
+    public PartialOrderIterator(Iterator<DigraphNode<E>> iter) {
         // Initialize scratch in-degree values, zero list
         while (iter.hasNext()) {
-            DigraphNode node = (DigraphNode)iter.next();
+            DigraphNode<E> node = iter.next();
             int inDegree = node.getInDegree();
             inDegrees.put(node, new Integer(inDegree));
 
@@ -189,14 +183,14 @@
         return !zeroList.isEmpty();
     }
 
-    public Object next() {
-        DigraphNode first = (DigraphNode)zeroList.removeFirst();
+    public E next() {
+        DigraphNode<E> first = zeroList.removeFirst();
 
         // For each out node of the output node, decrement its in-degree
-        Iterator outNodes = first.getOutNodes();
+        Iterator<DigraphNode<E>> outNodes = first.getOutNodes();
         while (outNodes.hasNext()) {
-            DigraphNode node = (DigraphNode)outNodes.next();
-            int inDegree = ((Integer)inDegrees.get(node)).intValue() - 1;
+            DigraphNode<E> node = outNodes.next();
+            int inDegree = inDegrees.get(node).intValue() - 1;
             inDegrees.put(node, new Integer(inDegree));
 
             // If the in-degree has fallen to 0, place the node on the list
--- a/jdk/src/share/classes/javax/imageio/spi/ServiceRegistry.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/spi/ServiceRegistry.java	Wed Jul 05 19:33:51 2017 +0200
@@ -99,7 +99,7 @@
 public class ServiceRegistry {
 
     // Class -> Registry
-    private Map categoryMap = new HashMap();
+    private Map<Class<?>, SubRegistry> categoryMap = new HashMap<>();
 
     /**
      * Constructs a <code>ServiceRegistry</code> instance with a
@@ -117,7 +117,7 @@
             throw new IllegalArgumentException("categories == null!");
         }
         while (categories.hasNext()) {
-            Class category = (Class)categories.next();
+            Class<?> category = categories.next();
             SubRegistry reg = new SubRegistry(this, category);
             categoryMap.put(category, reg);
         }
@@ -208,7 +208,7 @@
      * <code>Class</code>objects.
      */
     public Iterator<Class<?>> getCategories() {
-        Set keySet = categoryMap.keySet();
+        Set<Class<?>> keySet = categoryMap.keySet();
         return keySet.iterator();
     }
 
@@ -216,13 +216,13 @@
      * Returns an Iterator containing the subregistries to which the
      * provider belongs.
      */
-    private Iterator getSubRegistries(Object provider) {
-        List l = new ArrayList();
-        Iterator iter = categoryMap.keySet().iterator();
+    private Iterator<SubRegistry> getSubRegistries(Object provider) {
+        List<SubRegistry> l = new ArrayList<>();
+        Iterator<Class<?>> iter = categoryMap.keySet().iterator();
         while (iter.hasNext()) {
-            Class c = (Class)iter.next();
+            Class<?> c = iter.next();
             if (c.isAssignableFrom(provider.getClass())) {
-                l.add((SubRegistry)categoryMap.get(c));
+                l.add(categoryMap.get(c));
             }
         }
         return l.iterator();
@@ -259,7 +259,7 @@
         if (provider == null) {
             throw new IllegalArgumentException("provider == null!");
         }
-        SubRegistry reg = (SubRegistry)categoryMap.get(category);
+        SubRegistry reg = categoryMap.get(category);
         if (reg == null) {
             throw new IllegalArgumentException("category unknown!");
         }
@@ -292,9 +292,9 @@
         if (provider == null) {
             throw new IllegalArgumentException("provider == null!");
         }
-        Iterator regs = getSubRegistries(provider);
+        Iterator<SubRegistry> regs = getSubRegistries(provider);
         while (regs.hasNext()) {
-            SubRegistry reg = (SubRegistry)regs.next();
+            SubRegistry reg = regs.next();
             reg.registerServiceProvider(provider);
         }
     }
@@ -362,7 +362,7 @@
         if (provider == null) {
             throw new IllegalArgumentException("provider == null!");
         }
-        SubRegistry reg = (SubRegistry)categoryMap.get(category);
+        SubRegistry reg = categoryMap.get(category);
         if (reg == null) {
             throw new IllegalArgumentException("category unknown!");
         }
@@ -385,9 +385,9 @@
         if (provider == null) {
             throw new IllegalArgumentException("provider == null!");
         }
-        Iterator regs = getSubRegistries(provider);
+        Iterator<SubRegistry> regs = getSubRegistries(provider);
         while (regs.hasNext()) {
-            SubRegistry reg = (SubRegistry)regs.next();
+            SubRegistry reg = regs.next();
             reg.deregisterServiceProvider(provider);
         }
     }
@@ -408,9 +408,9 @@
         if (provider == null) {
             throw new IllegalArgumentException("provider == null!");
         }
-        Iterator regs = getSubRegistries(provider);
+        Iterator<SubRegistry> regs = getSubRegistries(provider);
         while (regs.hasNext()) {
-            SubRegistry reg = (SubRegistry)regs.next();
+            SubRegistry reg = regs.next();
             if (reg.contains(provider)) {
                 return true;
             }
@@ -442,11 +442,13 @@
      */
     public <T> Iterator<T> getServiceProviders(Class<T> category,
                                                boolean useOrdering) {
-        SubRegistry reg = (SubRegistry)categoryMap.get(category);
+        SubRegistry reg = categoryMap.get(category);
         if (reg == null) {
             throw new IllegalArgumentException("category unknown!");
         }
-        return reg.getServiceProviders(useOrdering);
+        @SuppressWarnings("unchecked")
+        Iterator<T> it = (Iterator<T>)reg.getServiceProviders(useOrdering);
+        return it;
     }
 
     /**
@@ -499,12 +501,12 @@
     public <T> Iterator<T> getServiceProviders(Class<T> category,
                                                Filter filter,
                                                boolean useOrdering) {
-        SubRegistry reg = (SubRegistry)categoryMap.get(category);
+        SubRegistry reg = categoryMap.get(category);
         if (reg == null) {
             throw new IllegalArgumentException("category unknown!");
         }
-        Iterator iter = getServiceProviders(category, useOrdering);
-        return new FilterIterator(iter, filter);
+        Iterator<T> iter = getServiceProviders(category, useOrdering);
+        return new FilterIterator<>(iter, filter);
     }
 
     /**
@@ -529,11 +531,11 @@
         if (providerClass == null) {
             throw new IllegalArgumentException("providerClass == null!");
         }
-        Iterator iter = categoryMap.keySet().iterator();
+        Iterator<Class<?>> iter = categoryMap.keySet().iterator();
         while (iter.hasNext()) {
-            Class c = (Class)iter.next();
+            Class<?> c = iter.next();
             if (c.isAssignableFrom(providerClass)) {
-                SubRegistry reg = (SubRegistry)categoryMap.get(c);
+                SubRegistry reg = categoryMap.get(c);
                 T provider = reg.getServiceProviderByClass(providerClass);
                 if (provider != null) {
                     return provider;
@@ -580,7 +582,7 @@
         if (firstProvider == secondProvider) {
             throw new IllegalArgumentException("providers are the same!");
         }
-        SubRegistry reg = (SubRegistry)categoryMap.get(category);
+        SubRegistry reg = categoryMap.get(category);
         if (reg == null) {
             throw new IllegalArgumentException("category unknown!");
         }
@@ -626,7 +628,7 @@
         if (firstProvider == secondProvider) {
             throw new IllegalArgumentException("providers are the same!");
         }
-        SubRegistry reg = (SubRegistry)categoryMap.get(category);
+        SubRegistry reg = categoryMap.get(category);
         if (reg == null) {
             throw new IllegalArgumentException("category unknown!");
         }
@@ -647,7 +649,7 @@
      * corresponding to <code>category</code>.
      */
     public void deregisterAll(Class<?> category) {
-        SubRegistry reg = (SubRegistry)categoryMap.get(category);
+        SubRegistry reg = categoryMap.get(category);
         if (reg == null) {
             throw new IllegalArgumentException("category unknown!");
         }
@@ -659,9 +661,9 @@
      * categories.
      */
     public void deregisterAll() {
-        Iterator iter = categoryMap.values().iterator();
+        Iterator<SubRegistry> iter = categoryMap.values().iterator();
         while (iter.hasNext()) {
-            SubRegistry reg = (SubRegistry)iter.next();
+            SubRegistry reg = iter.next();
             reg.clear();
         }
     }
@@ -690,15 +692,17 @@
 
     ServiceRegistry registry;
 
-    Class category;
+    Class<?> category;
 
     // Provider Objects organized by partial oridering
-    PartiallyOrderedSet poset = new PartiallyOrderedSet();
+    PartiallyOrderedSet<Object> poset = new PartiallyOrderedSet<>();
 
     // Class -> Provider Object of that class
-    Map<Class<?>,Object> map = new HashMap();
+    // No way to express heterogeneous map, we want
+    // Map<Class<T>, T>, where T is ?
+    Map<Class<?>, Object> map = new HashMap<>();
 
-    public SubRegistry(ServiceRegistry registry, Class category) {
+    public SubRegistry(ServiceRegistry registry, Class<?> category) {
         this.registry = registry;
         this.category = category;
     }
@@ -756,7 +760,7 @@
         return poset.unsetOrdering(firstProvider, secondProvider);
     }
 
-    public Iterator getServiceProviders(boolean useOrdering) {
+    public Iterator<Object> getServiceProviders(boolean useOrdering) {
         if (useOrdering) {
             return poset.iterator();
         } else {
@@ -764,12 +768,13 @@
         }
     }
 
+    @SuppressWarnings("unchecked")
     public <T> T getServiceProviderByClass(Class<T> providerClass) {
         return (T)map.get(providerClass);
     }
 
     public void clear() {
-        Iterator iter = map.values().iterator();
+        Iterator<Object> iter = map.values().iterator();
         while (iter.hasNext()) {
             Object provider = iter.next();
             iter.remove();
@@ -794,12 +799,12 @@
  */
 class FilterIterator<T> implements Iterator<T> {
 
-    private Iterator<T> iter;
+    private Iterator<? extends T> iter;
     private ServiceRegistry.Filter filter;
 
     private T next = null;
 
-    public FilterIterator(Iterator<T> iter,
+    public FilterIterator(Iterator<? extends T> iter,
                           ServiceRegistry.Filter filter) {
         this.iter = iter;
         this.filter = filter;
--- a/jdk/src/share/classes/javax/imageio/stream/ImageInputStreamImpl.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/stream/ImageInputStreamImpl.java	Wed Jul 05 19:33:51 2017 +0200
@@ -43,9 +43,9 @@
  */
 public abstract class ImageInputStreamImpl implements ImageInputStream {
 
-    private Stack markByteStack = new Stack();
+    private Stack<Long> markByteStack = new Stack<>();
 
-    private Stack markBitStack = new Stack();
+    private Stack<Integer> markBitStack = new Stack<>();
 
     private boolean isClosed = false;
 
@@ -798,14 +798,14 @@
             return;
         }
 
-        long pos = ((Long)markByteStack.pop()).longValue();
+        long pos = markByteStack.pop().longValue();
         if (pos < flushedPos) {
             throw new IIOException
                 ("Previous marked position has been discarded!");
         }
         seek(pos);
 
-        int offset = ((Integer)markBitStack.pop()).intValue();
+        int offset = markBitStack.pop().intValue();
         setBitOffset(offset);
     }
 
--- a/jdk/src/share/classes/javax/imageio/stream/MemoryCache.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/imageio/stream/MemoryCache.java	Wed Jul 05 19:33:51 2017 +0200
@@ -58,7 +58,7 @@
 
     private static final int BUFFER_LENGTH = 8192;
 
-    private ArrayList cache = new ArrayList();
+    private ArrayList<byte[]> cache = new ArrayList<>();
 
     private long cacheStart = 0L;
 
@@ -74,7 +74,7 @@
             // contiguous data...
             throw new IOException("Cache addressing limit exceeded!");
         }
-        return (byte[])cache.get((int)blockOffset);
+        return cache.get((int)blockOffset);
     }
 
     /**
--- a/jdk/src/share/classes/javax/smartcardio/TerminalFactory.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/smartcardio/TerminalFactory.java	Wed Jul 05 19:33:51 2017 +0200
@@ -32,8 +32,6 @@
 import sun.security.jca.*;
 import sun.security.jca.GetInstance.*;
 
-import sun.security.action.GetPropertyAction;
-
 /**
  * A factory for CardTerminal objects.
  *
@@ -99,8 +97,8 @@
 
     static {
         // lookup up the user specified type, default to PC/SC
-        String type = AccessController.doPrivileged
-                            (new GetPropertyAction(PROP_NAME, "PC/SC")).trim();
+        String type = AccessController.doPrivileged(
+             (PrivilegedAction<String>) () -> System.getProperty(PROP_NAME, "PC/SC")).trim();
         TerminalFactory factory = null;
         try {
             factory = TerminalFactory.getInstance(type, null);
--- a/jdk/src/share/classes/javax/swing/BufferStrategyPaintManager.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/BufferStrategyPaintManager.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,9 @@
 import java.util.*;
 
 import com.sun.java.swing.SwingUtilities3;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import sun.awt.AWTAccessor;
 
 import sun.awt.SubRegionShowable;
 import sun.java2d.SunGraphics2D;
@@ -69,12 +72,6 @@
     // if we get a blit strategy.
     //
 
-    //
-    // Methods used to create BufferStrategy for Applets.
-    //
-    private static Method COMPONENT_CREATE_BUFFER_STRATEGY_METHOD;
-    private static Method COMPONENT_GET_BUFFER_STRATEGY_METHOD;
-
     private static final PlatformLogger LOGGER = PlatformLogger.getLogger(
                            "javax.swing.BufferStrategyPaintManager");
 
@@ -143,44 +140,6 @@
      */
     private boolean disposeBufferOnEnd;
 
-    private static Method getGetBufferStrategyMethod() {
-        if (COMPONENT_GET_BUFFER_STRATEGY_METHOD == null) {
-            getMethods();
-        }
-        return COMPONENT_GET_BUFFER_STRATEGY_METHOD;
-    }
-
-    private static Method getCreateBufferStrategyMethod() {
-        if (COMPONENT_CREATE_BUFFER_STRATEGY_METHOD == null) {
-            getMethods();
-        }
-        return COMPONENT_CREATE_BUFFER_STRATEGY_METHOD;
-    }
-
-    private static void getMethods() {
-        java.security.AccessController.doPrivileged(
-                            new java.security.PrivilegedAction<Object>() {
-            public Object run() {
-                try {
-                    COMPONENT_CREATE_BUFFER_STRATEGY_METHOD = Component.class.
-                              getDeclaredMethod("createBufferStrategy",
-                                                new Class[] { int.class,
-                                                BufferCapabilities.class });
-                    COMPONENT_CREATE_BUFFER_STRATEGY_METHOD.
-                                            setAccessible(true);
-                    COMPONENT_GET_BUFFER_STRATEGY_METHOD = Component.class.
-                              getDeclaredMethod("getBufferStrategy");
-                    COMPONENT_GET_BUFFER_STRATEGY_METHOD.setAccessible(true);
-                } catch (SecurityException e) {
-                    assert false;
-                } catch (NoSuchMethodException nsme) {
-                    assert false;
-                }
-                return null;
-            }
-        });
-    }
-
     BufferStrategyPaintManager() {
         bufferInfos = new ArrayList<BufferInfo>(1);
     }
@@ -766,16 +725,7 @@
                     componentBS = ((Window)root).getBufferStrategy();
                 }
                 else {
-                    try {
-                        componentBS = (BufferStrategy)
-                                 getGetBufferStrategyMethod().invoke(root);
-                    } catch (InvocationTargetException ite) {
-                        assert false;
-                    } catch (IllegalArgumentException iae) {
-                        assert false;
-                    } catch (IllegalAccessException iae2) {
-                        assert false;
-                    }
+                    componentBS = AWTAccessor.getComponentAccessor().getBufferStrategy(root);
                 }
                 if (componentBS != ourBS) {
                     // Component has a different BS, dispose ours.
@@ -839,19 +789,16 @@
             BufferStrategy bs = null;
             if (SunToolkit.isInstanceOf(root, "java.applet.Applet")) {
                 try {
-                    getCreateBufferStrategyMethod().invoke(root, 2, caps);
-                    bs = (BufferStrategy)getGetBufferStrategyMethod().
-                                            invoke(root);
-                } catch (InvocationTargetException ite) {
+                    AWTAccessor.ComponentAccessor componentAccessor
+                            = AWTAccessor.getComponentAccessor();
+                    componentAccessor.createBufferStrategy(root, 2, caps);
+                    bs = componentAccessor.getBufferStrategy(root);
+                } catch (AWTException e) {
                     // Type is not supported
                     if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
                         LOGGER.finer("createBufferStratety failed",
-                                     ite);
+                                     e);
                     }
-                } catch (IllegalArgumentException iae) {
-                    assert false;
-                } catch (IllegalAccessException iae2) {
-                    assert false;
                 }
             }
             else {
--- a/jdk/src/share/classes/javax/swing/DefaultDesktopManager.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/DefaultDesktopManager.java	Wed Jul 05 19:33:51 2017 +0200
@@ -677,6 +677,11 @@
 
           f.setBounds(currentBounds);
 
+          if (!floaterCollision) {
+              Rectangle r = currentBounds;
+              currentManager.notifyRepaintPerformed(parent, r.x, r.y, r.width, r.height);
+          }
+
           if(floaterCollision) {
               // since we couldn't blit we just redraw as fast as possible
               // the isDragging mucking is to avoid activating emergency
@@ -706,6 +711,8 @@
           // Fix the damage
           for (int i = 0; i < dirtyRects.length; i++) {
               parent.paintImmediately(dirtyRects[i]);
+              Rectangle r = dirtyRects[i];
+              currentManager.notifyRepaintPerformed(parent, r.x, r.y, r.width, r.height);
           }
 
           // new areas of blit were exposed
@@ -716,9 +723,10 @@
                   dirtyRects[i].x += newX - previousBounds.x;
                   dirtyRects[i].y += newY - previousBounds.y;
                   ((JInternalFrame)f).isDragging = false;
-
                   parent.paintImmediately(dirtyRects[i]);
                   ((JInternalFrame)f).isDragging = true;
+                  Rectangle r = dirtyRects[i];
+                  currentManager.notifyRepaintPerformed(parent, r.x, r.y, r.width, r.height);
               }
 
           }
--- a/jdk/src/share/classes/javax/swing/JSpinner.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/JSpinner.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1221,6 +1221,7 @@
             JFormattedTextField ftf = getTextField();
             ftf.setEditable(true);
             ftf.setFormatterFactory(factory);
+            // Change the text orientation for the NumberEditor
             ftf.setHorizontalAlignment(JTextField.RIGHT);
 
             /* TBD - initializing the column width of the text field
@@ -1264,6 +1265,16 @@
         public SpinnerNumberModel getModel() {
             return (SpinnerNumberModel)(getSpinner().getModel());
         }
+
+        /**
+         * {@inheritDoc}
+         */
+        @Override
+        public void setComponentOrientation(ComponentOrientation o) {
+            super.setComponentOrientation(o);
+            getTextField().setHorizontalAlignment(
+                    o.isLeftToRight() ? JTextField.RIGHT : JTextField.LEFT);
+        }
     }
 
 
--- a/jdk/src/share/classes/javax/swing/JTable.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/JTable.java	Wed Jul 05 19:33:51 2017 +0200
@@ -5308,12 +5308,12 @@
         return retValue;
     }
 
-    private void setLazyValue(Hashtable h, Class c, String s) {
-        h.put(c, new SwingLazyValue(s));
-    }
-
-    private void setLazyRenderer(Class c, String s) {
-        setLazyValue(defaultRenderersByColumnClass, c, s);
+    private void setLazyValue(Hashtable h, Class c, LazyClass lazyClass) {
+        h.put(c, new TableLazyValue(lazyClass));
+    }
+
+    private void setLazyRenderer(Class c, LazyClass lazyClass) {
+        setLazyValue(defaultRenderersByColumnClass, c, lazyClass);
     }
 
     /**
@@ -5326,24 +5326,24 @@
         defaultRenderersByColumnClass = new UIDefaults(8, 0.75f);
 
         // Objects
-        setLazyRenderer(Object.class, "javax.swing.table.DefaultTableCellRenderer$UIResource");
+        setLazyRenderer(Object.class, LazyClass.UIResource);
 
         // Numbers
-        setLazyRenderer(Number.class, "javax.swing.JTable$NumberRenderer");
+        setLazyRenderer(Number.class, LazyClass.NumberRenderer);
 
         // Doubles and Floats
-        setLazyRenderer(Float.class, "javax.swing.JTable$DoubleRenderer");
-        setLazyRenderer(Double.class, "javax.swing.JTable$DoubleRenderer");
+        setLazyRenderer(Float.class, LazyClass.DoubleRenderer);
+        setLazyRenderer(Double.class, LazyClass.DoubleRenderer);
 
         // Dates
-        setLazyRenderer(Date.class, "javax.swing.JTable$DateRenderer");
+        setLazyRenderer(Date.class, LazyClass.DateRenderer);
 
         // Icons and ImageIcons
-        setLazyRenderer(Icon.class, "javax.swing.JTable$IconRenderer");
-        setLazyRenderer(ImageIcon.class, "javax.swing.JTable$IconRenderer");
+        setLazyRenderer(Icon.class, LazyClass.IconRenderer);
+        setLazyRenderer(ImageIcon.class, LazyClass.IconRenderer);
 
         // Booleans
-        setLazyRenderer(Boolean.class, "javax.swing.JTable$BooleanRenderer");
+        setLazyRenderer(Boolean.class, LazyClass.BooleanRenderer);
     }
 
     /**
@@ -5421,8 +5421,8 @@
         }
     }
 
-    private void setLazyEditor(Class c, String s) {
-        setLazyValue(defaultEditorsByColumnClass, c, s);
+    private void setLazyEditor(Class c, LazyClass lazyClass) {
+        setLazyValue(defaultEditorsByColumnClass, c, lazyClass);
     }
 
     /**
@@ -5433,13 +5433,13 @@
         defaultEditorsByColumnClass = new UIDefaults(3, 0.75f);
 
         // Objects
-        setLazyEditor(Object.class, "javax.swing.JTable$GenericEditor");
+        setLazyEditor(Object.class, LazyClass.GenericEditor);
 
         // Numbers
-        setLazyEditor(Number.class, "javax.swing.JTable$NumberEditor");
+        setLazyEditor(Number.class, LazyClass.NumberEditor);
 
         // Booleans
-        setLazyEditor(Boolean.class, "javax.swing.JTable$BooleanEditor");
+        setLazyEditor(Boolean.class, LazyClass.BooleanEditor);
     }
 
     /**
@@ -6545,6 +6545,53 @@
         }
     }
 
+    private enum LazyClass {
+
+        UIResource,
+        NumberRenderer,
+        DoubleRenderer,
+        DateRenderer,
+        IconRenderer,
+        BooleanRenderer,
+        GenericEditor,
+        NumberEditor,
+        BooleanEditor,
+    }
+
+    private static class TableLazyValue implements UIDefaults.LazyValue {
+
+        private LazyClass type;
+
+        public TableLazyValue(LazyClass type) {
+            this.type = type;
+        }
+
+        @Override
+        public Object createValue(UIDefaults table) {
+            switch (type) {
+                case UIResource:
+                    return new DefaultTableCellRenderer.UIResource();
+                case NumberRenderer:
+                    return new NumberRenderer();
+                case DoubleRenderer:
+                    return new DoubleRenderer();
+                case DateRenderer:
+                    return new DateRenderer();
+                case IconRenderer:
+                    return new IconRenderer();
+                case BooleanRenderer:
+                    return new BooleanRenderer();
+                case GenericEditor:
+                    return new GenericEditor();
+                case NumberEditor:
+                    return new NumberEditor();
+                case BooleanEditor:
+                    return new BooleanEditor();
+                default:
+                    return null;
+            }
+        }
+    }
 
 /////////////////
 // Accessibility support
--- a/jdk/src/share/classes/javax/swing/JViewport.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/JViewport.java	Wed Jul 05 19:33:51 2017 +0200
@@ -25,8 +25,6 @@
 
 package javax.swing;
 
-import sun.swing.JLightweightFrame;
-
 import java.awt.*;
 import java.awt.event.*;
 import java.awt.peer.ComponentPeer;
@@ -37,10 +35,8 @@
 import javax.swing.border.*;
 import javax.accessibility.*;
 
-
 import java.io.Serializable;
 
-
 /**
  * The "viewport" or "porthole" through which you see the underlying
  * information. When you scroll, what moves is the viewport. It is like
@@ -364,18 +360,6 @@
         super.remove(child);
     }
 
-    @Override
-    public void addNotify() {
-        super.addNotify();
-        // JLightweightFrame does not support BLIT_SCROLL_MODE, so it should be replaced
-        Window rootWindow = SwingUtilities.getWindowAncestor(this);
-        if (rootWindow instanceof JLightweightFrame
-                && getScrollMode() == BLIT_SCROLL_MODE) {
-            setScrollMode(BACKINGSTORE_SCROLL_MODE);
-        }
-    }
-
-
     /**
      * Scrolls the view so that <code>Rectangle</code>
      * within the view becomes visible.
@@ -1109,13 +1093,15 @@
                         Graphics g = JComponent.safelyGetGraphics(this);
                         flushViewDirtyRegion(g, dirty);
                         view.setLocation(newX, newY);
-                        g.setClip(0,0,getWidth(), Math.min(getHeight(),
-                                                           jview.getHeight()));
+                        Rectangle r = new Rectangle(
+                            0, 0, getWidth(), Math.min(getHeight(), jview.getHeight()));
+                        g.setClip(r);
                         // Repaint the complete component if the blit succeeded
                         // and needsRepaintAfterBlit returns true.
                         repaintAll = (windowBlitPaint(g) &&
                                       needsRepaintAfterBlit());
                         g.dispose();
+                        rm.notifyRepaintPerformed(this, r.x, r.y, r.width, r.height);
                         rm.markCompletelyClean((JComponent)getParent());
                         rm.markCompletelyClean(this);
                         rm.markCompletelyClean(jview);
--- a/jdk/src/share/classes/javax/swing/MenuSelectionManager.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/MenuSelectionManager.java	Wed Jul 05 19:33:51 2017 +0200
@@ -30,6 +30,7 @@
 import javax.swing.event.*;
 
 import sun.awt.AppContext;
+import sun.swing.SwingUtilities2;
 
 /**
  * A MenuSelectionManager owns the selection in menu hierarchy.
@@ -60,6 +61,12 @@
             if (msm == null) {
                 msm = new MenuSelectionManager();
                 context.put(MENU_SELECTION_MANAGER_KEY, msm);
+
+                // installing additional listener if found in the AppContext
+                Object o = context.get(SwingUtilities2.MENU_SELECTION_MANAGER_LISTENER_KEY);
+                if (o != null && o instanceof ChangeListener) {
+                    msm.addChangeListener((ChangeListener) o);
+                }
             }
 
             return msm;
--- a/jdk/src/share/classes/javax/swing/RepaintManager.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/RepaintManager.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,8 @@
 import sun.security.action.GetPropertyAction;
 
 import com.sun.java.swing.SwingUtilities3;
+import sun.swing.SwingAccessor;
+import sun.swing.SwingUtilities2.RepaintListener;
 
 /**
  * This class manages repaint requests, allowing the number
@@ -184,6 +186,17 @@
 
 
     static {
+        SwingAccessor.setRepaintManagerAccessor(new SwingAccessor.RepaintManagerAccessor() {
+            @Override
+            public void addRepaintListener(RepaintManager rm, RepaintListener l) {
+                rm.addRepaintListener(l);
+            }
+            @Override
+            public void removeRepaintListener(RepaintManager rm, RepaintListener l) {
+                rm.removeRepaintListener(l);
+            }
+        });
+
         volatileImageBufferEnabled = "true".equals(AccessController.
                 doPrivileged(new GetPropertyAction(
                 "swing.volatileImageBufferEnabled", "true")));
@@ -1267,6 +1280,33 @@
         getPaintManager().copyArea(c, g, x, y, w, h, deltaX, deltaY, clip);
     }
 
+    private java.util.List<RepaintListener> repaintListeners = new ArrayList<>(1);
+
+    private void addRepaintListener(RepaintListener l) {
+        repaintListeners.add(l);
+    }
+
+    private void removeRepaintListener(RepaintListener l) {
+        repaintListeners.remove(l);
+    }
+
+    /**
+     * Notify the attached repaint listeners that an area of the {@code c} component
+     * has been immediately repainted, that is without scheduling a repaint runnable,
+     * due to performing a "blit" (via calling the {@code copyArea} method).
+     *
+     * @param c the component
+     * @param x the x coordinate of the area
+     * @param y the y coordinate of the area
+     * @param w the width of the area
+     * @param h the height of the area
+     */
+    void notifyRepaintPerformed(JComponent c, int x, int y, int w, int h) {
+        for (RepaintListener l : repaintListeners) {
+            l.repaintPerformed(c, x, y, w, h);
+        }
+    }
+
     /**
      * Invoked prior to any paint/copyArea method calls.  This will
      * be followed by an invocation of <code>endPaint</code>.
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java	Wed Jul 05 19:33:51 2017 +0200
@@ -109,8 +109,7 @@
 
 
     static {
-        newline = java.security.AccessController.doPrivileged(
-                                new GetPropertyAction("line.separator"));
+        newline = System.lineSeparator();
         if (newline == null) {
             newline = "\n";
         }
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java	Wed Jul 05 19:33:51 2017 +0200
@@ -997,21 +997,32 @@
                              "model".equals(propertyName)) {
                         ui.updateEnabledState();
                     }
-                else if ("font".equals(propertyName)) {
-                    JComponent editor = spinner.getEditor();
-                    if (editor!=null && editor instanceof JSpinner.DefaultEditor) {
-                        JTextField tf =
-                            ((JSpinner.DefaultEditor)editor).getTextField();
-                        if (tf != null) {
-                            if (tf.getFont() instanceof UIResource) {
-                                tf.setFont(spinner.getFont());
+                    else if ("font".equals(propertyName)) {
+                        JComponent editor = spinner.getEditor();
+                        if (editor!=null && editor instanceof JSpinner.DefaultEditor) {
+                            JTextField tf =
+                                ((JSpinner.DefaultEditor)editor).getTextField();
+                            if (tf != null) {
+                                if (tf.getFont() instanceof UIResource) {
+                                    tf.setFont(spinner.getFont());
+                                }
                             }
                         }
                     }
-                }
-                else if (JComponent.TOOL_TIP_TEXT_KEY.equals(propertyName)) {
-                    updateToolTipTextForChildren(spinner);
-                }
+                    else if (JComponent.TOOL_TIP_TEXT_KEY.equals(propertyName)) {
+                        updateToolTipTextForChildren(spinner);
+                    } else if ("componentOrientation".equals(propertyName)) {
+                        ComponentOrientation o
+                                = (ComponentOrientation) e.getNewValue();
+                        if (o != (ComponentOrientation) e.getOldValue()) {
+                            JComponent editor = spinner.getEditor();
+                            if (editor != null) {
+                                editor.applyComponentOrientation(o);
+                            }
+                            spinner.revalidate();
+                            spinner.repaint();
+                        }
+                    }
                 }
             } else if (e.getSource() instanceof JComponent) {
                 JComponent c = (JComponent)e.getSource();
--- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1067,9 +1067,69 @@
     /**
      * Data model for a type-face selection combo-box.
      */
-    protected class FilterComboBoxModel extends AbstractFilterComboBoxModel {
-        protected JFileChooser getFileChooser() {
-            return MetalFileChooserUI.this.getFileChooser();
+    protected class FilterComboBoxModel extends AbstractListModel<Object> implements ComboBoxModel<Object>, PropertyChangeListener {
+        protected FileFilter[] filters;
+        protected FilterComboBoxModel() {
+            super();
+            filters = getFileChooser().getChoosableFileFilters();
+        }
+
+        public void propertyChange(PropertyChangeEvent e) {
+            String prop = e.getPropertyName();
+            if(prop == JFileChooser.CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY) {
+                filters = (FileFilter[]) e.getNewValue();
+                fireContentsChanged(this, -1, -1);
+            } else if (prop == JFileChooser.FILE_FILTER_CHANGED_PROPERTY) {
+                fireContentsChanged(this, -1, -1);
+            }
+        }
+
+        public void setSelectedItem(Object filter) {
+            if(filter != null) {
+                getFileChooser().setFileFilter((FileFilter) filter);
+                fireContentsChanged(this, -1, -1);
+            }
+        }
+
+        public Object getSelectedItem() {
+            // Ensure that the current filter is in the list.
+            // NOTE: we shouldnt' have to do this, since JFileChooser adds
+            // the filter to the choosable filters list when the filter
+            // is set. Lets be paranoid just in case someone overrides
+            // setFileFilter in JFileChooser.
+            FileFilter currentFilter = getFileChooser().getFileFilter();
+            boolean found = false;
+            if(currentFilter != null) {
+                for (FileFilter filter : filters) {
+                    if (filter == currentFilter) {
+                        found = true;
+                    }
+                }
+                if(found == false) {
+                    getFileChooser().addChoosableFileFilter(currentFilter);
+                }
+            }
+            return getFileChooser().getFileFilter();
+        }
+
+        public int getSize() {
+            if(filters != null) {
+                return filters.length;
+            } else {
+                return 0;
+            }
+        }
+
+        public Object getElementAt(int index) {
+            if(index > getSize() - 1) {
+                // This shouldn't happen. Try to recover gracefully.
+                return getFileChooser().getFileFilter();
+            }
+            if(filters != null) {
+                return filters[index];
+            } else {
+                return null;
+            }
         }
     }
 
--- a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java	Wed Jul 05 19:33:51 2017 +0200
@@ -698,7 +698,6 @@
             return;
         }
         DocumentFilter filter = getDocumentFilter();
-        InsertStringResult insertStringResult = null;
 
         writeLock();
 
@@ -706,23 +705,21 @@
             if (filter != null) {
                 filter.insertString(getFilterBypass(), offs, str, a);
             } else {
-                insertStringResult = handleInsertString(offs, str, a);
+                handleInsertString(offs, str, a);
             }
         } finally {
             writeUnlock();
         }
-
-        processInsertStringResult(insertStringResult);
     }
 
     /**
      * Performs the actual work of inserting the text; it is assumed the
      * caller has obtained a write lock before invoking this.
      */
-    private InsertStringResult handleInsertString(int offs, String str, AttributeSet a)
+    private void handleInsertString(int offs, String str, AttributeSet a)
             throws BadLocationException {
         if ((str == null) || (str.length() == 0)) {
-            return null;
+            return;
         }
         UndoableEdit u = data.insertString(offs, str);
         DefaultDocumentEvent e =
@@ -749,29 +746,11 @@
         insertUpdate(e, a);
         // Mark the edit as done.
         e.end();
-
-        InsertStringResult result = new InsertStringResult();
-
-        result.documentEvent = e;
-
+        fireInsertUpdate(e);
         // only fire undo if Content implementation supports it
         // undo for the composed text is not supported for now
         if (u != null && (a == null || !a.isDefined(StyleConstants.ComposedTextAttribute))) {
-            result.undoableEditEvent = new UndoableEditEvent(this, e);
-        }
-
-        return result;
-    }
-
-    private void processInsertStringResult(InsertStringResult insertStringResult) {
-        if (insertStringResult == null) {
-            return;
-        }
-
-        fireInsertUpdate(insertStringResult.documentEvent);
-
-        if (insertStringResult.undoableEditEvent != null) {
-            fireUndoableEditUpdate(insertStringResult.undoableEditEvent);
+            fireUndoableEditUpdate(new UndoableEditEvent(this, e));
         }
     }
 
@@ -3129,23 +3108,13 @@
         public void insertString(int offset, String string,
                                  AttributeSet attr) throws
                                         BadLocationException {
-            InsertStringResult insertStringResult = handleInsertString(offset, string, attr);
-
-            processInsertStringResult(insertStringResult);
+            handleInsertString(offset, string, attr);
         }
 
         public void replace(int offset, int length, String text,
                             AttributeSet attrs) throws BadLocationException {
             handleRemove(offset, length);
-
-            InsertStringResult insertStringResult = handleInsertString(offset, text, attrs);
-
-            processInsertStringResult(insertStringResult);
+            handleInsertString(offset, text, attrs);
         }
     }
-
-    private static class InsertStringResult {
-        DefaultDocumentEvent documentEvent;
-        UndoableEditEvent undoableEditEvent;
-    }
 }
--- a/jdk/src/share/classes/javax/swing/text/AbstractWriter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/text/AbstractWriter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -141,10 +141,7 @@
             setLineSeparator((String)docNewline);
         }
         else {
-            String newline = null;
-            try {
-                newline = System.getProperty("line.separator");
-            } catch (SecurityException se) {}
+            String newline = System.lineSeparator();
             if (newline == null) {
                 // Should not get here, but if we do it means we could not
                 // find a newline string, use \n in this case.
--- a/jdk/src/share/classes/javax/swing/text/DefaultEditorKit.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/text/DefaultEditorKit.java	Wed Jul 05 19:33:51 2017 +0200
@@ -317,9 +317,7 @@
         int offs = pos;
         Object endOfLineProperty = doc.getProperty(EndOfLineStringProperty);
         if (endOfLineProperty == null) {
-            try {
-                endOfLineProperty = System.getProperty("line.separator");
-            } catch (SecurityException se) { }
+            endOfLineProperty = System.lineSeparator();
         }
         String endOfLine;
         if (endOfLineProperty instanceof String) {
--- a/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2089,6 +2089,13 @@
                         // null end tag.
                         endTag(false);
                         continue;
+                    } else if (textpos == 0) {
+                        if (!legalElementContext(dtd.pcdata)) {
+                            error("unexpected.pcdata");
+                        }
+                        if (last.breaksFlow()) {
+                            space = false;
+                        }
                     }
                     break;
 
--- a/jdk/src/share/classes/jdk/internal/org/objectweb/asm/ByteVector.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/jdk/internal/org/objectweb/asm/ByteVector.java	Wed Jul 05 19:33:51 2017 +0200
@@ -259,41 +259,68 @@
             if (c >= '\001' && c <= '\177') {
                 data[len++] = (byte) c;
             } else {
-                int byteLength = i;
-                for (int j = i; j < charLength; ++j) {
-                    c = s.charAt(j);
-                    if (c >= '\001' && c <= '\177') {
-                        byteLength++;
-                    } else if (c > '\u07FF') {
-                        byteLength += 3;
-                    } else {
-                        byteLength += 2;
-                    }
-                }
-                if (byteLength > 65535) {
-                    throw new IllegalArgumentException();
-                }
-                data[length] = (byte) (byteLength >>> 8);
-                data[length + 1] = (byte) byteLength;
-                if (length + 2 + byteLength > data.length) {
-                    length = len;
-                    enlarge(2 + byteLength);
-                    data = this.data;
-                }
-                for (int j = i; j < charLength; ++j) {
-                    c = s.charAt(j);
-                    if (c >= '\001' && c <= '\177') {
-                        data[len++] = (byte) c;
-                    } else if (c > '\u07FF') {
-                        data[len++] = (byte) (0xE0 | c >> 12 & 0xF);
-                        data[len++] = (byte) (0x80 | c >> 6 & 0x3F);
-                        data[len++] = (byte) (0x80 | c & 0x3F);
-                    } else {
-                        data[len++] = (byte) (0xC0 | c >> 6 & 0x1F);
-                        data[len++] = (byte) (0x80 | c & 0x3F);
-                    }
-                }
-                break;
+                length = len;
+                return encodeUTF8(s, i, 65535);
+            }
+        }
+        length = len;
+        return this;
+    }
+
+    /**
+     * Puts an UTF8 string into this byte vector. The byte vector is
+     * automatically enlarged if necessary. The string length is encoded in two
+     * bytes before the encoded characters, if there is space for that (i.e. if
+     * this.length - i - 2 >= 0).
+     *
+     * @param s
+     *            the String to encode.
+     * @param i
+     *            the index of the first character to encode. The previous
+     *            characters are supposed to have already been encoded, using
+     *            only one byte per character.
+     * @param maxByteLength
+     *            the maximum byte length of the encoded string, including the
+     *            already encoded characters.
+     * @return this byte vector.
+     */
+    ByteVector encodeUTF8(final String s, int i, int maxByteLength) {
+        int charLength = s.length();
+        int byteLength = i;
+        char c;
+        for (int j = i; j < charLength; ++j) {
+            c = s.charAt(j);
+            if (c >= '\001' && c <= '\177') {
+                byteLength++;
+            } else if (c > '\u07FF') {
+                byteLength += 3;
+            } else {
+                byteLength += 2;
+            }
+        }
+        if (byteLength > maxByteLength) {
+            throw new IllegalArgumentException();
+        }
+        int start = length - i - 2;
+        if (start >= 0) {
+          data[start] = (byte) (byteLength >>> 8);
+          data[start + 1] = (byte) byteLength;
+        }
+        if (length + byteLength - i > data.length) {
+            enlarge(byteLength - i);
+        }
+        int len = length;
+        for (int j = i; j < charLength; ++j) {
+            c = s.charAt(j);
+            if (c >= '\001' && c <= '\177') {
+                data[len++] = (byte) c;
+            } else if (c > '\u07FF') {
+                data[len++] = (byte) (0xE0 | c >> 12 & 0xF);
+                data[len++] = (byte) (0x80 | c >> 6 & 0x3F);
+                data[len++] = (byte) (0x80 | c & 0x3F);
+            } else {
+                data[len++] = (byte) (0xC0 | c >> 6 & 0x1F);
+                data[len++] = (byte) (0x80 | c & 0x3F);
             }
         }
         length = len;
--- a/jdk/src/share/classes/jdk/internal/org/objectweb/asm/ClassWriter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/jdk/internal/org/objectweb/asm/ClassWriter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -716,7 +716,8 @@
             sourceFile = newUTF8(file);
         }
         if (debug != null) {
-            sourceDebug = new ByteVector().putUTF8(debug);
+            sourceDebug = new ByteVector().encodeUTF8(debug, 0,
+                    Integer.MAX_VALUE);
         }
     }
 
@@ -857,7 +858,7 @@
         }
         if (sourceDebug != null) {
             ++attributeCount;
-            size += sourceDebug.length + 4;
+            size += sourceDebug.length + 6;
             newUTF8("SourceDebugExtension");
         }
         if (enclosingMethodOwner != 0) {
@@ -946,9 +947,9 @@
             out.putShort(newUTF8("SourceFile")).putInt(2).putShort(sourceFile);
         }
         if (sourceDebug != null) {
-            int len = sourceDebug.length - 2;
+            int len = sourceDebug.length;
             out.putShort(newUTF8("SourceDebugExtension")).putInt(len);
-            out.putByteArray(sourceDebug.data, 2, len);
+            out.putByteArray(sourceDebug.data, 0, len);
         }
         if (enclosingMethodOwner != 0) {
             out.putShort(newUTF8("EnclosingMethod")).putInt(4);
--- a/jdk/src/share/classes/jdk/internal/org/objectweb/asm/Frame.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/jdk/internal/org/objectweb/asm/Frame.java	Wed Jul 05 19:33:51 2017 +0200
@@ -99,8 +99,8 @@
      * stack types. VALUE depends on KIND. For LOCAL types, it is an index in
      * the input local variable types. For STACK types, it is a position
      * relatively to the top of input frame stack. For BASE types, it is either
-     * one of the constants defined in FrameVisitor, or for OBJECT and
-     * UNINITIALIZED types, a tag and an index in the type table.
+     * one of the constants defined below, or for OBJECT and UNINITIALIZED
+     * types, a tag and an index in the type table.
      *
      * Output frames can contain types of any kind and with a positive or
      * negative dimension (and even unassigned types, represented by 0 - which
@@ -537,7 +537,7 @@
     /**
      * The types that are initialized in the basic block. A constructor
      * invocation on an UNINITIALIZED or UNINITIALIZED_THIS type must replace
-     * <i>every occurrence</i> of this type in the local variables and in the
+     * <i>every occurence</i> of this type in the local variables and in the
      * operand stack. This cannot be done during the first phase of the
      * algorithm since, during this phase, the local variables and the operand
      * stack are not completely computed. It is therefore necessary to store the
@@ -1446,6 +1446,7 @@
                 // if t is the NULL type, merge(u,t)=u, so there is no change
                 return false;
             } else if ((t & (DIM | BASE_KIND)) == (u & (DIM | BASE_KIND))) {
+                // if t and u have the same dimension and same base kind
                 if ((u & BASE_KIND) == OBJECT) {
                     // if t is also a reference type, and if u and t have the
                     // same dimension merge(u,t) = dim(t) | common parent of the
@@ -1458,9 +1459,13 @@
                     v = OBJECT | cw.addType("java/lang/Object");
                 }
             } else if ((t & BASE_KIND) == OBJECT || (t & DIM) != 0) {
-                // if t is any other reference or array type,
-                // merge(u,t)=java/lang/Object
-                v = OBJECT | cw.addType("java/lang/Object");
+                // if t is any other reference or array type, the merged type
+                // is Object, or min(dim(u), dim(t)) | java/lang/Object is u
+                // and t have different array dimensions
+                int tdim = t & DIM;
+                int udim = u & DIM;
+                v = (udim != tdim ? Math.min(tdim, udim) : 0) | OBJECT
+                        | cw.addType("java/lang/Object");
             } else {
                 // if t is any other type, merge(u,t)=TOP
                 v = TOP;
--- a/jdk/src/share/classes/jdk/internal/org/objectweb/asm/commons/AnalyzerAdapter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/jdk/internal/org/objectweb/asm/commons/AnalyzerAdapter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -240,6 +240,7 @@
                 locals.add(types[i].getInternalName());
             }
         }
+        maxLocals = locals.size();
     }
 
     @Override
@@ -519,12 +520,12 @@
     // ------------------------------------------------------------------------
 
     private Object get(final int local) {
-        maxLocals = Math.max(maxLocals, local);
+        maxLocals = Math.max(maxLocals, local + 1);
         return local < locals.size() ? locals.get(local) : Opcodes.TOP;
     }
 
     private void set(final int local, final Object type) {
-        maxLocals = Math.max(maxLocals, local);
+        maxLocals = Math.max(maxLocals, local + 1);
         while (local >= locals.size()) {
             locals.add(Opcodes.TOP);
         }
--- a/jdk/src/share/classes/jdk/internal/org/objectweb/asm/tree/InsnList.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/jdk/internal/org/objectweb/asm/tree/InsnList.java	Wed Jul 05 19:33:51 2017 +0200
@@ -556,6 +556,8 @@
 
         AbstractInsnNode prev;
 
+        AbstractInsnNode remove;
+
         InsnListIterator(int index) {
             if (index == size()) {
                 next = null;
@@ -577,12 +579,22 @@
             AbstractInsnNode result = next;
             prev = result;
             next = result.next;
+            remove = result;
             return result;
         }
 
         public void remove() {
-            InsnList.this.remove(prev);
-            prev = prev.prev;
+            if (remove != null) {
+                if (remove == next) {
+                    next = next.next;
+                } else {
+                    prev = prev.prev;
+                }
+                InsnList.this.remove(remove);
+                remove = null;
+            } else {
+                throw new IllegalStateException();
+            }
         }
 
         public boolean hasPrevious() {
@@ -593,6 +605,7 @@
             AbstractInsnNode result = prev;
             next = result;
             prev = result.prev;
+            remove = result;
             return result;
         }
 
@@ -619,6 +632,7 @@
         public void add(Object o) {
             InsnList.this.insertBefore(next, (AbstractInsnNode) o);
             prev = (AbstractInsnNode) o;
+            remove = null;
         }
 
         public void set(Object o) {
--- a/jdk/src/share/classes/jdk/internal/org/objectweb/asm/tree/analysis/Analyzer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/jdk/internal/org/objectweb/asm/tree/analysis/Analyzer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -404,7 +404,7 @@
      *         instruction of the method. The size of the returned array is
      *         equal to the number of instructions (and labels) of the method. A
      *         given frame is <tt>null</tt> if the corresponding instruction
-     *         cannot be reached, or if an error occurred during the analysis of
+     *         cannot be reached, or if an error occured during the analysis of
      *         the method.
      */
     public Frame<V>[] getFrames() {
--- a/jdk/src/share/classes/jdk/internal/org/objectweb/asm/tree/analysis/AnalyzerException.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/jdk/internal/org/objectweb/asm/tree/analysis/AnalyzerException.java	Wed Jul 05 19:33:51 2017 +0200
@@ -66,7 +66,7 @@
  * @author Bing Ran
  * @author Eric Bruneton
  */
-@SuppressWarnings("serial") // JDK-implementation class
+@SuppressWarnings("serial") // implementation class
 public class AnalyzerException extends Exception {
 
     public final AbstractInsnNode node;
--- a/jdk/src/share/classes/jdk/internal/org/objectweb/asm/tree/analysis/Interpreter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/jdk/internal/org/objectweb/asm/tree/analysis/Interpreter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -111,7 +111,7 @@
      *            the bytecode instruction to be interpreted.
      * @return the result of the interpretation of the given instruction.
      * @throws AnalyzerException
-     *             if an error occurred during the interpretation.
+     *             if an error occured during the interpretation.
      */
     public abstract V newOperation(AbstractInsnNode insn)
             throws AnalyzerException;
@@ -130,7 +130,7 @@
      * @return the result of the interpretation of the given instruction. The
      *         returned value must be <tt>equal</tt> to the given value.
      * @throws AnalyzerException
-     *             if an error occurred during the interpretation.
+     *             if an error occured during the interpretation.
      */
     public abstract V copyOperation(AbstractInsnNode insn, V value)
             throws AnalyzerException;
@@ -151,7 +151,7 @@
      *            the argument of the instruction to be interpreted.
      * @return the result of the interpretation of the given instruction.
      * @throws AnalyzerException
-     *             if an error occurred during the interpretation.
+     *             if an error occured during the interpretation.
      */
     public abstract V unaryOperation(AbstractInsnNode insn, V value)
             throws AnalyzerException;
@@ -175,7 +175,7 @@
      *            the second argument of the instruction to be interpreted.
      * @return the result of the interpretation of the given instruction.
      * @throws AnalyzerException
-     *             if an error occurred during the interpretation.
+     *             if an error occured during the interpretation.
      */
     public abstract V binaryOperation(AbstractInsnNode insn, V value1, V value2)
             throws AnalyzerException;
@@ -196,7 +196,7 @@
      *            the third argument of the instruction to be interpreted.
      * @return the result of the interpretation of the given instruction.
      * @throws AnalyzerException
-     *             if an error occurred during the interpretation.
+     *             if an error occured during the interpretation.
      */
     public abstract V ternaryOperation(AbstractInsnNode insn, V value1,
             V value2, V value3) throws AnalyzerException;
@@ -214,7 +214,7 @@
      *            the arguments of the instruction to be interpreted.
      * @return the result of the interpretation of the given instruction.
      * @throws AnalyzerException
-     *             if an error occurred during the interpretation.
+     *             if an error occured during the interpretation.
      */
     public abstract V naryOperation(AbstractInsnNode insn,
             List<? extends V> values) throws AnalyzerException;
@@ -232,7 +232,7 @@
      * @param expected
      *            the expected return type of the analyzed method.
      * @throws AnalyzerException
-     *             if an error occurred during the interpretation.
+     *             if an error occured during the interpretation.
      */
     public abstract void returnOperation(AbstractInsnNode insn, V value,
             V expected) throws AnalyzerException;
--- a/jdk/src/share/classes/jdk/internal/org/objectweb/asm/util/CheckAnnotationAdapter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/jdk/internal/org/objectweb/asm/util/CheckAnnotationAdapter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -99,7 +99,7 @@
         }
         if (value instanceof Type) {
             int sort = ((Type) value).getSort();
-            if (sort != Type.OBJECT && sort != Type.ARRAY) {
+            if (sort == Type.METHOD) {
                 throw new IllegalArgumentException("Invalid annotation value");
             }
         }
--- a/jdk/src/share/classes/jdk/internal/org/objectweb/asm/util/Textifier.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/jdk/internal/org/objectweb/asm/util/Textifier.java	Wed Jul 05 19:33:51 2017 +0200
@@ -166,6 +166,11 @@
      */
     protected Map<Label, String> labelNames;
 
+    /**
+     * Class access flags
+     */
+    private int access;
+
     private int valueNumber = 0;
 
     /**
@@ -245,6 +250,7 @@
     public void visit(final int version, final int access, final String name,
             final String signature, final String superName,
             final String[] interfaces) {
+        this.access = access;
         int major = version & 0xFFFF;
         int minor = version >>> 16;
         buf.setLength(0);
@@ -447,6 +453,11 @@
         if ((access & Opcodes.ACC_BRIDGE) != 0) {
             buf.append("bridge ");
         }
+        if ((this.access & Opcodes.ACC_INTERFACE) != 0
+                && (access & Opcodes.ACC_ABSTRACT) == 0
+                && (access & Opcodes.ACC_STATIC) == 0) {
+            buf.append("default ");
+        }
 
         buf.append(name);
         appendDescriptor(METHOD_DESCRIPTOR, desc);
@@ -856,7 +867,6 @@
         appendDescriptor(INTERNAL_NAME, owner);
         buf.append('.').append(name).append(' ');
         appendDescriptor(METHOD_DESCRIPTOR, desc);
-        buf.append(' ').append(itf ? "itf" : "");
         buf.append('\n');
         text.add(buf.toString());
     }
@@ -869,26 +879,35 @@
         buf.append(name);
         appendDescriptor(METHOD_DESCRIPTOR, desc);
         buf.append(" [");
+        buf.append('\n');
+        buf.append(tab3);
         appendHandle(bsm);
+        buf.append('\n');
         buf.append(tab3).append("// arguments:");
         if (bsmArgs.length == 0) {
             buf.append(" none");
         } else {
-            buf.append('\n').append(tab3);
+            buf.append('\n');
             for (int i = 0; i < bsmArgs.length; i++) {
+                buf.append(tab3);
                 Object cst = bsmArgs[i];
                 if (cst instanceof String) {
                     Printer.appendString(buf, (String) cst);
                 } else if (cst instanceof Type) {
-                    buf.append(((Type) cst).getDescriptor()).append(".class");
+                    Type type = (Type) cst;
+                    if(type.getSort() == Type.METHOD){
+                        appendDescriptor(METHOD_DESCRIPTOR, type.getDescriptor());
+                    } else {
+                        buf.append(type.getDescriptor()).append(".class");
+                    }
                 } else if (cst instanceof Handle) {
                     appendHandle((Handle) cst);
                 } else {
                     buf.append(cst);
                 }
-                buf.append(", ");
+                buf.append(", \n");
             }
-            buf.setLength(buf.length() - 2);
+            buf.setLength(buf.length() - 3);
         }
         buf.append('\n');
         buf.append(tab2).append("]\n");
@@ -1234,10 +1253,10 @@
      *            a handle, non null.
      */
     protected void appendHandle(final Handle h) {
-        buf.append('\n').append(tab3);
         int tag = h.getTag();
         buf.append("// handle kind 0x").append(Integer.toHexString(tag))
                 .append(" : ");
+        boolean isMethodHandle = false;
         switch (tag) {
         case Opcodes.H_GETFIELD:
             buf.append("GETFIELD");
@@ -1253,18 +1272,23 @@
             break;
         case Opcodes.H_INVOKEINTERFACE:
             buf.append("INVOKEINTERFACE");
+            isMethodHandle = true;
             break;
         case Opcodes.H_INVOKESPECIAL:
             buf.append("INVOKESPECIAL");
+            isMethodHandle = true;
             break;
         case Opcodes.H_INVOKESTATIC:
             buf.append("INVOKESTATIC");
+            isMethodHandle = true;
             break;
         case Opcodes.H_INVOKEVIRTUAL:
             buf.append("INVOKEVIRTUAL");
+            isMethodHandle = true;
             break;
         case Opcodes.H_NEWINVOKESPECIAL:
             buf.append("NEWINVOKESPECIAL");
+            isMethodHandle = true;
             break;
         }
         buf.append('\n');
@@ -1272,9 +1296,13 @@
         appendDescriptor(INTERNAL_NAME, h.getOwner());
         buf.append('.');
         buf.append(h.getName());
-        buf.append('(');
+        if(!isMethodHandle){
+            buf.append('(');
+        }
         appendDescriptor(HANDLE_DESCRIPTOR, h.getDesc());
-        buf.append(')').append('\n');
+        if(!isMethodHandle){
+            buf.append(')');
+        }
     }
 
     /**
--- a/jdk/src/share/classes/jdk/internal/org/objectweb/asm/version.txt	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/jdk/internal/org/objectweb/asm/version.txt	Wed Jul 05 19:33:51 2017 +0200
@@ -1,12 +1,12 @@
 Path: .
-Working Copy Root Path: /hudson/jobs/objectweb-pull/workspace/ASM_5_0_BETA
-URL: svn://svn.forge.objectweb.org/svnroot/asm/trunk/asm
-Repository Root: svn://svn.forge.objectweb.org/svnroot/asm
+Working Copy Root Path: /hudson/jobs/objectweb-pull/workspace/asm-svn-2014-03-12
+URL: file:///svnroot/asm/trunk/asm
+Repository Root: file:///svnroot/asm
 Repository UUID: 271bd773-ee82-43a6-9b2b-1890ed8ce7f9
-Revision: 1700
+Revision: 1721
 Node Kind: directory
 Schedule: normal
 Last Changed Author: ebruneton
-Last Changed Rev: 1700
-Last Changed Date: 2013-10-29 20:22:52 +0100 (Tue, 29 Oct 2013)
+Last Changed Rev: 1721
+Last Changed Date: 2014-03-02 17:25:35 +0100 (Sun, 02 Mar 2014)
 
--- a/jdk/src/share/classes/sun/awt/AWTAccessor.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/awt/AWTAccessor.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 import java.awt.event.InvocationEvent;
 import java.awt.event.KeyEvent;
 import java.awt.geom.Point2D;
+import java.awt.image.BufferStrategy;
 import java.awt.peer.ComponentPeer;
 
 import java.lang.reflect.InvocationTargetException;
@@ -243,6 +244,16 @@
          */
         void revalidateSynchronously(Component comp);
 
+        /**
+         * Creates a new strategy for multi-buffering on this component.
+         */
+        void createBufferStrategy(Component comp, int numBuffers,
+                BufferCapabilities caps) throws AWTException;
+
+        /**
+         * returns the buffer strategy used by this component.
+         */
+        BufferStrategy getBufferStrategy(Component comp);
     }
 
     /*
@@ -375,6 +386,11 @@
          * Accessor for InputEvent.getButtonDownMasks()
          */
         int[] getButtonDownMasks();
+
+        /*
+         * Accessor for InputEvent.canAccessSystemClipboard field
+         */
+        boolean canAccessSystemClipboard(InputEvent event);
     }
 
     /*
@@ -729,6 +745,13 @@
     }
 
     /*
+     * An accessor object for the SystemColor class
+     */
+    public interface SystemColorAccessor {
+        void updateSystemColors();
+    }
+
+    /*
      * Accessor instances are initialized in the static initializers of
      * corresponding AWT classes by using setters defined below.
      */
@@ -757,6 +780,7 @@
     private static SequencedEventAccessor sequencedEventAccessor;
     private static ToolkitAccessor toolkitAccessor;
     private static InvocationEventAccessor invocationEventAccessor;
+    private static SystemColorAccessor systemColorAccessor;
 
     /*
      * Set an accessor object for the java.awt.Component class.
@@ -1182,4 +1206,22 @@
     public static InvocationEventAccessor getInvocationEventAccessor() {
         return invocationEventAccessor;
     }
+
+    /*
+     * Get the accessor object for the java.awt.SystemColor class.
+     */
+    public static SystemColorAccessor getSystemColorAccessor() {
+        if (systemColorAccessor == null) {
+            unsafe.ensureClassInitialized(SystemColor.class);
+        }
+
+        return systemColorAccessor;
+    }
+
+     /*
+     * Set the accessor object for the java.awt.SystemColor class.
+     */
+     public static void setSystemColorAccessor(SystemColorAccessor systemColorAccessor) {
+         AWTAccessor.systemColorAccessor = systemColorAccessor;
+     }
 }
--- a/jdk/src/share/classes/sun/awt/FontConfiguration.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/awt/FontConfiguration.java	Wed Jul 05 19:33:51 2017 +0200
@@ -867,7 +867,7 @@
         return descriptors;
     }
 
-    private FontDescriptor[] buildFontDescriptors(int fontIndex, int styleIndex) {
+    protected FontDescriptor[] buildFontDescriptors(int fontIndex, int styleIndex) {
         String fontName = fontNames[fontIndex];
         String styleName = styleNames[styleIndex];
 
--- a/jdk/src/share/classes/sun/awt/HToolkit.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/awt/HToolkit.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,8 @@
 
 package sun.awt;
 
+import sun.awt.datatransfer.DataTransferer;
+
 import java.awt.*;
 import java.awt.dnd.*;
 import java.awt.dnd.peer.DragSourceContextPeer;
@@ -184,6 +186,11 @@
         return false;
     }
 
+    @Override
+    public DataTransferer getDataTransferer() {
+        return null;
+    }
+
     public GlobalCursorManager getGlobalCursorManager()
         throws HeadlessException {
         throw new HeadlessException();
--- a/jdk/src/share/classes/sun/awt/SunHints.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/awt/SunHints.java	Wed Jul 05 19:33:51 2017 +0200
@@ -172,7 +172,7 @@
         }
     }
 
-    private static final int NUM_KEYS = 9;
+    private static final int NUM_KEYS = 10;
     private static final int VALS_PER_KEY = 8;
 
     /**
@@ -253,6 +253,13 @@
     @Native public static final int INTVAL_STROKE_PURE = 2;
 
     /**
+     * Image scaling hint key and values
+     */
+    @Native public static final int INTKEY_RESOLUTION_VARIANT = 9;
+    @Native public static final int INTVAL_RESOLUTION_VARIANT_DEFAULT = 0;
+    @Native public static final int INTVAL_RESOLUTION_VARIANT_OFF = 1;
+    @Native public static final int INTVAL_RESOLUTION_VARIANT_ON = 2;
+    /**
      * LCD text contrast control hint key.
      * Value is "100" to make discontiguous with the others which
      * are all enumerative and are of a different class.
@@ -450,6 +457,24 @@
                            SunHints.INTVAL_STROKE_PURE,
                            "Pure stroke conversion for accurate paths");
 
+    /**
+     * Image resolution variant hint key and value objects
+     */
+    public static final Key KEY_RESOLUTION_VARIANT =
+        new SunHints.Key(SunHints.INTKEY_RESOLUTION_VARIANT,
+                         "Global image resolution variant key");
+    public static final Object VALUE_RESOLUTION_VARIANT_DEFAULT =
+        new SunHints.Value(KEY_RESOLUTION_VARIANT,
+                           SunHints.INTVAL_RESOLUTION_VARIANT_DEFAULT,
+                           "Choose image resolutions based on a default heuristic");
+    public static final Object VALUE_RESOLUTION_VARIANT_OFF =
+        new SunHints.Value(KEY_RESOLUTION_VARIANT,
+                           SunHints.INTVAL_RESOLUTION_VARIANT_OFF,
+                           "Use only the standard resolution of an image");
+    public static final Object VALUE_RESOLUTION_VARIANT_ON =
+        new SunHints.Value(KEY_RESOLUTION_VARIANT,
+                           SunHints.INTVAL_RESOLUTION_VARIANT_ON,
+                           "Always use resolution-specific variants of images");
 
     public static class LCDContrastKey extends Key {
 
--- a/jdk/src/share/classes/sun/awt/SunToolkit.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/awt/SunToolkit.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,9 @@
 import java.awt.TrayIcon;
 import java.awt.SystemTray;
 import java.awt.event.InputEvent;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
 import java.net.URL;
 import java.util.*;
 import java.util.concurrent.TimeUnit;
@@ -43,6 +46,7 @@
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
 
+import sun.awt.datatransfer.DataTransferer;
 import sun.util.logging.PlatformLogger;
 import sun.misc.SoftCache;
 import sun.font.FontDesignMetrics;
@@ -199,6 +203,8 @@
 
     public abstract boolean isTraySupported();
 
+    public abstract DataTransferer getDataTransferer();
+
     @SuppressWarnings("deprecation")
     public abstract FontPeer getFontPeer(String name, int style);
 
@@ -714,6 +720,194 @@
     static final SoftCache imgCache = new SoftCache();
 
     static Image getImageFromHash(Toolkit tk, URL url) {
+        checkPermissions(url);
+        synchronized (imgCache) {
+            Image img = (Image)imgCache.get(url);
+            if (img == null) {
+                try {
+                    img = tk.createImage(new URLImageSource(url));
+                    imgCache.put(url, img);
+                } catch (Exception e) {
+                }
+            }
+            return img;
+        }
+    }
+
+    static Image getImageFromHash(Toolkit tk,
+                                               String filename) {
+        checkPermissions(filename);
+        synchronized (imgCache) {
+            Image img = (Image)imgCache.get(filename);
+            if (img == null) {
+                try {
+                    img = tk.createImage(new FileImageSource(filename));
+                    imgCache.put(filename, img);
+                } catch (Exception e) {
+                }
+            }
+            return img;
+        }
+    }
+
+    public Image getImage(String filename) {
+        return getImageFromHash(this, filename);
+    }
+
+    public Image getImage(URL url) {
+        return getImageFromHash(this, url);
+    }
+
+    protected Image getImageWithResolutionVariant(String fileName,
+            String resolutionVariantName) {
+        synchronized (imgCache) {
+            Image image = getImageFromHash(this, fileName);
+            if (image instanceof MultiResolutionImage) {
+                return image;
+            }
+            Image resolutionVariant = getImageFromHash(this, resolutionVariantName);
+            image = createImageWithResolutionVariant(image, resolutionVariant);
+            imgCache.put(fileName, image);
+            return image;
+        }
+    }
+
+    protected Image getImageWithResolutionVariant(URL url,
+            URL resolutionVariantURL) {
+        synchronized (imgCache) {
+            Image image = getImageFromHash(this, url);
+            if (image instanceof MultiResolutionImage) {
+                return image;
+            }
+            Image resolutionVariant = getImageFromHash(this, resolutionVariantURL);
+            image = createImageWithResolutionVariant(image, resolutionVariant);
+            imgCache.put(url, image);
+            return image;
+        }
+    }
+
+
+    public Image createImage(String filename) {
+        checkPermissions(filename);
+        return createImage(new FileImageSource(filename));
+    }
+
+    public Image createImage(URL url) {
+        checkPermissions(url);
+        return createImage(new URLImageSource(url));
+    }
+
+    public Image createImage(byte[] data, int offset, int length) {
+        return createImage(new ByteArrayImageSource(data, offset, length));
+    }
+
+    public Image createImage(ImageProducer producer) {
+        return new ToolkitImage(producer);
+    }
+
+    public static Image createImageWithResolutionVariant(Image image,
+            Image resolutionVariant) {
+        return new MultiResolutionToolkitImage(image, resolutionVariant);
+    }
+
+    public int checkImage(Image img, int w, int h, ImageObserver o) {
+        if (!(img instanceof ToolkitImage)) {
+            return ImageObserver.ALLBITS;
+        }
+
+        ToolkitImage tkimg = (ToolkitImage)img;
+        int repbits;
+        if (w == 0 || h == 0) {
+            repbits = ImageObserver.ALLBITS;
+        } else {
+            repbits = tkimg.getImageRep().check(o);
+        }
+        return (tkimg.check(o) | repbits) & checkResolutionVariant(img, w, h, o);
+    }
+
+    public boolean prepareImage(Image img, int w, int h, ImageObserver o) {
+        if (w == 0 || h == 0) {
+            return true;
+        }
+
+        // Must be a ToolkitImage
+        if (!(img instanceof ToolkitImage)) {
+            return true;
+        }
+
+        ToolkitImage tkimg = (ToolkitImage)img;
+        if (tkimg.hasError()) {
+            if (o != null) {
+                o.imageUpdate(img, ImageObserver.ERROR|ImageObserver.ABORT,
+                              -1, -1, -1, -1);
+            }
+            return false;
+        }
+        ImageRepresentation ir = tkimg.getImageRep();
+        return ir.prepare(o) & prepareResolutionVariant(img, w, h, o);
+    }
+
+    private int checkResolutionVariant(Image img, int w, int h, ImageObserver o) {
+        ToolkitImage rvImage = getResolutionVariant(img);
+        // Ignore the resolution variant in case of error
+        return (rvImage == null || rvImage.hasError()) ? 0xFFFF :
+                checkImage(rvImage, 2 * w, 2 * h, MultiResolutionToolkitImage.
+                                getResolutionVariantObserver(
+                                        img, o, w, h, 2 * w, 2 * h));
+    }
+
+    private boolean prepareResolutionVariant(Image img, int w, int h,
+            ImageObserver o) {
+
+        ToolkitImage rvImage = getResolutionVariant(img);
+        // Ignore the resolution variant in case of error
+        return rvImage == null || rvImage.hasError() || prepareImage(
+                rvImage, 2 * w, 2 * h,
+                MultiResolutionToolkitImage.getResolutionVariantObserver(
+                        img, o, w, h, 2 * w, 2 * h));
+    }
+
+    private static ToolkitImage getResolutionVariant(Image image) {
+        if (image instanceof MultiResolutionToolkitImage) {
+            Image resolutionVariant = ((MultiResolutionToolkitImage) image).
+                    getResolutionVariant();
+            if (resolutionVariant instanceof ToolkitImage) {
+                return (ToolkitImage) resolutionVariant;
+            }
+        }
+        return null;
+    }
+
+    protected static boolean imageCached(Object key) {
+        return imgCache.containsKey(key);
+    }
+
+    protected static boolean imageExists(String filename) {
+        checkPermissions(filename);
+        return filename != null && new File(filename).exists();
+    }
+
+    @SuppressWarnings("try")
+    protected static boolean imageExists(URL url) {
+        checkPermissions(url);
+        if (url != null) {
+            try (InputStream is = url.openStream()) {
+                return true;
+            }catch(IOException e){
+                return false;
+            }
+        }
+        return false;
+    }
+
+    private static void checkPermissions(String filename) {
+        SecurityManager security = System.getSecurityManager();
+        if (security != null) {
+            security.checkRead(filename);
+        }
+    }
+
+    private static void checkPermissions(URL url) {
         SecurityManager sm = System.getSecurityManager();
         if (sm != null) {
             try {
@@ -741,128 +935,6 @@
                     sm.checkConnect(url.getHost(), url.getPort());
             }
         }
-        synchronized (imgCache) {
-            Image img = (Image)imgCache.get(url);
-            if (img == null) {
-                try {
-                    img = tk.createImage(new URLImageSource(url));
-                    imgCache.put(url, img);
-                } catch (Exception e) {
-                }
-            }
-            return img;
-        }
-    }
-
-    static Image getImageFromHash(Toolkit tk,
-                                               String filename) {
-        SecurityManager security = System.getSecurityManager();
-        if (security != null) {
-            security.checkRead(filename);
-        }
-        synchronized (imgCache) {
-            Image img = (Image)imgCache.get(filename);
-            if (img == null) {
-                try {
-                    img = tk.createImage(new FileImageSource(filename));
-                    imgCache.put(filename, img);
-                } catch (Exception e) {
-                }
-            }
-            return img;
-        }
-    }
-
-    public Image getImage(String filename) {
-        return getImageFromHash(this, filename);
-    }
-
-    public Image getImage(URL url) {
-        return getImageFromHash(this, url);
-    }
-
-    public Image createImage(String filename) {
-        SecurityManager security = System.getSecurityManager();
-        if (security != null) {
-            security.checkRead(filename);
-        }
-        return createImage(new FileImageSource(filename));
-    }
-
-    public Image createImage(URL url) {
-        SecurityManager sm = System.getSecurityManager();
-        if (sm != null) {
-            try {
-                java.security.Permission perm =
-                    url.openConnection().getPermission();
-                if (perm != null) {
-                    try {
-                        sm.checkPermission(perm);
-                    } catch (SecurityException se) {
-                        // fallback to checkRead/checkConnect for pre 1.2
-                        // security managers
-                        if ((perm instanceof java.io.FilePermission) &&
-                            perm.getActions().indexOf("read") != -1) {
-                            sm.checkRead(perm.getName());
-                        } else if ((perm instanceof
-                            java.net.SocketPermission) &&
-                            perm.getActions().indexOf("connect") != -1) {
-                            sm.checkConnect(url.getHost(), url.getPort());
-                        } else {
-                            throw se;
-                        }
-                    }
-                }
-            } catch (java.io.IOException ioe) {
-                    sm.checkConnect(url.getHost(), url.getPort());
-            }
-        }
-        return createImage(new URLImageSource(url));
-    }
-
-    public Image createImage(byte[] data, int offset, int length) {
-        return createImage(new ByteArrayImageSource(data, offset, length));
-    }
-
-    public Image createImage(ImageProducer producer) {
-        return new ToolkitImage(producer);
-    }
-
-    public int checkImage(Image img, int w, int h, ImageObserver o) {
-        if (!(img instanceof ToolkitImage)) {
-            return ImageObserver.ALLBITS;
-        }
-
-        ToolkitImage tkimg = (ToolkitImage)img;
-        int repbits;
-        if (w == 0 || h == 0) {
-            repbits = ImageObserver.ALLBITS;
-        } else {
-            repbits = tkimg.getImageRep().check(o);
-        }
-        return tkimg.check(o) | repbits;
-    }
-
-    public boolean prepareImage(Image img, int w, int h, ImageObserver o) {
-        if (w == 0 || h == 0) {
-            return true;
-        }
-
-        // Must be a ToolkitImage
-        if (!(img instanceof ToolkitImage)) {
-            return true;
-        }
-
-        ToolkitImage tkimg = (ToolkitImage)img;
-        if (tkimg.hasError()) {
-            if (o != null) {
-                o.imageUpdate(img, ImageObserver.ERROR|ImageObserver.ABORT,
-                              -1, -1, -1, -1);
-            }
-            return false;
-        }
-        ImageRepresentation ir = tkimg.getImageRep();
-        return ir.prepare(o);
     }
 
     /**
@@ -1120,19 +1192,6 @@
         return getStartupLocale();
     }
 
-    private static String dataTransfererClassName = null;
-
-    protected static void setDataTransfererClassName(String className) {
-        dataTransfererClassName = className;
-    }
-
-    public static String getDataTransfererClassName() {
-        if (dataTransfererClassName == null) {
-            Toolkit.getDefaultToolkit(); // transferer set during toolkit init
-        }
-        return dataTransfererClassName;
-    }
-
     // Support for window closing event notifications
     private transient WindowClosingListener windowClosingListener = null;
     /**
--- a/jdk/src/share/classes/sun/awt/datatransfer/ClipboardTransferable.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/awt/datatransfer/ClipboardTransferable.java	Wed Jul 05 19:33:51 2017 +0200
@@ -32,7 +32,6 @@
 import java.io.IOException;
 
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.Map;
 
 
@@ -55,7 +54,7 @@
  * @since 1.4 (appeared in modified form as FullyRenderedTransferable in 1.3.1)
  */
 public class ClipboardTransferable implements Transferable {
-    private final HashMap flavorsToData = new HashMap();
+    private final Map<DataFlavor, Object> flavorsToData = new HashMap<>();
     private DataFlavor[] flavors = new DataFlavor[0];
 
     private final class DataFactory {
@@ -84,20 +83,13 @@
                 // Since the SystemFlavorMap will specify many DataFlavors
                 // which map to the same format, we should cache data as we
                 // read it.
-                HashMap cached_data = new HashMap(formats.length, 1.0f);
+                Map<Long, Object> cached_data = new HashMap<>(formats.length, 1.0f);
+                DataTransferer.getInstance()
+                        .getFlavorsForFormats(formats, SunClipboard.flavorMap)
+                        .entrySet()
+                        .forEach(entry -> fetchOneFlavor(clipboard, entry.getKey(), entry.getValue(), cached_data));
+                flavors = DataTransferer.setToSortedDataFlavorArray(flavorsToData.keySet());
 
-                Map flavorsForFormats = DataTransferer.getInstance().
-                    getFlavorsForFormats(formats, SunClipboard.flavorMap);
-                for (Iterator iter = flavorsForFormats.keySet().iterator();
-                     iter.hasNext(); )
-                {
-                    DataFlavor flavor = (DataFlavor)iter.next();
-                    Long lFormat = (Long)flavorsForFormats.get(flavor);
-
-                    fetchOneFlavor(clipboard, flavor, lFormat, cached_data);
-                }
-
-                flavors = DataTransferer.setToSortedDataFlavorArray(flavorsToData.keySet());
             }
         } finally {
             clipboard.closeClipboard();
@@ -105,13 +97,12 @@
     }
 
     private boolean fetchOneFlavor(SunClipboard clipboard, DataFlavor flavor,
-                                   Long lFormat, HashMap cached_data)
+                                   long format, Map<Long, Object> cached_data)
     {
         if (!flavorsToData.containsKey(flavor)) {
-            long format = lFormat.longValue();
             Object data = null;
 
-            if (!cached_data.containsKey(lFormat)) {
+            if (!cached_data.containsKey(format)) {
                 try {
                     data = clipboard.getClipboardData(format);
                 } catch (IOException e) {
@@ -122,9 +113,9 @@
 
                 // Cache this data, even if it's null, so we don't have to go
                 // to native code again for this format.
-                cached_data.put(lFormat, data);
+                cached_data.put(format, data);
             } else {
-                data = cached_data.get(lFormat);
+                data = cached_data.get(format);
             }
 
             // Casting IOException to byte array causes ClassCastException.
@@ -134,8 +125,7 @@
                 flavorsToData.put(flavor, data);
                 return false;
             } else if (data != null) {
-                flavorsToData.put(flavor, new DataFactory(format,
-                                                          (byte[])data));
+                flavorsToData.put(flavor, new DataFactory(format, (byte[])data));
                 return true;
             }
         }
@@ -143,14 +133,17 @@
         return false;
     }
 
+    @Override
     public DataFlavor[] getTransferDataFlavors() {
         return flavors.clone();
     }
 
+    @Override
     public boolean isDataFlavorSupported(DataFlavor flavor) {
         return flavorsToData.containsKey(flavor);
     }
 
+    @Override
     public Object getTransferData(DataFlavor flavor)
         throws UnsupportedFlavorException, IOException
     {
--- a/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,10 @@
 
 package sun.awt.datatransfer;
 
-import java.awt.AWTError;
 import java.awt.EventQueue;
+import java.awt.Graphics;
 import java.awt.Image;
-import java.awt.Graphics;
+import java.awt.Toolkit;
 
 import java.awt.datatransfer.DataFlavor;
 import java.awt.datatransfer.FlavorMap;
@@ -70,6 +70,7 @@
 import java.security.PrivilegedExceptionAction;
 import java.security.ProtectionDomain;
 
+import java.util.AbstractMap;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -112,6 +113,7 @@
 import sun.awt.image.ToolkitImage;
 
 import java.io.FilePermission;
+import java.util.stream.Stream;
 
 
 /**
@@ -136,27 +138,6 @@
  * @since 1.3.1
  */
 public abstract class DataTransferer {
-
-    /**
-     * Cached value of Class.forName("[C");
-     */
-    public static final Class charArrayClass;
-
-    /**
-     * Cached value of Class.forName("[B");
-     */
-    public static final Class byteArrayClass;
-
-    /**
-     * The <code>DataFlavor</code> representing plain text with Unicode
-     * encoding, where:
-     * <pre>
-     *     representationClass = java.lang.String
-     *     mimeType            = "text/plain; charset=Unicode"
-     * </pre>
-     */
-    public static final DataFlavor plainTextStringFlavor;
-
     /**
      * The <code>DataFlavor</code> representing a Java text encoding String
      * encoded in UTF-8, where
@@ -174,9 +155,9 @@
         private static final SortedSet<String> standardEncodings = load();
 
         private static SortedSet<String> load() {
-            final Comparator comparator =
+            final Comparator<String> comparator =
                     new CharsetComparator(IndexedComparator.SELECT_WORST);
-            final SortedSet<String> tempSet = new TreeSet<String>(comparator);
+            final SortedSet<String> tempSet = new TreeSet<>(comparator);
             tempSet.add("US-ASCII");
             tempSet.add("ISO-8859-1");
             tempSet.add("UTF-8");
@@ -194,7 +175,7 @@
      * listed in the DataFlavor.selectBestTextFlavor method comment. Additional
      * entries may be added during the life of the JRE for text/<other> types.
      */
-    private static final Map textMIMESubtypeCharsetSupport;
+    private static final Map<String, Boolean> textMIMESubtypeCharsetSupport;
 
     /**
      * Cache of the platform default encoding as specified in the
@@ -206,67 +187,43 @@
      * A collection of all natives listed in flavormap.properties with
      * a primary MIME type of "text".
      */
-    private static final Set textNatives =
-        Collections.synchronizedSet(new HashSet());
+    private static final Set<Long> textNatives =
+            Collections.synchronizedSet(new HashSet<>());
 
     /**
      * The native encodings/charsets for the Set of textNatives.
      */
-    private static final Map nativeCharsets =
-        Collections.synchronizedMap(new HashMap());
+    private static final Map<Long, String> nativeCharsets =
+            Collections.synchronizedMap(new HashMap<>());
 
     /**
      * The end-of-line markers for the Set of textNatives.
      */
-    private static final Map nativeEOLNs =
-        Collections.synchronizedMap(new HashMap());
+    private static final Map<Long, String> nativeEOLNs =
+            Collections.synchronizedMap(new HashMap<>());
 
     /**
      * The number of terminating NUL bytes for the Set of textNatives.
      */
-    private static final Map nativeTerminators =
-        Collections.synchronizedMap(new HashMap());
+    private static final Map<Long, Integer> nativeTerminators =
+            Collections.synchronizedMap(new HashMap<>());
 
     /**
      * The key used to store pending data conversion requests for an AppContext.
      */
     private static final String DATA_CONVERTER_KEY = "DATA_CONVERTER_KEY";
 
-    /**
-     * The singleton DataTransferer instance. It is created during MToolkit
-     * or WToolkit initialization.
-     */
-    private static DataTransferer transferer;
-
     private static final PlatformLogger dtLog = PlatformLogger.getLogger("sun.awt.datatransfer.DataTransfer");
 
     static {
-        Class tCharArrayClass = null, tByteArrayClass = null;
-        try {
-            tCharArrayClass = Class.forName("[C");
-            tByteArrayClass = Class.forName("[B");
-        } catch (ClassNotFoundException cannotHappen) {
-        }
-        charArrayClass = tCharArrayClass;
-        byteArrayClass = tByteArrayClass;
-
-        DataFlavor tPlainTextStringFlavor = null;
-        try {
-            tPlainTextStringFlavor = new DataFlavor
-                ("text/plain;charset=Unicode;class=java.lang.String");
-        } catch (ClassNotFoundException cannotHappen) {
-        }
-        plainTextStringFlavor = tPlainTextStringFlavor;
-
         DataFlavor tJavaTextEncodingFlavor = null;
         try {
-            tJavaTextEncodingFlavor = new DataFlavor
-                ("application/x-java-text-encoding;class=\"[B\"");
+            tJavaTextEncodingFlavor = new DataFlavor("application/x-java-text-encoding;class=\"[B\"");
         } catch (ClassNotFoundException cannotHappen) {
         }
         javaTextEncodingFlavor = tJavaTextEncodingFlavor;
 
-        Map tempMap = new HashMap(17);
+        Map<String, Boolean> tempMap = new HashMap<>(17);
         tempMap.put("sgml", Boolean.TRUE);
         tempMap.put("xml", Boolean.TRUE);
         tempMap.put("html", Boolean.TRUE);
@@ -290,63 +247,8 @@
      * that in a headless environment, there may be no DataTransferer instance;
      * instead, null will be returned.
      */
-    public static DataTransferer getInstance() {
-        synchronized (DataTransferer.class) {
-            if (transferer == null) {
-                final String name = SunToolkit.getDataTransfererClassName();
-                if (name != null) {
-                    PrivilegedAction<DataTransferer> action = new PrivilegedAction<DataTransferer>()
-                    {
-                      public DataTransferer run() {
-                          Class cls = null;
-                          Method method = null;
-                          DataTransferer ret = null;
-
-                          try {
-                              cls = Class.forName(name);
-                          } catch (ClassNotFoundException e) {
-                              ClassLoader cl = ClassLoader.
-                                  getSystemClassLoader();
-                              if (cl != null) {
-                                  try {
-                                      cls = cl.loadClass(name);
-                                  } catch (ClassNotFoundException ee) {
-                                      ee.printStackTrace();
-                                      throw new AWTError("DataTransferer not found: " + name);
-                                  }
-                              }
-                          }
-                          if (cls != null) {
-                              try {
-                                  method = cls.getDeclaredMethod("getInstanceImpl");
-                                  method.setAccessible(true);
-                              } catch (NoSuchMethodException e) {
-                                  e.printStackTrace();
-                                  throw new AWTError("Cannot instantiate DataTransferer: " + name);
-                              } catch (SecurityException e) {
-                                  e.printStackTrace();
-                                  throw new AWTError("Access is denied for DataTransferer: " + name);
-                              }
-                          }
-                          if (method != null) {
-                              try {
-                                  ret = (DataTransferer) method.invoke(null);
-                              } catch (InvocationTargetException e) {
-                                  e.printStackTrace();
-                                  throw new AWTError("Cannot instantiate DataTransferer: " + name);
-                              } catch (IllegalAccessException e) {
-                                  e.printStackTrace();
-                                  throw new AWTError("Cannot access DataTransferer: " + name);
-                              }
-                          }
-                          return ret;
-                      }
-                    };
-                    transferer = AccessController.doPrivileged(action);
-                }
-            }
-        }
-        return transferer;
+    public static synchronized DataTransferer getInstance() {
+        return ((SunToolkit) Toolkit.getDefaultToolkit()).getDataTransferer();
     }
 
     /**
@@ -409,29 +311,27 @@
             return false;
         }
 
-        Object support = textMIMESubtypeCharsetSupport.get(subType);
+        Boolean support = textMIMESubtypeCharsetSupport.get(subType);
 
         if (support != null) {
-            return (support == Boolean.TRUE);
+            return support;
         }
 
         boolean ret_val = (flavor.getParameter("charset") != null);
-        textMIMESubtypeCharsetSupport.put
-            (subType, (ret_val) ? Boolean.TRUE : Boolean.FALSE);
+        textMIMESubtypeCharsetSupport.put(subType, ret_val);
         return ret_val;
     }
     public static boolean doesSubtypeSupportCharset(String subType,
                                                     String charset)
     {
-        Object support = textMIMESubtypeCharsetSupport.get(subType);
+        Boolean support = textMIMESubtypeCharsetSupport.get(subType);
 
         if (support != null) {
-            return (support == Boolean.TRUE);
+            return support;
         }
 
         boolean ret_val = (charset != null);
-        textMIMESubtypeCharsetSupport.put
-            (subType, (ret_val) ? Boolean.TRUE : Boolean.FALSE);
+        textMIMESubtypeCharsetSupport.put(subType, ret_val);
         return ret_val;
     }
 
@@ -459,14 +359,14 @@
         if (flavor.isRepresentationClassReader() ||
             String.class.equals(rep_class) ||
             flavor.isRepresentationClassCharBuffer() ||
-            DataTransferer.charArrayClass.equals(rep_class))
+            char[].class.equals(rep_class))
         {
             return true;
         }
 
         if (!(flavor.isRepresentationClassInputStream() ||
               flavor.isRepresentationClassByteBuffer() ||
-              DataTransferer.byteArrayClass.equals(rep_class))) {
+              byte[].class.equals(rep_class))) {
             return false;
         }
 
@@ -490,15 +390,14 @@
 
         return (flavor.isRepresentationClassInputStream() ||
                 flavor.isRepresentationClassByteBuffer() ||
-                DataTransferer.byteArrayClass.
-                    equals(flavor.getRepresentationClass()));
+                byte[].class.equals(flavor.getRepresentationClass()));
     }
 
     /**
      * Determines whether this JRE can both encode and decode text in the
      * specified encoding.
      */
-    public static boolean isEncodingSupported(String encoding) {
+    private static boolean isEncodingSupported(String encoding) {
         if (encoding == null) {
             return false;
         }
@@ -536,37 +435,35 @@
         }
 
         return new FlavorTable() {
-                public Map getNativesForFlavors(DataFlavor[] flavors) {
-                    return map.getNativesForFlavors(flavors);
-                }
-                public Map getFlavorsForNatives(String[] natives) {
-                    return map.getFlavorsForNatives(natives);
+            @Override
+            public Map<DataFlavor, String> getNativesForFlavors(DataFlavor[] flavors) {
+                return map.getNativesForFlavors(flavors);
+            }
+            @Override
+            public Map<String, DataFlavor> getFlavorsForNatives(String[] natives) {
+                return map.getFlavorsForNatives(natives);
+            }
+            @Override
+            public List<String> getNativesForFlavor(DataFlavor flav) {
+                Map<DataFlavor, String> natives = getNativesForFlavors(new DataFlavor[]{flav});
+                String nat = natives.get(flav);
+                if (nat != null) {
+                    return Collections.singletonList(nat);
+                } else {
+                    return Collections.emptyList();
                 }
-                public List getNativesForFlavor(DataFlavor flav) {
-                    Map natives =
-                        getNativesForFlavors(new DataFlavor[] { flav } );
-                    String nat = (String)natives.get(flav);
-                    if (nat != null) {
-                        List list = new ArrayList(1);
-                        list.add(nat);
-                        return list;
-                    } else {
-                        return Collections.EMPTY_LIST;
-                    }
+            }
+            @Override
+            public List<DataFlavor> getFlavorsForNative(String nat) {
+                Map<String, DataFlavor> flavors = getFlavorsForNatives(new String[]{nat});
+                DataFlavor flavor = flavors.get(nat);
+                if (flavor != null) {
+                    return Collections.singletonList(flavor);
+                } else {
+                    return Collections.emptyList();
                 }
-                public List getFlavorsForNative(String nat) {
-                    Map flavors =
-                        getFlavorsForNatives(new String[] { nat } );
-                    DataFlavor flavor = (DataFlavor)flavors.get(nat);
-                    if (flavor != null) {
-                        List list = new ArrayList(1);
-                        list.add(flavor);
-                        return list;
-                    } else {
-                        return Collections.EMPTY_LIST;
-                    }
-                }
-            };
+            }
+        };
     }
 
     /**
@@ -588,13 +485,13 @@
 
         textNatives.add(format);
         nativeCharsets.put(format, (charset != null && charset.length() != 0)
-            ? charset : getDefaultTextCharset());
+                ? charset : getDefaultTextCharset());
         if (eoln != null && eoln.length() != 0 && !eoln.equals("\n")) {
             nativeEOLNs.put(format, eoln);
         }
         if (terminators != null && terminators.length() != 0) {
             Integer iTerminators = Integer.valueOf(terminators);
-            if (iTerminators.intValue() > 0) {
+            if (iTerminators > 0) {
                 nativeTerminators.put(format, iTerminators);
             }
         }
@@ -609,7 +506,7 @@
     }
 
     protected String getCharsetForTextFormat(Long lFormat) {
-        return (String)nativeCharsets.get(lFormat);
+        return nativeCharsets.get(lFormat);
     }
 
     /**
@@ -649,32 +546,18 @@
      * The map keys are sorted according to the native formats preference
      * order.
      */
-    public SortedMap<Long,DataFlavor> getFormatsForTransferable(
-                               Transferable contents, FlavorTable map)
+    public SortedMap<Long,DataFlavor> getFormatsForTransferable(Transferable contents,
+                                                                FlavorTable map)
     {
         DataFlavor[] flavors = contents.getTransferDataFlavors();
         if (flavors == null) {
-            return new TreeMap();
+            return Collections.emptySortedMap();
         }
         return getFormatsForFlavors(flavors, map);
     }
 
     /**
      * Returns a Map whose keys are all of the possible formats into which data
-     * in the specified DataFlavor can be translated. The value of each key
-     * is the DataFlavor in which a Transferable's data should be requested
-     * when converting to the format.
-     * <p>
-     * The map keys are sorted according to the native formats preference
-     * order.
-     */
-    public SortedMap getFormatsForFlavor(DataFlavor flavor, FlavorTable map) {
-        return getFormatsForFlavors(new DataFlavor[] { flavor },
-                                    map);
-    }
-
-    /**
-     * Returns a Map whose keys are all of the possible formats into which data
      * in the specified DataFlavors can be translated. The value of each key
      * is the DataFlavor in which the Transferable's data should be requested
      * when converting to the format.
@@ -687,18 +570,16 @@
      *            DataFlavors and data formats
      * @throws NullPointerException if flavors or map is <code>null</code>
      */
-    public SortedMap <Long, DataFlavor> getFormatsForFlavors(
-        DataFlavor[] flavors, FlavorTable map)
+    public SortedMap<Long, DataFlavor> getFormatsForFlavors(DataFlavor[] flavors,
+                                                            FlavorTable map)
     {
-        Map <Long,DataFlavor> formatMap =
-            new HashMap <> (flavors.length);
-        Map <Long,DataFlavor> textPlainMap =
-            new HashMap <> (flavors.length);
+        Map<Long,DataFlavor> formatMap = new HashMap<>(flavors.length);
+        Map<Long,DataFlavor> textPlainMap = new HashMap<>(flavors.length);
         // Maps formats to indices that will be used to sort the formats
         // according to the preference order.
         // Larger index value corresponds to the more preferable format.
-        Map indexMap = new HashMap(flavors.length);
-        Map textPlainIndexMap = new HashMap(flavors.length);
+        Map<Long, Integer> indexMap = new HashMap<>(flavors.length);
+        Map<Long, Integer> textPlainIndexMap = new HashMap<>(flavors.length);
 
         int currentIndex = 0;
 
@@ -718,14 +599,13 @@
                 flavor.isRepresentationClassInputStream() ||
                 flavor.isRepresentationClassRemote())
             {
-                List natives = map.getNativesForFlavor(flavor);
+                List<String> natives = map.getNativesForFlavor(flavor);
 
                 currentIndex += natives.size();
 
-                for (Iterator iter = natives.iterator(); iter.hasNext(); ) {
-                    Long lFormat =
-                        getFormatForNativeAsLong((String)iter.next());
-                    Integer index = Integer.valueOf(currentIndex--);
+                for (String aNative : natives) {
+                    Long lFormat = getFormatForNativeAsLong(aNative);
+                    Integer index = currentIndex--;
 
                     formatMap.put(lFormat, flavor);
                     indexMap.put(lFormat, index);
@@ -735,9 +615,8 @@
                     // for a single text/* flavor, we would prefer that
                     // text/plain native data come from a text/plain flavor.
                     if (("text".equals(flavor.getPrimaryType()) &&
-                         "plain".equals(flavor.getSubType())) ||
-                        flavor.equals(DataFlavor.stringFlavor))
-                    {
+                            "plain".equals(flavor.getSubType())) ||
+                            flavor.equals(DataFlavor.stringFlavor)) {
                         textPlainMap.put(lFormat, flavor);
                         textPlainIndexMap.put(lFormat, index);
                     }
@@ -751,9 +630,9 @@
         indexMap.putAll(textPlainIndexMap);
 
         // Sort the map keys according to the formats preference order.
-        Comparator comparator =
-            new IndexOrderComparator(indexMap, IndexedComparator.SELECT_WORST);
-        SortedMap sortedMap = new TreeMap(comparator);
+        Comparator<Long> comparator =
+                new IndexOrderComparator(indexMap, IndexedComparator.SELECT_WORST);
+        SortedMap<Long, DataFlavor> sortedMap = new TreeMap<>(comparator);
         sortedMap.putAll(formatMap);
 
         return sortedMap;
@@ -767,24 +646,6 @@
                                                    FlavorTable map) {
         return keysToLongArray(getFormatsForTransferable(contents, map));
     }
-    public long[] getFormatsForFlavorAsArray(DataFlavor flavor,
-                                             FlavorTable map) {
-        return keysToLongArray(getFormatsForFlavor(flavor, map));
-    }
-    public long[] getFormatsForFlavorsAsArray(DataFlavor[] flavors,
-                                              FlavorTable map) {
-        return keysToLongArray(getFormatsForFlavors(flavors, map));
-    }
-
-    /**
-     * Returns a Map whose keys are all of the possible DataFlavors into which
-     * data in the specified format can be translated. The value of each key
-     * is the format in which the Clipboard or dropped data should be requested
-     * when converting to the DataFlavor.
-     */
-    public Map getFlavorsForFormat(long format, FlavorTable map) {
-        return getFlavorsForFormats(new long[] { format }, map);
-    }
 
     /**
      * Returns a Map whose keys are all of the possible DataFlavors into which
@@ -792,10 +653,10 @@
      * is the format in which the Clipboard or dropped data should be requested
      * when converting to the DataFlavor.
      */
-    public Map getFlavorsForFormats(long[] formats, FlavorTable map) {
-        Map flavorMap = new HashMap(formats.length);
-        Set mappingSet = new HashSet(formats.length);
-        Set flavorSet = new HashSet(formats.length);
+    public Map<DataFlavor, Long> getFlavorsForFormats(long[] formats, FlavorTable map) {
+        Map<DataFlavor, Long> flavorMap = new HashMap<>(formats.length);
+        Set<AbstractMap.SimpleEntry<Long, DataFlavor>> mappingSet = new HashSet<>(formats.length);
+        Set<DataFlavor> flavorSet = new HashSet<>(formats.length);
 
         // First step: build flavorSet, mappingSet and initial flavorMap
         // flavorSet  - the set of all the DataFlavors into which
@@ -804,27 +665,22 @@
         //              into any DataFlavor;
         // flavorMap  - after this step, this map maps each of the DataFlavors
         //              from flavorSet to any of the specified formats.
-        for (int i = 0; i < formats.length; i++) {
-            long format = formats[i];
+        for (long format : formats) {
             String nat = getNativeForFormat(format);
-            List flavors = map.getFlavorsForNative(nat);
-
-            for (Iterator iter = flavors.iterator(); iter.hasNext(); ) {
-                DataFlavor flavor = (DataFlavor)iter.next();
-
+            List<DataFlavor> flavors = map.getFlavorsForNative(nat);
+            for (DataFlavor flavor : flavors) {
                 // Don't explicitly test for String, since it is just a special
                 // case of Serializable
                 if (flavor.isFlavorTextType() ||
-                    flavor.isFlavorJavaFileListType() ||
-                    DataFlavor.imageFlavor.equals(flavor) ||
-                    flavor.isRepresentationClassSerializable() ||
-                    flavor.isRepresentationClassInputStream() ||
-                    flavor.isRepresentationClassRemote())
-                {
-                    Long lFormat = Long.valueOf(format);
-                    Object mapping =
-                        DataTransferer.createMapping(lFormat, flavor);
-                    flavorMap.put(flavor, lFormat);
+                        flavor.isFlavorJavaFileListType() ||
+                        DataFlavor.imageFlavor.equals(flavor) ||
+                        flavor.isRepresentationClassSerializable() ||
+                        flavor.isRepresentationClassInputStream() ||
+                        flavor.isRepresentationClassRemote()) {
+
+                    AbstractMap.SimpleEntry<Long, DataFlavor> mapping =
+                            new AbstractMap.SimpleEntry<>(format, flavor);
+                    flavorMap.put(flavor, format);
                     mappingSet.add(mapping);
                     flavorSet.add(flavor);
                 }
@@ -844,19 +700,11 @@
         // a mappingSet of all format-to-flavor mappings for the specified formats
         // and check if the format-to-flavor mapping exists for the
         // (flavor,format) pair being added.
-        for (Iterator flavorIter = flavorSet.iterator();
-             flavorIter.hasNext(); ) {
-            DataFlavor flavor = (DataFlavor)flavorIter.next();
-
-            List natives = map.getNativesForFlavor(flavor);
-
-            for (Iterator nativeIter = natives.iterator();
-                 nativeIter.hasNext(); ) {
-                Long lFormat =
-                    getFormatForNativeAsLong((String)nativeIter.next());
-                Object mapping = DataTransferer.createMapping(lFormat, flavor);
-
-                if (mappingSet.contains(mapping)) {
+        for (DataFlavor flavor : flavorSet) {
+            List<String> natives = map.getNativesForFlavor(flavor);
+            for (String aNative : natives) {
+                Long lFormat = getFormatForNativeAsLong(aNative);
+                if (mappingSet.contains(new AbstractMap.SimpleEntry<>(lFormat, flavor))) {
                     flavorMap.put(flavor, lFormat);
                     break;
                 }
@@ -879,24 +727,19 @@
      * @throws NullPointerException if formats or map is <code>null</code>
      */
     public Set getFlavorsForFormatsAsSet(long[] formats, FlavorTable map) {
-        Set flavorSet = new HashSet(formats.length);
-
-        for (int i = 0; i < formats.length; i++) {
-            String nat = getNativeForFormat(formats[i]);
-            List flavors = map.getFlavorsForNative(nat);
-
-            for (Iterator iter = flavors.iterator(); iter.hasNext(); ) {
-                DataFlavor flavor = (DataFlavor)iter.next();
-
+        Set<DataFlavor> flavorSet = new HashSet<>(formats.length);
+
+        for (long format : formats) {
+            List<DataFlavor> flavors = map.getFlavorsForNative(getNativeForFormat(format));
+            for (DataFlavor flavor : flavors) {
                 // Don't explicitly test for String, since it is just a special
                 // case of Serializable
                 if (flavor.isFlavorTextType() ||
-                    flavor.isFlavorJavaFileListType() ||
-                    DataFlavor.imageFlavor.equals(flavor) ||
-                    flavor.isRepresentationClassSerializable() ||
-                    flavor.isRepresentationClassInputStream() ||
-                    flavor.isRepresentationClassRemote())
-                {
+                        flavor.isFlavorJavaFileListType() ||
+                        DataFlavor.imageFlavor.equals(flavor) ||
+                        flavor.isRepresentationClassSerializable() ||
+                        flavor.isRepresentationClassInputStream() ||
+                        flavor.isRepresentationClassRemote()) {
                     flavorSet.add(flavor);
                 }
             }
@@ -907,25 +750,6 @@
 
     /**
      * Returns an array of all DataFlavors for which
-     * 1) a mapping from the specified format exists in the specified map and
-     * 2) the data translation for this mapping can be performed by the data
-     * transfer subsystem.
-     * The array will be sorted according to a
-     * <code>DataFlavorComparator</code> created with the specified
-     * map as an argument.
-     *
-     * @param format the data format
-     * @param map the FlavorTable which contains mappings between
-     *            DataFlavors and data formats
-     * @throws NullPointerException if map is <code>null</code>
-     */
-    public DataFlavor[] getFlavorsForFormatAsArray(long format,
-                                                   FlavorTable map) {
-        return getFlavorsForFormatsAsArray(new long[] { format }, map);
-    }
-
-    /**
-     * Returns an array of all DataFlavors for which
      * 1) a mapping from at least one of the specified formats exists in the
      * specified map and
      * 2) the data translation for this mapping can be performed by the data
@@ -947,22 +771,6 @@
     }
 
     /**
-     * Returns an object that represents a mapping between the specified
-     * key and value. <tt>null</tt> values and the <tt>null</tt> keys are
-     * permitted. The internal representation of the mapping object is
-     * irrelevant. The only requrement is that the two mapping objects are equal
-     * if and only if their keys are equal and their values are equal.
-     * More formally, the two mapping objects are equal if and only if
-     * <tt>(value1 == null ? value2 == null : value1.equals(value2))
-     * && (key1 == null ? key2 == null : key1.equals(key2))</tt>.
-     */
-    private static Object createMapping(Object key, Object value) {
-        // NOTE: Should be updated to use AbstractMap.SimpleEntry as
-        // soon as it is made public.
-        return Arrays.asList(new Object[] { key, value });
-    }
-
-    /**
      * Looks-up or registers the String native with the native data transfer
      * system and returns a long format corresponding to that native.
      */
@@ -1013,17 +821,16 @@
     private byte[] translateTransferableString(String str,
                                                long format) throws IOException
     {
-        Long lFormat = Long.valueOf(format);
+        Long lFormat = format;
         String charset = getBestCharsetForTextFormat(lFormat, null);
         // Search and replace EOLN. Note that if EOLN is "\n", then we
         // never added an entry to nativeEOLNs anyway, so we'll skip this
         // code altogether.
         // windows: "abc\nde"->"abc\r\nde"
-        String eoln = (String)nativeEOLNs.get(lFormat);
+        String eoln = nativeEOLNs.get(lFormat);
         if (eoln != null) {
             int length = str.length();
-            StringBuffer buffer =
-                new StringBuffer(length * 2); // 2 is a heuristic
+            StringBuilder buffer = new StringBuilder(length * 2); // 2 is a heuristic
             for (int i = 0; i < length; i++) {
                 // Fix for 4914613 - skip native EOLN
                 if (str.startsWith(eoln, i)) {
@@ -1048,9 +855,9 @@
         // the we never added an entry to nativeTerminators anyway, so
         // we'll skip code altogether.
         // "abcde" -> "abcde\0"
-        Integer terminators = (Integer)nativeTerminators.get(lFormat);
+        Integer terminators = nativeTerminators.get(lFormat);
         if (terminators != null) {
-            int numTerminators = terminators.intValue();
+            int numTerminators = terminators;
             byte[] terminatedBytes =
                 new byte[bytes.length + numTerminators];
             System.arraycopy(bytes, 0, terminatedBytes, 0, bytes.length);
@@ -1073,7 +880,7 @@
             throws IOException
     {
 
-        Long lFormat = Long.valueOf(format);
+        Long lFormat = format;
         String charset = getBestCharsetForTextFormat(lFormat, localeTransferable);
 
         // Locate terminating NUL bytes. Note that if terminators is 0,
@@ -1086,11 +893,11 @@
         // multibyte coding like UTF-8, but helps understand the procedure.
         // "abcde\0" -> "abcde"
 
-        String eoln = (String)nativeEOLNs.get(lFormat);
-        Integer terminators = (Integer)nativeTerminators.get(lFormat);
+        String eoln = nativeEOLNs.get(lFormat);
+        Integer terminators = nativeTerminators.get(lFormat);
         int count;
         if (terminators != null) {
-            int numTerminators = terminators.intValue();
+            int numTerminators = terminators;
 search:
             for (count = 0; count < (bytes.length - numTerminators + 1); count += numTerminators) {
                 for (int i = count; i < count + numTerminators; i++) {
@@ -1123,7 +930,6 @@
 
             char[] buf = converted.toCharArray();
             char[] eoln_arr = eoln.toCharArray();
-            converted = null;
             int j = 0;
             boolean match;
 
@@ -1214,7 +1020,7 @@
                     ("cannot transfer non-text data as Reader");
             }
 
-            StringBuffer buf = new StringBuffer();
+            StringBuilder buf = new StringBuilder();
             try (Reader r = (Reader)obj) {
                 int c;
                 while ((c = r.read()) != -1) {
@@ -1243,7 +1049,7 @@
                 format);
 
         // Source data is a char array. Convert to a String and recur.
-        } else if (charArrayClass.equals(flavor.getRepresentationClass())) {
+        } else if (char[].class.equals(flavor.getRepresentationClass())) {
             if (!(isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
                 throw new IOException
                     ("cannot transfer non-text data as char array");
@@ -1274,7 +1080,7 @@
         // Source data is a byte array. For arbitrary flavors, simply return
         // the array. For text flavors, decode back to a String and recur to
         // reencode according to the requested format.
-        } else if (byteArrayClass.equals(flavor.getRepresentationClass())) {
+        } else if (byte[].class.equals(flavor.getRepresentationClass())) {
             byte[] bytes = (byte[])obj;
 
             if (isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
@@ -1342,7 +1148,7 @@
             final List list = (List)obj;
             final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents);
             final ArrayList<String> fileList = castToFiles(list, userProtectionDomain);
-            final ArrayList<String> uriList = new ArrayList<String>(fileList.size());
+            final ArrayList<String> uriList = new ArrayList<>(fileList.size());
             for (String fileObject : fileList) {
                 final URI uri = new File(fileObject).toURI();
                 // Some implementations are fussy about the number of slashes (file:///path/to/file is best)
@@ -1356,8 +1162,8 @@
             byte[] eoln = "\r\n".getBytes(targetCharset);
 
             try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
-                for (int i = 0; i < uriList.size(); i++) {
-                    byte[] bytes = uriList.get(i).getBytes(targetCharset);
+                for (String uri : uriList) {
+                    byte[] bytes = uri.getBytes(targetCharset);
                     bos.write(bytes, 0, bytes.length);
                     bos.write(eoln, 0, eoln.length);
                 }
@@ -1433,42 +1239,35 @@
             return str;
         }
 
-
-        String ret_val = "";
         final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents);
 
         try {
-            ret_val = (String) AccessController.doPrivileged(new PrivilegedExceptionAction() {
-                    public Object run() {
-
-                        StringBuffer allowedFiles = new StringBuffer(str.length());
-                        String [] uriArray = str.split("(\\s)+");
-
-                        for (String fileName : uriArray)
+            return AccessController.doPrivileged((PrivilegedExceptionAction<String>) () -> {
+
+                StringBuilder allowedFiles = new StringBuilder(str.length());
+                String [] uriArray = str.split("(\\s)+");
+
+                for (String fileName : uriArray)
+                {
+                    File file = new File(fileName);
+                    if (file.exists() &&
+                        !(isFileInWebstartedCache(file) ||
+                        isForbiddenToRead(file, userProtectionDomain)))
+                    {
+                        if (0 != allowedFiles.length())
                         {
-                            File file = new File(fileName);
-                            if (file.exists() &&
-                                !(isFileInWebstartedCache(file) ||
-                                isForbiddenToRead(file, userProtectionDomain)))
-                            {
-
-                                if (0 != allowedFiles.length())
-                                {
-                                    allowedFiles.append("\\r\\n");
-                                }
-
-                                allowedFiles.append(fileName);
-                            }
+                            allowedFiles.append("\\r\\n");
                         }
 
-                        return allowedFiles.toString();
+                        allowedFiles.append(fileName);
                     }
-                });
+                }
+
+                return allowedFiles.toString();
+            });
         } catch (PrivilegedActionException pae) {
             throw new IOException(pae.getMessage(), pae);
         }
-
-        return ret_val;
     }
 
     private static ProtectionDomain getUserProtectionDomain(Transferable contents) {
@@ -1492,30 +1291,26 @@
     }
 
     private ArrayList<String> castToFiles(final List files,
-                                          final ProtectionDomain userProtectionDomain) throws IOException
-    {
-        final ArrayList<String> fileList = new ArrayList<String>();
+                                          final ProtectionDomain userProtectionDomain) throws IOException {
         try {
-            AccessController.doPrivileged(new PrivilegedExceptionAction() {
-                public Object run() throws IOException {
-                    for (Object fileObject : files)
+            return AccessController.doPrivileged((PrivilegedExceptionAction<ArrayList<String>>) () -> {
+                ArrayList<String> fileList = new ArrayList<>();
+                for (Object fileObject : files)
+                {
+                    File file = castToFile(fileObject);
+                    if (file != null &&
+                        (null == System.getSecurityManager() ||
+                        !(isFileInWebstartedCache(file) ||
+                        isForbiddenToRead(file, userProtectionDomain))))
                     {
-                        File file = castToFile(fileObject);
-                        if (file != null &&
-                            (null == System.getSecurityManager() ||
-                            !(isFileInWebstartedCache(file) ||
-                            isForbiddenToRead(file, userProtectionDomain))))
-                        {
-                            fileList.add(file.getCanonicalPath());
-                        }
+                        fileList.add(file.getCanonicalPath());
                     }
-                    return null;
                 }
+                return fileList;
             });
         } catch (PrivilegedActionException pae) {
             throw new IOException(pae.getMessage());
         }
-        return fileList;
     }
 
     // It is important do not use user's successors
@@ -1539,8 +1334,7 @@
         "deployment.javapi.cachedir"
     };
 
-    private final static ArrayList <File> deploymentCacheDirectoryList =
-            new ArrayList<File>();
+    private final static ArrayList <File> deploymentCacheDirectoryList = new ArrayList<>();
 
     private static boolean isFileInWebstartedCache(File f) {
 
@@ -1598,6 +1392,30 @@
             // Turn the list of Files into a List and return
             theObject = Arrays.asList(files);
 
+            // Source data is a URI list. Convert to DataFlavor.javaFileListFlavor
+            // where possible.
+        } else if (isURIListFormat(format)
+                    && DataFlavor.javaFileListFlavor.equals(flavor)) {
+
+            try (ByteArrayInputStream str = new ByteArrayInputStream(bytes))  {
+
+                URI uris[] = dragQueryURIs(str, format, localeTransferable);
+                if (uris == null) {
+                    return null;
+                }
+                List<File> files = new ArrayList<>();
+                for (URI uri : uris) {
+                    try {
+                        files.add(new File(uri));
+                    } catch (IllegalArgumentException illegalArg) {
+                        // When converting from URIs to less generic files,
+                        // common practice (Wine, SWT) seems to be to
+                        // silently drop the URIs that aren't local files.
+                    }
+                }
+                theObject = files;
+            }
+
             // Target data is a String. Strip terminating NUL bytes. Decode bytes
             // into characters. Search-and-replace EOLN.
         } else if (String.class.equals(flavor.getRepresentationClass()) &&
@@ -1627,7 +1445,7 @@
 
             // Target data is a char array. Recur to obtain String and convert to
             // char array.
-        } else if (charArrayClass.equals(flavor.getRepresentationClass())) {
+        } else if (char[].class.equals(flavor.getRepresentationClass())) {
             if (!(isFlavorCharsetTextType(flavor) && isTextFormat(format))) {
                 throw new IOException
                           ("cannot transfer non-text data as char array");
@@ -1655,7 +1473,7 @@
             // the raw bytes. For text flavors, convert to a String to strip
             // terminators and search-and-replace EOLN, then reencode according to
             // the requested flavor.
-        } else if (byteArrayClass.equals(flavor.getRepresentationClass())) {
+        } else if (byte[].class.equals(flavor.getRepresentationClass())) {
             if (isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
                 theObject = translateBytesToString(
                     bytes, format, localeTransferable
@@ -1728,7 +1546,7 @@
             if (uris == null) {
                 return null;
             }
-            ArrayList files = new ArrayList();
+            List<File> files = new ArrayList<>();
             for (URI uri : uris) {
                 try {
                     files.add(new File(uri));
@@ -1783,7 +1601,7 @@
 
             theObject = constructFlavoredObject(reader, flavor, Reader.class);
             // Target data is a byte array
-        } else if (byteArrayClass.equals(flavor.getRepresentationClass())) {
+        } else if (byte[].class.equals(flavor.getRepresentationClass())) {
             if(isFlavorCharsetTextType(flavor) && isTextFormat(format)) {
                 theObject = translateBytesToString(inputStreamToByteArray(str), format, localeTransferable)
                         .getBytes(DataTransferer.getTextCharset(flavor));
@@ -1853,47 +1671,34 @@
                                            Class clazz)
         throws IOException
     {
-        final Class dfrc = flavor.getRepresentationClass();
+        final Class<?> dfrc = flavor.getRepresentationClass();
 
         if (clazz.equals(dfrc)) {
             return arg; // simple case
         } else {
-            Constructor[] constructors = null;
+            Constructor[] constructors;
 
             try {
-                constructors = (Constructor[])
-                    AccessController.doPrivileged(new PrivilegedAction() {
-                            public Object run() {
-                                return dfrc.getConstructors();
-                            }
-                        });
+                constructors = AccessController.doPrivileged(
+                        (PrivilegedAction<Constructor[]>) dfrc::getConstructors);
             } catch (SecurityException se) {
                 throw new IOException(se.getMessage());
             }
 
-            Constructor constructor = null;
-
-            for (int j = 0; j < constructors.length; j++) {
-                if (!Modifier.isPublic(constructors[j].getModifiers())) {
-                    continue;
-                }
-
-                Class[] ptypes = constructors[j].getParameterTypes();
-
-                if (ptypes != null && ptypes.length == 1 &&
-                    clazz.equals(ptypes[0])) {
-                    constructor = constructors[j];
-                    break;
-                }
-            }
-
-            if (constructor == null) {
-                throw new IOException("can't find <init>(L"+ clazz +
-                                      ";)V for class: " + dfrc.getName());
-            }
+            Constructor constructor = Stream.of(constructors)
+                    .filter(c -> Modifier.isPublic(c.getModifiers()))
+                    .filter(c -> {
+                        Class[] ptypes = c.getParameterTypes();
+                        return ptypes != null
+                                && ptypes.length == 1
+                                && clazz.equals(ptypes[0]);
+                    })
+                    .findFirst()
+                    .orElseThrow(() ->
+                            new IOException("can't find <init>(L"+ clazz + ";)V for class: " + dfrc.getName()));
 
             try {
-                return constructor.newInstance(new Object[] { arg } );
+                return constructor.newInstance(arg);
             } catch (Exception e) {
                 throw new IOException(e.getMessage());
             }
@@ -1905,26 +1710,26 @@
      * can strip NUL terminators and perform EOLN search-and-replace.
      */
     public class ReencodingInputStream extends InputStream {
-        protected BufferedReader wrapped;
-        protected final char[] in = new char[2];
-        protected byte[] out;
-
-        protected CharsetEncoder encoder;
-        protected CharBuffer inBuf;
-        protected ByteBuffer outBuf;
-
-        protected char[] eoln;
-        protected int numTerminators;
-
-        protected boolean eos;
-        protected int index, limit;
+        BufferedReader wrapped;
+        final char[] in = new char[2];
+        byte[] out;
+
+        CharsetEncoder encoder;
+        CharBuffer inBuf;
+        ByteBuffer outBuf;
+
+        char[] eoln;
+        int numTerminators;
+
+        boolean eos;
+        int index, limit;
 
         public ReencodingInputStream(InputStream bytestream, long format,
                                      String targetEncoding,
                                      Transferable localeTransferable)
             throws IOException
         {
-            Long lFormat = Long.valueOf(format);
+            Long lFormat = format;
 
             String sourceEncoding = null;
             if (isLocaleDependentTextFormat(format) &&
@@ -1962,24 +1767,22 @@
                 out = new byte[(int)(encoder.maxBytesPerChar() * 2 + 0.5)];
                 inBuf = CharBuffer.wrap(in);
                 outBuf = ByteBuffer.wrap(out);
-            } catch (IllegalCharsetNameException e) {
-                throw new IOException(e.toString());
-            } catch (UnsupportedCharsetException e) {
-                throw new IOException(e.toString());
-            } catch (UnsupportedOperationException e) {
+            } catch (IllegalCharsetNameException
+                    | UnsupportedCharsetException
+                    | UnsupportedOperationException e) {
                 throw new IOException(e.toString());
             }
 
-            String sEoln = (String)nativeEOLNs.get(lFormat);
+            String sEoln = nativeEOLNs.get(lFormat);
             if (sEoln != null) {
                 eoln = sEoln.toCharArray();
             }
 
             // A hope and a prayer that this works generically. This will
             // definitely work on Win32.
-            Integer terminators = (Integer)nativeTerminators.get(lFormat);
+            Integer terminators = nativeTerminators.get(lFormat);
             if (terminators != null) {
-                numTerminators = terminators.intValue();
+                numTerminators = terminators;
             }
         }
 
@@ -2126,19 +1929,14 @@
         while (readerIterator.hasNext()) {
             ImageReader imageReader = (ImageReader)readerIterator.next();
             try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes)) {
-                ImageInputStream imageInputStream =
-                    ImageIO.createImageInputStream(bais);
-
-                try {
+                try (ImageInputStream imageInputStream = ImageIO.createImageInputStream(bais)) {
                     ImageReadParam param = imageReader.getDefaultReadParam();
                     imageReader.setInput(imageInputStream, true, true);
-                    BufferedImage bufferedImage =
-                        imageReader.read(imageReader.getMinIndex(), param);
+                    BufferedImage bufferedImage = imageReader.read(imageReader.getMinIndex(), param);
                     if (bufferedImage != null) {
                         return bufferedImage;
                     }
                 } finally {
-                    imageInputStream.close();
                     imageReader.dispose();
                 }
             } catch (IOException e) {
@@ -2227,7 +2025,7 @@
         }
     }
 
-    protected byte[] imageToStandardBytesImpl(RenderedImage renderedImage,
+    byte[] imageToStandardBytesImpl(RenderedImage renderedImage,
                                               String mimeType)
         throws IOException {
 
@@ -2248,14 +2046,10 @@
             }
 
             try {
-                ImageOutputStream imageOutputStream =
-                    ImageIO.createImageOutputStream(baos);
-                try {
+                try (ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(baos)) {
                     imageWriter.setOutput(imageOutputStream);
                     imageWriter.write(renderedImage);
                     imageOutputStream.flush();
-                } finally {
-                    imageOutputStream.close();
                 }
             } catch (IOException e) {
                 imageWriter.dispose();
@@ -2341,7 +2135,7 @@
          * that may contain client code.
          */
         if (isToolkitThread) try {
-            final Stack stack = new Stack();
+            final Stack<byte[]> stack = new Stack<>();
             final Runnable dataConverter = new Runnable() {
                 // Guard against multiple executions.
                 private boolean done = false;
@@ -2351,7 +2145,7 @@
                     }
                     byte[] data = null;
                     try {
-                        DataFlavor flavor = (DataFlavor)formatMap.get(Long.valueOf(format));
+                        DataFlavor flavor = (DataFlavor)formatMap.get(format);
                         if (flavor != null) {
                             data = translateTransferable(contents, flavor, format);
                         }
@@ -2388,12 +2182,11 @@
                 appContext.remove(DATA_CONVERTER_KEY);
             }
 
-            ret = (byte[])stack.pop();
+            ret = stack.pop();
         } finally {
             getToolkitThreadBlockedHandler().unlock();
         } else {
-            DataFlavor flavor = (DataFlavor)
-                formatMap.get(Long.valueOf(format));
+            DataFlavor flavor = (DataFlavor)formatMap.get(format);
             if (flavor != null) {
                 ret = translateTransferable(contents, flavor, format);
             }
@@ -2428,12 +2221,12 @@
      * The map keys are sorted according to the native formats preference
      * order.
      */
-    public static long[] keysToLongArray(SortedMap map) {
-        Set keySet = map.keySet();
+    public static long[] keysToLongArray(SortedMap<Long, ?> map) {
+        Set<Long> keySet = map.keySet();
         long[] retval = new long[keySet.size()];
         int i = 0;
-        for (Iterator iter = keySet.iterator(); iter.hasNext(); i++) {
-            retval[i] = ((Long)iter.next()).longValue();
+        for (Iterator<Long> iter = keySet.iterator(); iter.hasNext(); i++) {
+            retval[i] = iter.next();
         }
         return retval;
     }
@@ -2445,7 +2238,7 @@
     public static DataFlavor[] setToSortedDataFlavorArray(Set flavorsSet) {
         DataFlavor[] flavors = new DataFlavor[flavorsSet.size()];
         flavorsSet.toArray(flavors);
-        final Comparator comparator =
+        final Comparator<DataFlavor> comparator =
                 new DataFlavorComparator(IndexedComparator.SELECT_WORST);
         Arrays.sort(flavors, comparator);
         return flavors;
@@ -2474,8 +2267,8 @@
      * If there are no platform-specific mappings for this native, the method
      * returns an empty <code>List</code>.
      */
-    public List getPlatformMappingsForNative(String nat) {
-        return new ArrayList();
+    public List<DataFlavor> getPlatformMappingsForNative(String nat) {
+        return new ArrayList<>();
     }
 
     /**
@@ -2483,15 +2276,15 @@
      * If there are no platform-specific mappings for this flavor, the method
      * returns an empty <code>List</code>.
      */
-    public List getPlatformMappingsForFlavor(DataFlavor df) {
-        return new ArrayList();
+    public List<String> getPlatformMappingsForFlavor(DataFlavor df) {
+        return new ArrayList<>();
     }
 
     /**
      * A Comparator which includes a helper function for comparing two Objects
      * which are likely to be keys in the specified Map.
      */
-    public abstract static class IndexedComparator implements Comparator {
+    public abstract static class IndexedComparator<T> implements Comparator<T> {
 
         /**
          * The best Object (e.g., DataFlavor) will be the last in sequence.
@@ -2503,11 +2296,7 @@
          */
         public static final boolean SELECT_WORST = false;
 
-        protected final boolean order;
-
-        public IndexedComparator() {
-            this(SELECT_BEST);
-        }
+        final boolean order;
 
         public IndexedComparator(boolean order) {
             this.order = order;
@@ -2526,48 +2315,11 @@
          *             first object is mapped to a less, equal to, or greater
          *             index than the second.
          */
-        protected static int compareIndices(Map indexMap,
-                                            Object obj1, Object obj2,
-                                            Integer fallbackIndex) {
-            Integer index1 = (Integer)indexMap.get(obj1);
-            Integer index2 = (Integer)indexMap.get(obj2);
-
-            if (index1 == null) {
-                index1 = fallbackIndex;
-            }
-            if (index2 == null) {
-                index2 = fallbackIndex;
-            }
-
-            return index1.compareTo(index2);
-        }
-
-        /**
-         * Helper method to compare two objects by their Long indices in the
-         * given map. If the map doesn't contain an entry for either of the
-         * objects, the fallback index will be used for the object instead.
-         *
-         * @param indexMap the map which maps objects into Long indexes.
-         * @param obj1 the first object to be compared.
-         * @param obj2 the second object to be compared.
-         * @param fallbackIndex the Long to be used as a fallback index.
-         * @return a negative integer, zero, or a positive integer as the
-         *             first object is mapped to a less, equal to, or greater
-         *             index than the second.
-         */
-        protected static int compareLongs(Map indexMap,
-                                          Object obj1, Object obj2,
-                                          Long fallbackIndex) {
-            Long index1 = (Long)indexMap.get(obj1);
-            Long index2 = (Long)indexMap.get(obj2);
-
-            if (index1 == null) {
-                index1 = fallbackIndex;
-            }
-            if (index2 == null) {
-                index2 = fallbackIndex;
-            }
-
+        static <T> int compareIndices(Map<T, Integer> indexMap,
+                                      T obj1, T obj2,
+                                      Integer fallbackIndex) {
+            Integer index1 = indexMap.getOrDefault(obj1, fallbackIndex);
+            Integer index2 = indexMap.getOrDefault(obj2, fallbackIndex);
             return index1.compareTo(index2);
         }
     }
@@ -2579,45 +2331,37 @@
      * in alphabetical order, charsets are not automatically converted to their
      * canonical forms.
      */
-    public static class CharsetComparator extends IndexedComparator {
-        private static final Map charsets;
-        private static String defaultEncoding;
-
-        private static final Integer DEFAULT_CHARSET_INDEX = Integer.valueOf(2);
-        private static final Integer OTHER_CHARSET_INDEX = Integer.valueOf(1);
-        private static final Integer WORST_CHARSET_INDEX = Integer.valueOf(0);
-        private static final Integer UNSUPPORTED_CHARSET_INDEX =
-            Integer.valueOf(Integer.MIN_VALUE);
+    public static class CharsetComparator extends IndexedComparator<String> {
+        private static final Map<String, Integer> charsets;
+        private static final String defaultEncoding;
+
+        private static final Integer DEFAULT_CHARSET_INDEX = 2;
+        private static final Integer OTHER_CHARSET_INDEX = 1;
+        private static final Integer WORST_CHARSET_INDEX = 0;
+        private static final Integer UNSUPPORTED_CHARSET_INDEX = Integer.MIN_VALUE;
 
         private static final String UNSUPPORTED_CHARSET = "UNSUPPORTED";
 
         static {
-            HashMap charsetsMap = new HashMap(8, 1.0f);
+            Map<String, Integer> charsetsMap = new HashMap<>(8, 1.0f);
 
             // we prefer Unicode charsets
-            charsetsMap.put(canonicalName("UTF-16LE"), Integer.valueOf(4));
-            charsetsMap.put(canonicalName("UTF-16BE"), Integer.valueOf(5));
-            charsetsMap.put(canonicalName("UTF-8"), Integer.valueOf(6));
-            charsetsMap.put(canonicalName("UTF-16"), Integer.valueOf(7));
+            charsetsMap.put(canonicalName("UTF-16LE"), 4);
+            charsetsMap.put(canonicalName("UTF-16BE"), 5);
+            charsetsMap.put(canonicalName("UTF-8"), 6);
+            charsetsMap.put(canonicalName("UTF-16"), 7);
 
             // US-ASCII is the worst charset supported
             charsetsMap.put(canonicalName("US-ASCII"), WORST_CHARSET_INDEX);
 
-            String defEncoding = DataTransferer.canonicalName
-                (DataTransferer.getDefaultTextCharset());
-
-            if (charsetsMap.get(defaultEncoding) == null) {
-                charsetsMap.put(defaultEncoding, DEFAULT_CHARSET_INDEX);
-            }
+            defaultEncoding = DataTransferer.canonicalName(DataTransferer.getDefaultTextCharset());
+            charsetsMap.putIfAbsent(defaultEncoding, DEFAULT_CHARSET_INDEX);
+
             charsetsMap.put(UNSUPPORTED_CHARSET, UNSUPPORTED_CHARSET_INDEX);
 
             charsets = Collections.unmodifiableMap(charsetsMap);
         }
 
-        public CharsetComparator() {
-            this(SELECT_BEST);
-        }
-
         public CharsetComparator(boolean order) {
             super(order);
         }
@@ -2637,18 +2381,12 @@
          * @throws NullPointerException if either of the arguments is
          *         <code>null</code>.
          */
-        public int compare(Object obj1, Object obj2) {
-            String charset1 = null;
-            String charset2 = null;
+        public int compare(String obj1, String obj2) {
             if (order == SELECT_BEST) {
-                charset1 = (String)obj1;
-                charset2 = (String)obj2;
+                return compareCharsets(obj1, obj2);
             } else {
-                charset1 = (String)obj2;
-                charset2 = (String)obj1;
+                return compareCharsets(obj2, obj1);
             }
-
-            return compareCharsets(charset1, charset2);
         }
 
         /**
@@ -2674,7 +2412,7 @@
          *             first argument is worse, equal to, or better than the
          *             second.
          */
-        protected int compareCharsets(String charset1, String charset2) {
+        int compareCharsets(String charset1, String charset2) {
             charset1 = getEncoding(charset1);
             charset2 = getEncoding(charset2);
 
@@ -2704,7 +2442,7 @@
          * @param charset the charset.
          * @return an encoding for this charset.
          */
-        protected static String getEncoding(String charset) {
+        static String getEncoding(String charset) {
             if (charset == null) {
                 return null;
             } else if (!DataTransferer.isEncodingSupported(charset)) {
@@ -2732,131 +2470,108 @@
      * most descriptive one. For flavors which are otherwise equal, the
      * flavors' string representation are compared in the alphabetical order.
      */
-    public static class DataFlavorComparator extends IndexedComparator {
+    public static class DataFlavorComparator extends IndexedComparator<DataFlavor> {
 
         private final CharsetComparator charsetComparator;
 
-        private static final Map exactTypes;
-        private static final Map primaryTypes;
-        private static final Map nonTextRepresentations;
-        private static final Map textTypes;
-        private static final Map decodedTextRepresentations;
-        private static final Map encodedTextRepresentations;
-
-        private static final Integer UNKNOWN_OBJECT_LOSES =
-            Integer.valueOf(Integer.MIN_VALUE);
-        private static final Integer UNKNOWN_OBJECT_WINS =
-            Integer.valueOf(Integer.MAX_VALUE);
-
-        private static final Long UNKNOWN_OBJECT_LOSES_L =
-            Long.valueOf(Long.MIN_VALUE);
-        private static final Long UNKNOWN_OBJECT_WINS_L =
-            Long.valueOf(Long.MAX_VALUE);
+        private static final Map<String, Integer> exactTypes;
+        private static final Map<String, Integer> primaryTypes;
+        private static final Map<Class<?>, Integer> nonTextRepresentations;
+        private static final Map<String, Integer> textTypes;
+        private static final Map<Class<?>, Integer> decodedTextRepresentations;
+        private static final Map<Class<?>, Integer> encodedTextRepresentations;
+
+        private static final Integer UNKNOWN_OBJECT_LOSES = Integer.MIN_VALUE;
+        private static final Integer UNKNOWN_OBJECT_WINS = Integer.MAX_VALUE;
 
         static {
             {
-                HashMap exactTypesMap = new HashMap(4, 1.0f);
+                Map<String, Integer> exactTypesMap = new HashMap<>(4, 1.0f);
 
                 // application/x-java-* MIME types
-                exactTypesMap.put("application/x-java-file-list",
-                                  Integer.valueOf(0));
-                exactTypesMap.put("application/x-java-serialized-object",
-                                  Integer.valueOf(1));
-                exactTypesMap.put("application/x-java-jvm-local-objectref",
-                                  Integer.valueOf(2));
-                exactTypesMap.put("application/x-java-remote-object",
-                                  Integer.valueOf(3));
+                exactTypesMap.put("application/x-java-file-list", 0);
+                exactTypesMap.put("application/x-java-serialized-object", 1);
+                exactTypesMap.put("application/x-java-jvm-local-objectref", 2);
+                exactTypesMap.put("application/x-java-remote-object", 3);
 
                 exactTypes = Collections.unmodifiableMap(exactTypesMap);
             }
 
             {
-                HashMap primaryTypesMap = new HashMap(1, 1.0f);
-
-                primaryTypesMap.put("application", Integer.valueOf(0));
+                Map<String, Integer> primaryTypesMap = new HashMap<>(1, 1.0f);
+
+                primaryTypesMap.put("application", 0);
 
                 primaryTypes = Collections.unmodifiableMap(primaryTypesMap);
             }
 
             {
-                HashMap nonTextRepresentationsMap = new HashMap(3, 1.0f);
-
-                nonTextRepresentationsMap.put(java.io.InputStream.class,
-                                              Integer.valueOf(0));
-                nonTextRepresentationsMap.put(java.io.Serializable.class,
-                                              Integer.valueOf(1));
+                Map<Class<?>, Integer> nonTextRepresentationsMap = new HashMap<>(3, 1.0f);
+
+                nonTextRepresentationsMap.put(java.io.InputStream.class, 0);
+                nonTextRepresentationsMap.put(java.io.Serializable.class, 1);
 
                 Class<?> remoteClass = RMI.remoteClass();
                 if (remoteClass != null) {
-                    nonTextRepresentationsMap.put(remoteClass,
-                                                  Integer.valueOf(2));
+                    nonTextRepresentationsMap.put(remoteClass, 2);
                 }
 
-                nonTextRepresentations =
-                    Collections.unmodifiableMap(nonTextRepresentationsMap);
+                nonTextRepresentations = Collections.unmodifiableMap(nonTextRepresentationsMap);
             }
 
             {
-                HashMap textTypesMap = new HashMap(16, 1.0f);
+                Map<String, Integer> textTypesMap = new HashMap<>(16, 1.0f);
 
                 // plain text
-                textTypesMap.put("text/plain", Integer.valueOf(0));
+                textTypesMap.put("text/plain", 0);
 
                 // stringFlavor
-                textTypesMap.put("application/x-java-serialized-object",
-                                Integer.valueOf(1));
+                textTypesMap.put("application/x-java-serialized-object", 1);
 
                 // misc
-                textTypesMap.put("text/calendar", Integer.valueOf(2));
-                textTypesMap.put("text/css", Integer.valueOf(3));
-                textTypesMap.put("text/directory", Integer.valueOf(4));
-                textTypesMap.put("text/parityfec", Integer.valueOf(5));
-                textTypesMap.put("text/rfc822-headers", Integer.valueOf(6));
-                textTypesMap.put("text/t140", Integer.valueOf(7));
-                textTypesMap.put("text/tab-separated-values", Integer.valueOf(8));
-                textTypesMap.put("text/uri-list", Integer.valueOf(9));
+                textTypesMap.put("text/calendar", 2);
+                textTypesMap.put("text/css", 3);
+                textTypesMap.put("text/directory", 4);
+                textTypesMap.put("text/parityfec", 5);
+                textTypesMap.put("text/rfc822-headers", 6);
+                textTypesMap.put("text/t140", 7);
+                textTypesMap.put("text/tab-separated-values", 8);
+                textTypesMap.put("text/uri-list", 9);
 
                 // enriched
-                textTypesMap.put("text/richtext", Integer.valueOf(10));
-                textTypesMap.put("text/enriched", Integer.valueOf(11));
-                textTypesMap.put("text/rtf", Integer.valueOf(12));
+                textTypesMap.put("text/richtext", 10);
+                textTypesMap.put("text/enriched", 11);
+                textTypesMap.put("text/rtf", 12);
 
                 // markup
-                textTypesMap.put("text/html", Integer.valueOf(13));
-                textTypesMap.put("text/xml", Integer.valueOf(14));
-                textTypesMap.put("text/sgml", Integer.valueOf(15));
+                textTypesMap.put("text/html", 13);
+                textTypesMap.put("text/xml", 14);
+                textTypesMap.put("text/sgml", 15);
 
                 textTypes = Collections.unmodifiableMap(textTypesMap);
             }
 
             {
-                HashMap decodedTextRepresentationsMap = new HashMap(4, 1.0f);
-
-                decodedTextRepresentationsMap.put
-                    (DataTransferer.charArrayClass, Integer.valueOf(0));
-                decodedTextRepresentationsMap.put
-                    (java.nio.CharBuffer.class, Integer.valueOf(1));
-                decodedTextRepresentationsMap.put
-                    (java.lang.String.class, Integer.valueOf(2));
-                decodedTextRepresentationsMap.put
-                    (java.io.Reader.class, Integer.valueOf(3));
+                Map<Class<?>, Integer> decodedTextRepresentationsMap = new HashMap<>(4, 1.0f);
+
+                decodedTextRepresentationsMap.put(char[].class, 0);
+                decodedTextRepresentationsMap.put(CharBuffer.class, 1);
+                decodedTextRepresentationsMap.put(String.class, 2);
+                decodedTextRepresentationsMap.put(Reader.class, 3);
 
                 decodedTextRepresentations =
-                    Collections.unmodifiableMap(decodedTextRepresentationsMap);
+                        Collections.unmodifiableMap(decodedTextRepresentationsMap);
             }
 
             {
-                HashMap encodedTextRepresentationsMap = new HashMap(3, 1.0f);
-
-                encodedTextRepresentationsMap.put
-                    (DataTransferer.byteArrayClass, Integer.valueOf(0));
-                encodedTextRepresentationsMap.put
-                    (java.nio.ByteBuffer.class, Integer.valueOf(1));
-                encodedTextRepresentationsMap.put
-                    (java.io.InputStream.class, Integer.valueOf(2));
+                Map<Class<?>, Integer> encodedTextRepresentationsMap = new HashMap<>(3, 1.0f);
+
+                encodedTextRepresentationsMap.put(byte[].class, 0);
+                encodedTextRepresentationsMap.put(ByteBuffer.class, 1);
+                encodedTextRepresentationsMap.put(InputStream.class, 2);
 
                 encodedTextRepresentations =
-                    Collections.unmodifiableMap(encodedTextRepresentationsMap);
+                        Collections.unmodifiableMap(encodedTextRepresentationsMap);
             }
         }
 
@@ -2870,16 +2585,9 @@
             charsetComparator = new CharsetComparator(order);
         }
 
-        public int compare(Object obj1, Object obj2) {
-            DataFlavor flavor1 = null;
-            DataFlavor flavor2 = null;
-            if (order == SELECT_BEST) {
-                flavor1 = (DataFlavor)obj1;
-                flavor2 = (DataFlavor)obj2;
-            } else {
-                flavor1 = (DataFlavor)obj2;
-                flavor2 = (DataFlavor)obj1;
-            }
+        public int compare(DataFlavor obj1, DataFlavor obj2) {
+            DataFlavor flavor1 = order == SELECT_BEST ? obj1 : obj2;
+            DataFlavor flavor2 = order == SELECT_BEST ? obj2 : obj1;
 
             if (flavor1.equals(flavor2)) {
                 return 0;
@@ -2982,22 +2690,16 @@
      * reverse index-based order: an object A is greater than an object B if and
      * only if A is less than B with the direct index-based order.
      */
-    public static class IndexOrderComparator extends IndexedComparator {
-        private final Map indexMap;
-        private static final Integer FALLBACK_INDEX =
-            Integer.valueOf(Integer.MIN_VALUE);
-
-        public IndexOrderComparator(Map indexMap) {
-            super(SELECT_BEST);
-            this.indexMap = indexMap;
-        }
-
-        public IndexOrderComparator(Map indexMap, boolean order) {
+    public static class IndexOrderComparator extends IndexedComparator<Long> {
+        private final Map<Long, Integer> indexMap;
+        private static final Integer FALLBACK_INDEX = Integer.MIN_VALUE;
+
+        public IndexOrderComparator(Map<Long, Integer> indexMap, boolean order) {
             super(order);
             this.indexMap = indexMap;
         }
 
-        public int compare(Object obj1, Object obj2) {
+        public int compare(Long obj1, Long obj2) {
             if (order == SELECT_WORST) {
                 return -compareIndices(indexMap, obj1, obj2, FALLBACK_INDEX);
             } else {
@@ -3047,7 +2749,7 @@
          * Returns {@code true} if the given class is java.rmi.Remote.
          */
         static boolean isRemote(Class<?> c) {
-            return (remoteClass == null) ? null : remoteClass.isAssignableFrom(c);
+            return (remoteClass == null) ? false : remoteClass.isAssignableFrom(c);
         }
 
         /**
@@ -3064,9 +2766,7 @@
         static Object newMarshalledObject(Object obj) throws IOException {
             try {
                 return marshallCtor.newInstance(obj);
-            } catch (InstantiationException x) {
-                throw new AssertionError(x);
-            } catch (IllegalAccessException x) {
+            } catch (InstantiationException | IllegalAccessException x) {
                 throw new AssertionError(x);
             } catch (InvocationTargetException  x) {
                 Throwable cause = x.getCause();
--- a/jdk/src/share/classes/sun/awt/datatransfer/SunClipboard.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/awt/datatransfer/SunClipboard.java	Wed Jul 05 19:33:51 2017 +0200
@@ -217,7 +217,7 @@
             openClipboard(null);
 
             long[] formats = getClipboardFormats();
-            Long lFormat = (Long)DataTransferer.getInstance().
+            Long lFormat = DataTransferer.getInstance().
                     getFlavorsForFormats(formats, flavorMap).get(flavor);
 
             if (lFormat == null) {
--- a/jdk/src/share/classes/sun/awt/dnd/SunDropTargetContextPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/awt/dnd/SunDropTargetContextPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -627,14 +627,14 @@
         if (dropOperation == DnDConstants.ACTION_NONE)
             throw new IllegalArgumentException("invalid acceptDrop() action");
 
-        if (dropStatus != STATUS_WAIT) {
+        if (dropStatus == STATUS_WAIT || dropStatus == STATUS_ACCEPT) {
+            currentDA = currentA = mapOperation(dropOperation & currentSA);
+
+            dropStatus   = STATUS_ACCEPT;
+            dropComplete = false;
+        } else {
             throw new InvalidDnDOperationException("invalid acceptDrop()");
         }
-
-        currentDA = currentA = mapOperation(dropOperation & currentSA);
-
-        dropStatus   = STATUS_ACCEPT;
-        dropComplete = false;
     }
 
     /**
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/awt/image/MultiResolutionBufferedImage.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.awt.image;
+
+import java.awt.Image;
+import java.awt.Graphics;
+import java.awt.image.BufferedImage;
+import java.util.Arrays;
+import java.util.List;
+import java.util.function.Function;
+
+public class MultiResolutionBufferedImage extends BufferedImage
+        implements MultiResolutionImage {
+
+    Image[] resolutionVariants;
+    int baseIndex;
+
+    public MultiResolutionBufferedImage(int imageType, int baseIndex, Image... images) {
+        super(images[baseIndex].getWidth(null), images[baseIndex].getHeight(null),
+                imageType);
+        this.baseIndex = baseIndex;
+        this.resolutionVariants = images;
+        Graphics g = getGraphics();
+        g.drawImage(images[baseIndex], 0, 0, null);
+        g.dispose();
+        images[baseIndex] = this;
+    }
+
+    @Override
+    public Image getResolutionVariant(int width, int height) {
+        for (Image image : resolutionVariants) {
+            if (width <= image.getWidth(null) && height <= image.getHeight(null)) {
+                return image;
+            }
+        }
+        return this;
+    }
+
+    @Override
+    public List<Image> getResolutionVariants() {
+        return Arrays.asList(resolutionVariants);
+    }
+
+    public MultiResolutionBufferedImage map(Function<Image, Image> mapper) {
+        return new MultiResolutionBufferedImage(getType(), baseIndex,
+                Arrays.stream(resolutionVariants).map(mapper)
+                        .toArray(length -> new Image[length]));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/awt/image/MultiResolutionImage.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,83 @@
+/*
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.awt.image;
+
+import java.awt.Image;
+import java.util.List;
+
+/**
+ * This interface is designed to provide a set of images at various resolutions.
+ *
+ * The <code>MultiResolutionImage</code> interface should be implemented by any
+ * class whose instances are intended to provide image resolution variants
+ * according to the given image width and height.
+ *
+ * For example,
+ * <pre>
+ * {@code
+ *  public class ScaledImage extends BufferedImage
+ *         implements MultiResolutionImage {
+ *
+ *    @Override
+ *    public Image getResolutionVariant(int width, int height) {
+ *      return ((width <= getWidth() && height <= getHeight()))
+ *             ? this : highResolutionImage;
+ *    }
+ *
+ *    @Override
+ *    public List<Image> getResolutionVariants() {
+ *        return Arrays.asList(this, highResolutionImage);
+ *    }
+ *  }
+ * }</pre>
+ *
+ * It is recommended to cache image variants for performance reasons.
+ *
+ * <b>WARNING</b>: This class is an implementation detail. This API may change
+ * between update release, and it may even be removed or be moved in some other
+ * package(s)/class(es).
+ */
+public interface MultiResolutionImage {
+
+    /**
+     * Provides an image with necessary resolution which best fits to the given
+     * image width and height.
+     *
+     * @param width the desired image resolution width.
+     * @param height the desired image resolution height.
+     * @return image resolution variant.
+     *
+     * @since JDK1.8
+     */
+    public Image getResolutionVariant(int width, int height);
+
+    /**
+     * Gets list of all resolution variants including the base image
+     *
+     * @return list of resolution variants.
+     * @since JDK1.8
+     */
+    public List<Image> getResolutionVariants();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/awt/image/MultiResolutionToolkitImage.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,104 @@
+/*
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.awt.image;
+
+import java.awt.Image;
+import java.awt.image.ImageObserver;
+import java.util.Arrays;
+import java.util.List;
+import sun.misc.SoftCache;
+
+public class MultiResolutionToolkitImage extends ToolkitImage implements MultiResolutionImage {
+
+    Image resolutionVariant;
+
+    public MultiResolutionToolkitImage(Image lowResolutionImage, Image resolutionVariant) {
+        super(lowResolutionImage.getSource());
+        this.resolutionVariant = resolutionVariant;
+    }
+
+    @Override
+    public Image getResolutionVariant(int width, int height) {
+        return ((width <= getWidth() && height <= getHeight()))
+                ? this : resolutionVariant;
+    }
+
+    public Image getResolutionVariant() {
+        return resolutionVariant;
+    }
+
+    @Override
+    public List<Image> getResolutionVariants() {
+        return Arrays.<Image>asList(this, resolutionVariant);
+    }
+
+    private static final int BITS_INFO = ImageObserver.SOMEBITS
+            | ImageObserver.FRAMEBITS | ImageObserver.ALLBITS;
+
+    private static class ObserverCache {
+
+        static final SoftCache INSTANCE = new SoftCache();
+    }
+
+    public static ImageObserver getResolutionVariantObserver(
+            final Image image, final ImageObserver observer,
+            final int imgWidth, final int imgHeight,
+            final int rvWidth, final int rvHeight) {
+
+        if (observer == null) {
+            return null;
+        }
+
+        synchronized (ObserverCache.INSTANCE) {
+            ImageObserver o = (ImageObserver) ObserverCache.INSTANCE.get(image);
+
+            if (o == null) {
+
+                o = (Image resolutionVariant, int flags,
+                        int x, int y, int width, int height) -> {
+
+                            if ((flags & (ImageObserver.WIDTH | BITS_INFO)) != 0) {
+                                width = (width + 1) / 2;
+                            }
+
+                            if ((flags & (ImageObserver.HEIGHT | BITS_INFO)) != 0) {
+                                height = (height + 1) / 2;
+                            }
+
+                            if ((flags & BITS_INFO) != 0) {
+                                x /= 2;
+                                y /= 2;
+                            }
+
+                            return observer.imageUpdate(
+                                    image, flags, x, y, width, height);
+                        };
+
+                ObserverCache.INSTANCE.put(image, o);
+            }
+            return o;
+        }
+    }
+}
--- a/jdk/src/share/classes/sun/font/AttributeValues.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/AttributeValues.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -410,7 +410,7 @@
     }
 
     public Hashtable<Object, Object> toSerializableHashtable() {
-        Hashtable ht = new Hashtable();
+        Hashtable<Object, Object> ht = new Hashtable<>();
         int hashkey = defined;
         for (int m = defined, i = 0; m != 0; ++i) {
             EAttribute ea = EAttribute.atts[i];
@@ -798,7 +798,7 @@
                 hl = (InputMethodHighlight)((Annotation)imHighlight).getValue();
             }
 
-            Map imStyles = hl.getStyle();
+            Map<TextAttribute, ?> imStyles = hl.getStyle();
             if (imStyles == null) {
                 Toolkit tk = Toolkit.getDefaultToolkit();
                 imStyles = tk.mapInputMethodHighlight(hl);
@@ -812,6 +812,7 @@
         return this;
     }
 
+    @SuppressWarnings("unchecked")
     public static AffineTransform getBaselineTransform(Map<?, ?> map) {
         if (map != null) {
             AttributeValues av = null;
@@ -828,6 +829,7 @@
         return null;
     }
 
+    @SuppressWarnings("unchecked")
     public static AffineTransform getCharTransform(Map<?, ?> map) {
         if (map != null) {
             AttributeValues av = null;
--- a/jdk/src/share/classes/sun/font/CompositeFont.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/CompositeFont.java	Wed Jul 05 19:33:51 2017 +0200
@@ -447,8 +447,7 @@
     }
 
     public String toString() {
-        String ls = java.security.AccessController.doPrivileged(
-                new sun.security.action.GetPropertyAction("line.separator"));
+        String ls = System.lineSeparator();
         String componentsStr = "";
         for (int i=0; i<numSlots; i++) {
             componentsStr += "    Slot["+i+"]="+getSlotFont(i)+ls;
--- a/jdk/src/share/classes/sun/font/CreatedFontTracker.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/CreatedFontTracker.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -113,7 +113,7 @@
             if (t == null) {
                 // Add a shutdown hook to remove the temp file.
                 java.security.AccessController.doPrivileged(
-                   new java.security.PrivilegedAction() {
+                   new java.security.PrivilegedAction<Object>() {
                       public Object run() {
                           /* The thread must be a member of a thread group
                            * which will not get GCed before VM exit.
--- a/jdk/src/share/classes/sun/font/Decoration.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/Decoration.java	Wed Jul 05 19:33:51 2017 +0200
@@ -46,6 +46,7 @@
 import java.awt.geom.Line2D;
 import java.awt.geom.Rectangle2D;
 import java.awt.geom.GeneralPath;
+import java.text.AttributedCharacterIterator.Attribute;
 
 import static sun.font.AttributeValues.*;
 import static sun.font.EAttribute.*;
@@ -107,7 +108,7 @@
      * Return a Decoration appropriate for the the given Map.
      * @param attributes the Map used to determine the Decoration
      */
-    public static Decoration getDecoration(Map attributes) {
+    public static Decoration getDecoration(Map<? extends Attribute, ?> attributes) {
         if (attributes == null) {
             return PLAIN;
         }
--- a/jdk/src/share/classes/sun/font/FileFont.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/FileFont.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -159,7 +159,7 @@
         SunFontManager fm = SunFontManager.getInstance();
         fm.deRegisterBadFont(this);
 
-        for (Reference strikeRef : strikeCache.values()) {
+        for (Reference<FontStrike> strikeRef : strikeCache.values()) {
             if (strikeRef != null) {
                 /* NB we know these are all FileFontStrike instances
                  * because the cache is on this FileFont
@@ -261,7 +261,7 @@
 
         public void dispose() {
             java.security.AccessController.doPrivileged(
-                 new java.security.PrivilegedAction() {
+                 new java.security.PrivilegedAction<Object>() {
                       public Object run() {
                           if (fontFile != null) {
                               try {
--- a/jdk/src/share/classes/sun/font/Font2D.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/Font2D.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,8 +91,8 @@
      * the map will have fewer entries, and there's no need to try to
      * make the Font2D part of the key.
      */
-    protected ConcurrentHashMap<FontStrikeDesc, Reference>
-        strikeCache = new ConcurrentHashMap<FontStrikeDesc, Reference>();
+    protected ConcurrentHashMap<FontStrikeDesc, Reference<FontStrike>>
+        strikeCache = new ConcurrentHashMap<>();
 
     /* Store the last Strike in a Reference object.
      * Similarly to the strike that was stored on a C++ font object,
@@ -105,7 +105,7 @@
      * This pre-supposes that a FontStrike is a shareable object, which
      * it should.
      */
-    protected Reference lastFontStrike = new SoftReference(null);
+    protected Reference<FontStrike> lastFontStrike = new SoftReference<>(null);
 
     /*
      * POSSIBLE OPTIMISATION:
@@ -195,7 +195,7 @@
      * strike.
      */
     public FontStrike getStrike(Font font) {
-        FontStrike strike = (FontStrike)lastFontStrike.get();
+        FontStrike strike = lastFontStrike.get();
         if (strike != null) {
             return strike;
         } else {
@@ -307,17 +307,17 @@
          * collected, then we create a new strike, put it in the map and
          * set it to be the last strike.
          */
-        FontStrike strike = (FontStrike)lastFontStrike.get();
+        FontStrike strike = lastFontStrike.get();
         if (strike != null && desc.equals(strike.desc)) {
             //strike.lastlookupTime = System.currentTimeMillis();
             return strike;
         } else {
-            Reference strikeRef = strikeCache.get(desc);
+            Reference<FontStrike> strikeRef = strikeCache.get(desc);
             if (strikeRef != null) {
-                strike = (FontStrike)strikeRef.get();
+                strike = strikeRef.get();
                 if (strike != null) {
                     //strike.lastlookupTime = System.currentTimeMillis();
-                    lastFontStrike = new SoftReference(strike);
+                    lastFontStrike = new SoftReference<>(strike);
                     StrikeCache.refStrike(strike);
                     return strike;
                 }
@@ -360,14 +360,14 @@
             }
             strikeCache.put(desc, strikeRef);
             //strike.lastlookupTime = System.currentTimeMillis();
-            lastFontStrike = new SoftReference(strike);
+            lastFontStrike = new SoftReference<>(strike);
             StrikeCache.refStrike(strike);
             return strike;
         }
     }
 
     void removeFromCache(FontStrikeDesc desc) {
-        Reference ref = strikeCache.get(desc);
+        Reference<FontStrike> ref = strikeCache.get(desc);
         if (ref != null) {
             Object o = ref.get();
             if (o == null) {
--- a/jdk/src/share/classes/sun/font/FontDesignMetrics.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/FontDesignMetrics.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,10 +170,10 @@
      * Also we put the references on a queue so that if they do get nulled
      * out we can clear the keys from the table.
      */
-    private static class KeyReference extends SoftReference
+    private static class KeyReference extends SoftReference<Object>
         implements DisposerRecord, Disposer.PollDisposable {
 
-        static ReferenceQueue queue = Disposer.getQueue();
+        static ReferenceQueue<Object> queue = Disposer.getQueue();
 
         Object key;
 
--- a/jdk/src/share/classes/sun/font/FontFamily.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/FontFamily.java	Wed Jul 05 19:33:51 2017 +0200
@@ -25,6 +25,7 @@
 
 package sun.font;
 
+import java.io.File;
 import java.awt.Font;
 import java.util.HashMap;
 import java.util.concurrent.ConcurrentHashMap;
@@ -105,8 +106,39 @@
         return familyRank;
     }
 
+    private boolean isFromSameSource(Font2D font) {
+        if (!(font instanceof FileFont)) {
+            return false;
+        }
+
+        FileFont existingFont = null;
+        if (plain instanceof FileFont) {
+            existingFont = (FileFont)plain;
+        } else if (bold instanceof FileFont) {
+            existingFont = (FileFont)bold;
+        } else if (italic instanceof FileFont) {
+             existingFont = (FileFont)italic;
+        } else if (bolditalic instanceof FileFont) {
+             existingFont = (FileFont)bolditalic;
+        }
+        // A family isn't created until there's a font.
+        // So if we didn't find a file font it means this
+        // isn't a file-based family.
+        if (existingFont == null) {
+            return false;
+        }
+        File existDir = (new File(existingFont.platName)).getParentFile();
+
+        FileFont newFont = (FileFont)font;
+        File newDir = (new File(newFont.platName)).getParentFile();
+        return java.util.Objects.equals(newDir, existDir);
+    }
+
     public void setFont(Font2D font, int style) {
-        if (font.getRank() > familyRank) {
+        /* Allow a lower-rank font only if its a file font
+         * from the exact same source as any previous font.
+         */
+        if ((font.getRank() > familyRank) && !isFromSameSource(font)) {
             if (FontUtilities.isLogging()) {
                 FontUtilities.getLogger()
                                   .warning("Rejecting adding " + font +
--- a/jdk/src/share/classes/sun/font/FontManagerFactory.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/FontManagerFactory.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -71,7 +71,7 @@
             return instance;
         }
 
-        AccessController.doPrivileged(new PrivilegedAction() {
+        AccessController.doPrivileged(new PrivilegedAction<Object>() {
 
             public Object run() {
                 try {
@@ -79,7 +79,7 @@
                             System.getProperty("sun.font.fontmanager",
                                                DEFAULT_CLASS);
                     ClassLoader cl = ClassLoader.getSystemClassLoader();
-                    Class fmClass = Class.forName(fmClassName, true, cl);
+                    Class<?> fmClass = Class.forName(fmClassName, true, cl);
                     instance = (FontManager) fmClass.newInstance();
                 } catch (ClassNotFoundException |
                          InstantiationException |
--- a/jdk/src/share/classes/sun/font/FontManagerNativeLibrary.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/FontManagerNativeLibrary.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +30,7 @@
 public class FontManagerNativeLibrary {
     static {
         java.security.AccessController.doPrivileged(
-                                    new java.security.PrivilegedAction() {
+                                    new java.security.PrivilegedAction<Object>() {
             public Object run() {
                /* REMIND do we really have to load awt here? */
                System.loadLibrary("awt");
--- a/jdk/src/share/classes/sun/font/FontResolver.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/FontResolver.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,6 +33,7 @@
 import java.awt.Font;
 import java.awt.GraphicsEnvironment;
 import java.awt.font.TextAttribute;
+import java.text.AttributedCharacterIterator;
 import java.util.ArrayList;
 import java.util.Map;
 import sun.text.CodePointIterator;
@@ -222,7 +223,8 @@
      *        is Font.PLAIN
      * @see #getFontIndex
      */
-    public Font getFont(int index, Map attributes) {
+    public Font getFont(int index,
+                        Map<? extends AttributedCharacterIterator.Attribute, ?> attributes) {
         Font font = defaultFont;
 
         if (index >= 2) {
--- a/jdk/src/share/classes/sun/font/FontScaler.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/FontScaler.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,23 +82,24 @@
 public abstract class FontScaler implements DisposerRecord {
 
     private static FontScaler nullScaler = null;
-    private static Constructor<FontScaler> scalerConstructor = null;
+    private static Constructor<? extends FontScaler> scalerConstructor = null;
 
     //Find preferred font scaler
     //
     //NB: we can allow property based preferences
     //   (theoretically logic can be font type specific)
     static {
-        Class scalerClass = null;
-        Class arglst[] = new Class[] {Font2D.class, int.class,
+        Class<? extends FontScaler> scalerClass = null;
+        Class<?>[] arglst = new Class<?>[] {Font2D.class, int.class,
         boolean.class, int.class};
 
         try {
-            if (FontUtilities.isOpenJDK) {
-                scalerClass = Class.forName("sun.font.FreetypeFontScaler");
-            } else {
-                scalerClass = Class.forName("sun.font.T2KFontScaler");
-            }
+            @SuppressWarnings("unchecked")
+            Class<? extends FontScaler> tmp = (Class<? extends FontScaler>)
+                (FontUtilities.isOpenJDK ?
+                 Class.forName("sun.font.FreetypeFontScaler") :
+                 Class.forName("sun.font.T2KFontScaler"));
+            scalerClass = tmp;
         } catch (ClassNotFoundException e) {
                 scalerClass = NullFontScaler.class;
         }
--- a/jdk/src/share/classes/sun/font/FontUtilities.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/FontUtilities.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -71,7 +71,7 @@
     // This static initializer block figures out the OS constants.
     static {
 
-        AccessController.doPrivileged(new PrivilegedAction () {
+        AccessController.doPrivileged(new PrivilegedAction<Object>() {
             public Object run() {
                 String osName = System.getProperty("os.name", "unknownOS");
                 isSolaris = osName.startsWith("SunOS");
@@ -391,7 +391,7 @@
      */
     private static volatile
         SoftReference<ConcurrentHashMap<PhysicalFont, CompositeFont>>
-        compMapRef = new SoftReference(null);
+        compMapRef = new SoftReference<>(null);
 
     public static FontUIResource getCompositeFontUIResource(Font font) {
 
@@ -421,7 +421,7 @@
         ConcurrentHashMap<PhysicalFont, CompositeFont> compMap = compMapRef.get();
         if (compMap == null) { // Its been collected.
             compMap = new ConcurrentHashMap<PhysicalFont, CompositeFont>();
-            compMapRef = new SoftReference(compMap);
+            compMapRef = new SoftReference<>(compMap);
         }
         CompositeFont compFont = compMap.get(physicalFont);
         if (compFont == null) {
--- a/jdk/src/share/classes/sun/font/FreetypeFontScaler.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/FreetypeFontScaler.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +50,7 @@
         initIDs(FreetypeFontScaler.class);
     }
 
-    private static native void initIDs(Class FFS);
+    private static native void initIDs(Class<?> FFS);
 
     private void invalidateScaler() throws FontScalerException {
         nativeScaler = 0;
@@ -69,7 +69,7 @@
                                         indexInCollection,
                                         supportsCJK,
                                         filesize);
-        this.font = new WeakReference(font);
+        this.font = new WeakReference<>(font);
     }
 
     synchronized StrikeMetrics getFontMetrics(long pScalerContext)
--- a/jdk/src/share/classes/sun/font/GlyphLayout.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/GlyphLayout.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +92,7 @@
     private ScriptRun _scriptRuns;     // iterator over script runs
     private FontRunIterator _fontRuns; // iterator over physical fonts in a composite
     private int _ercount;
-    private ArrayList _erecords;
+    private ArrayList<EngineRecord> _erecords;
     private Point2D.Float _pt;
     private FontStrikeDesc _sd;
     private float[] _mat;
@@ -457,7 +457,7 @@
         //        _sd.init(dtx, gtx, font.getStyle(), frc.isAntiAliased(), frc.usesFractionalMetrics());
         _sd = txinfo.sd;
         for (;ix != stop; ix += dir) {
-            EngineRecord er = (EngineRecord)_erecords.get(ix);
+            EngineRecord er = _erecords.get(ix);
             for (;;) {
                 try {
                     er.layout();
@@ -505,7 +505,7 @@
         this._textRecord = new TextRecord();
         this._scriptRuns = new ScriptRun();
         this._fontRuns = new FontRunIterator();
-        this._erecords = new ArrayList(10);
+        this._erecords = new ArrayList<>(10);
         this._pt = new Point2D.Float();
         this._sd = new FontStrikeDesc();
         this._mat = new float[4];
@@ -523,7 +523,7 @@
             er = new EngineRecord();
             _erecords.add(er);
         } else {
-            er = (EngineRecord)_erecords.get(_ercount);
+            er = _erecords.get(_ercount);
         }
         er.init(start, limit, font, script, lang, gmask);
         ++_ercount;
--- a/jdk/src/share/classes/sun/font/StandardGlyphVector.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/StandardGlyphVector.java	Wed Jul 05 19:33:51 2017 +0200
@@ -153,7 +153,7 @@
     private AffineTransform invdtx; // inverse of dtx or null if dtx is identity
     private AffineTransform frctx; // font render context transform, wish we could just share it
     private Font2D font2D;         // basic strike-independent stuff
-    private SoftReference fsref;   // font strike reference for glyphs with no per-glyph transform
+    private SoftReference<GlyphStrike> fsref;   // font strike reference for glyphs with no per-glyph transform
 
     /////////////////////////////
     // Constructors and Factory methods
@@ -526,9 +526,9 @@
         }
 
         Shape[] lbcache;
-        if (lbcacheRef == null || (lbcache = (Shape[])lbcacheRef.get()) == null) {
+        if (lbcacheRef == null || (lbcache = lbcacheRef.get()) == null) {
             lbcache = new Shape[glyphs.length];
-            lbcacheRef = new SoftReference(lbcache);
+            lbcacheRef = new SoftReference<>(lbcache);
         }
 
         Shape result = lbcache[ix];
@@ -568,7 +568,7 @@
 
         return result;
     }
-    private SoftReference lbcacheRef;
+    private SoftReference<Shape[]> lbcacheRef;
 
     public Shape getGlyphVisualBounds(int ix) {
         if (ix < 0 || ix >= glyphs.length) {
@@ -576,9 +576,9 @@
         }
 
         Shape[] vbcache;
-        if (vbcacheRef == null || (vbcache = (Shape[])vbcacheRef.get()) == null) {
+        if (vbcacheRef == null || (vbcache = vbcacheRef.get()) == null) {
             vbcache = new Shape[glyphs.length];
-            vbcacheRef = new SoftReference(vbcache);
+            vbcacheRef = new SoftReference<>(vbcache);
         }
 
         Shape result = vbcache[ix];
@@ -589,7 +589,7 @@
 
         return result;
     }
-    private SoftReference vbcacheRef;
+    private SoftReference<Shape[]> vbcacheRef;
 
     public Rectangle getGlyphPixelBounds(int index, FontRenderContext renderFRC, float x, float y) {
       return getGlyphsPixelBounds(renderFRC, x, y, index, 1);
@@ -1230,14 +1230,14 @@
 
     private void clearCaches(int ix) {
         if (lbcacheRef != null) {
-            Shape[] lbcache = (Shape[])lbcacheRef.get();
+            Shape[] lbcache = lbcacheRef.get();
             if (lbcache != null) {
                 lbcache[ix] = null;
             }
         }
 
         if (vbcacheRef != null) {
-            Shape[] vbcache = (Shape[])vbcacheRef.get();
+            Shape[] vbcache = vbcacheRef.get();
             if (vbcache != null) {
                 vbcache[ix] = null;
             }
@@ -1357,11 +1357,11 @@
     private GlyphStrike getDefaultStrike() {
         GlyphStrike gs = null;
         if (fsref != null) {
-            gs = (GlyphStrike)fsref.get();
+            gs = fsref.get();
         }
         if (gs == null) {
             gs = GlyphStrike.create(this, dtx, null);
-            fsref = new SoftReference(gs);
+            fsref = new SoftReference<>(gs);
         }
         return gs;
     }
@@ -1379,7 +1379,7 @@
         StandardGlyphVector sgv;  // reference back to glyph vector - yuck
         int[] indices;            // index into unique strikes
         double[] transforms;      // six doubles per unique transform, because AT is a pain to manipulate
-        SoftReference strikesRef; // ref to unique strikes, one per transform
+        SoftReference<GlyphStrike[]> strikesRef; // ref to unique strikes, one per transform
         boolean haveAllStrikes;   // true if the strike array has been filled by getStrikes().
 
         // used when first setting a transform
@@ -1653,12 +1653,12 @@
         private GlyphStrike[] getStrikeArray() {
             GlyphStrike[] strikes = null;
             if (strikesRef != null) {
-                strikes = (GlyphStrike[])strikesRef.get();
+                strikes = strikesRef.get();
             }
             if (strikes == null) {
                 haveAllStrikes = false;
                 strikes = new GlyphStrike[transformCount() + 1];
-                strikesRef = new SoftReference(strikes);
+                strikesRef = new SoftReference<>(strikes);
             }
 
             return strikes;
--- a/jdk/src/share/classes/sun/font/StrikeCache.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/StrikeCache.java	Wed Jul 05 19:33:51 2017 +0200
@@ -65,7 +65,7 @@
 
     static final Unsafe unsafe = Unsafe.getUnsafe();
 
-    static ReferenceQueue refQueue = Disposer.getQueue();
+    static ReferenceQueue<Object> refQueue = Disposer.getQueue();
 
     static ArrayList<GlyphDisposedListener> disposeListeners = new ArrayList<GlyphDisposedListener>(1);
 
@@ -159,7 +159,7 @@
         }
 
         java.security.AccessController.doPrivileged(
-                                    new java.security.PrivilegedAction() {
+                                    new java.security.PrivilegedAction<Object>() {
             public Object run() {
 
                /* Allow a client to override the reference type used to
@@ -378,11 +378,11 @@
         }
     }
 
-    public static Reference getStrikeRef(FontStrike strike) {
+    public static Reference<FontStrike> getStrikeRef(FontStrike strike) {
         return getStrikeRef(strike, cacheRefTypeWeak);
     }
 
-    public static Reference getStrikeRef(FontStrike strike, boolean weak) {
+    public static Reference<FontStrike> getStrikeRef(FontStrike strike, boolean weak) {
         /* Some strikes may have no disposer as there's nothing
          * for them to free, as they allocated no native resource
          * eg, if they did not allocate resources because of a problem,
@@ -392,9 +392,9 @@
          */
         if (strike.disposer == null) {
             if (weak) {
-                return new WeakReference(strike);
+                return new WeakReference<>(strike);
             } else {
-                return new SoftReference(strike);
+                return new SoftReference<>(strike);
             }
         }
 
@@ -410,7 +410,7 @@
     }
 
     static class SoftDisposerRef
-        extends SoftReference implements DisposableStrike {
+        extends SoftReference<FontStrike> implements DisposableStrike {
 
         private FontStrikeDisposer disposer;
 
@@ -418,15 +418,16 @@
             return disposer;
         }
 
+        @SuppressWarnings("unchecked")
         SoftDisposerRef(FontStrike strike) {
             super(strike, StrikeCache.refQueue);
             disposer = strike.disposer;
-            Disposer.addReference(this, disposer);
+            Disposer.addReference((Reference<Object>)(Reference)this, disposer);
         }
     }
 
     static class WeakDisposerRef
-        extends WeakReference implements DisposableStrike {
+        extends WeakReference<FontStrike> implements DisposableStrike {
 
         private FontStrikeDisposer disposer;
 
@@ -434,10 +435,11 @@
             return disposer;
         }
 
+        @SuppressWarnings("unchecked")
         WeakDisposerRef(FontStrike strike) {
             super(strike, StrikeCache.refQueue);
             disposer = strike.disposer;
-            Disposer.addReference(this, disposer);
+            Disposer.addReference((Reference<Object>)(Reference)this, disposer);
         }
     }
 
--- a/jdk/src/share/classes/sun/font/SunFontManager.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/SunFontManager.java	Wed Jul 05 19:33:51 2017 +0200
@@ -197,9 +197,9 @@
     private static HashSet<String> missingFontFiles = null;
     private String defaultFontName;
     private String defaultFontFileName;
-    protected HashSet registeredFontFiles = new HashSet();
-
-    private ArrayList badFonts;
+    protected HashSet<String> registeredFontFiles = new HashSet<>();
+
+    private ArrayList<String> badFonts;
     /* fontPath is the location of all fonts on the system, excluding the
      * JRE's own font directory but including any path specified using the
      * sun.java2d.fontpath property. Together with that property,  it is
@@ -332,7 +332,7 @@
     static {
 
         java.security.AccessController.doPrivileged(
-                                    new java.security.PrivilegedAction() {
+                                    new java.security.PrivilegedAction<Object>() {
 
            public Object run() {
                FontManagerNativeLibrary.load();
@@ -373,7 +373,7 @@
 
         initJREFontMap();
         java.security.AccessController.doPrivileged(
-                new java.security.PrivilegedAction() {
+                new java.security.PrivilegedAction<Object>() {
                     public Object run() {
                         File badFontFile =
                             new File(jreFontDirName + File.separator +
@@ -381,7 +381,7 @@
                         if (badFontFile.exists()) {
                             FileInputStream fis = null;
                             try {
-                                badFonts = new ArrayList();
+                                badFonts = new ArrayList<>();
                                 fis = new FileInputStream(badFontFile);
                                 InputStreamReader isr = new InputStreamReader(fis);
                                 BufferedReader br = new BufferedReader(isr);
@@ -762,7 +762,7 @@
             if (family == null) {
                 family = new FontFamily(familyName, false, rank);
                 family.setFont(f, f.style);
-            } else if (family.getRank() >= rank) {
+            } else {
                 family.setFont(f, f.style);
             }
             fullNameToFont.put(fontName.toLowerCase(Locale.ENGLISH), f);
@@ -853,7 +853,7 @@
                 if (family == null) {
                     family = new FontFamily(familyName, false, rank);
                     family.setFont(newFont, newFont.style);
-                } else if (family.getRank() >= rank) {
+                } else {
                     family.setFont(newFont, newFont.style);
                 }
                 return newFont;
@@ -1227,9 +1227,9 @@
                  * and I don't know how to recover from there being absolutely
                  * no fonts anywhere on the system.
                  */
-                Iterator i = physicalFonts.values().iterator();
+                Iterator<PhysicalFont> i = physicalFonts.values().iterator();
                 if (i.hasNext()) {
-                    defaultPhysicalFont = (PhysicalFont)i.next();
+                    defaultPhysicalFont = i.next();
                 } else {
                     throw new Error("Probable fatal error:No fonts found.");
                 }
@@ -1303,7 +1303,7 @@
         } else {
             filter = new TTorT1Filter();
         }
-        return (String[])AccessController.doPrivileged(new PrivilegedAction() {
+        return (String[])AccessController.doPrivileged(new PrivilegedAction<Object>() {
             public Object run() {
                 if (pathDirs.length == 1) {
                     File dir = new File(pathDirs[0]);
@@ -1419,6 +1419,7 @@
              * them "MS UI Gothic" has no JA name whereas the other two do.
              * So not every font in these files is unmapped or new.
              */
+            @SuppressWarnings("unchecked")
             HashMap<String,String> ffmapCopy =
                 (HashMap<String,String>)(fontToFileMap.clone());
             for (String key : fontToFamilyNameMap.keySet()) {
@@ -1470,7 +1471,7 @@
                     String name = unmappedFontNames.get(i);
                     String familyName = fontToFamilyNameMap.get(name);
                     if (familyName != null) {
-                        ArrayList family = familyToFontListMap.get(familyName);
+                        ArrayList<String> family = familyToFontListMap.get(familyName);
                         if (family != null) {
                             if (family.size() <= 1) {
                                 familyToFontListMap.remove(familyName);
@@ -1896,7 +1897,7 @@
      * to register those again, but we do want to register other registry
      * installed fonts.
      */
-    protected void registerOtherFontFiles(HashSet registeredFontFiles) {
+    protected void registerOtherFontFiles(HashSet<String> registeredFontFiles) {
         if (getFullNameToFileMap().size() == 0) {
             return;
         }
@@ -2080,6 +2081,7 @@
          * name.
          */
         if (_usingPerAppContextComposites) {
+            @SuppressWarnings("unchecked")
             ConcurrentHashMap<String, Font2D> altNameCache =
                 (ConcurrentHashMap<String, Font2D>)
                 AppContext.getAppContext().get(CompositeFont.class);
@@ -2304,10 +2306,15 @@
                 nameTable = createdByFullName;
             } else {
                 AppContext appContext = AppContext.getAppContext();
-                familyTable =
+                @SuppressWarnings("unchecked")
+                Hashtable<String,FontFamily> tmp1 =
                     (Hashtable<String,FontFamily>)appContext.get(regFamilyKey);
-                nameTable =
+                familyTable = tmp1;
+
+                @SuppressWarnings("unchecked")
+                Hashtable<String, Font2D> tmp2 =
                     (Hashtable<String,Font2D>)appContext.get(regFullNameKey);
+                nameTable = tmp2;
             }
 
             family = familyTable.get(lowerCaseName);
@@ -2467,7 +2474,7 @@
         } catch (FontFormatException e) {
             if (isCopy) {
                 java.security.AccessController.doPrivileged(
-                     new java.security.PrivilegedAction() {
+                     new java.security.PrivilegedAction<Object>() {
                           public Object run() {
                               if (_tracker != null) {
                                   _tracker.subBytes((int)fFile.length());
@@ -2492,7 +2499,7 @@
                     final Runnable fileCloserRunnable = new Runnable() {
                       public void run() {
                          java.security.AccessController.doPrivileged(
-                         new java.security.PrivilegedAction() {
+                         new java.security.PrivilegedAction<Object>() {
                          public Object run() {
 
                             for (int i=0;i<CHANNELPOOLSIZE;i++) {
@@ -2521,7 +2528,7 @@
                       }
                     };
                     java.security.AccessController.doPrivileged(
-                       new java.security.PrivilegedAction() {
+                       new java.security.PrivilegedAction<Object>() {
                           public Object run() {
                               /* The thread must be a member of a thread group
                                * which will not get GCed before VM exit.
@@ -2627,15 +2634,17 @@
         fullNameToFont.remove(oldFont.fullName.toLowerCase(Locale.ENGLISH));
         FontFamily.remove(oldFont);
         if (localeFullNamesToFont != null) {
-            Map.Entry[] mapEntries = localeFullNamesToFont.entrySet().
-                toArray(new Map.Entry[0]);
+            Map.Entry<?, ?>[] mapEntries = localeFullNamesToFont.entrySet().
+                toArray(new Map.Entry<?, ?>[0]);
             /* Should I be replacing these, or just I just remove
              * the names from the map?
              */
             for (int i=0; i<mapEntries.length;i++) {
                 if (mapEntries[i].getValue() == oldFont) {
                     try {
-                        mapEntries[i].setValue(newFont);
+                        @SuppressWarnings("unchecked")
+                        Map.Entry<String, PhysicalFont> tmp = (Map.Entry<String, PhysicalFont>)mapEntries[i];
+                        tmp.setValue(newFont);
                     } catch (Exception e) {
                         /* some maps don't support this operation.
                          * In this case just give up and remove the entry.
@@ -2864,7 +2873,7 @@
     private static boolean maybeMultiAppContext() {
         Boolean appletSM = (Boolean)
             java.security.AccessController.doPrivileged(
-                new java.security.PrivilegedAction() {
+                new java.security.PrivilegedAction<Object>() {
                         public Object run() {
                             SecurityManager sm = System.getSecurityManager();
                             return new Boolean
@@ -3055,10 +3064,15 @@
             fontsAreRegistered = true;
         } else {
             AppContext appContext = AppContext.getAppContext();
-            familyTable =
+            @SuppressWarnings("unchecked")
+            Hashtable<String,FontFamily> tmp1 =
                 (Hashtable<String,FontFamily>)appContext.get(regFamilyKey);
-            fullNameTable =
+            familyTable = tmp1;
+            @SuppressWarnings("unchecked")
+            Hashtable<String,Font2D> tmp2 =
                 (Hashtable<String,Font2D>)appContext.get(regFullNameKey);
+            fullNameTable = tmp2;
+
             if (familyTable == null) {
                 familyTable = new Hashtable<String,FontFamily>();
                 fullNameTable = new Hashtable<String,Font2D>();
@@ -3114,8 +3128,10 @@
             familyTable = createdByFamilyName;
         } else if (fontsAreRegisteredPerAppContext) {
             AppContext appContext = AppContext.getAppContext();
-            familyTable =
+            @SuppressWarnings("unchecked")
+            Hashtable<String,FontFamily> tmp =
                 (Hashtable<String,FontFamily>)appContext.get(regFamilyKey);
+            familyTable = tmp;
         } else {
             return null;
         }
@@ -3142,8 +3158,10 @@
             nameTable = createdByFullName;
         } else if (fontsAreRegisteredPerAppContext) {
             AppContext appContext = AppContext.getAppContext();
-            nameTable =
+            @SuppressWarnings("unchecked")
+            Hashtable<String,Font2D> tmp =
                 (Hashtable<String,Font2D>)appContext.get(regFullNameKey);
+            nameTable = tmp;
         } else {
             return null;
         }
@@ -3305,7 +3323,7 @@
             initialiseDeferredFonts();
 
             java.security.AccessController.doPrivileged(
-                                    new java.security.PrivilegedAction() {
+                                    new java.security.PrivilegedAction<Object>() {
                 public Object run() {
                     if (fontPath == null) {
                         fontPath = getPlatformFontPath(noType1Font);
@@ -3440,7 +3458,7 @@
                 FontUtilities.getLogger().info("loadAllFontFiles() called");
             }
             java.security.AccessController.doPrivileged(
-                                    new java.security.PrivilegedAction() {
+                                    new java.security.PrivilegedAction<Object>() {
                 public Object run() {
                     if (fontPath == null) {
                         fontPath = getPlatformFontPath(noType1Font);
@@ -3682,7 +3700,7 @@
     public Font[] getAllInstalledFonts() {
         if (allFonts == null) {
             loadFonts();
-            TreeMap fontMapNames = new TreeMap();
+            TreeMap<String, Font2D> fontMapNames = new TreeMap<>();
             /* warning: the number of composite fonts could change dynamically
              * if applications are allowed to create them. "allfonts" could
              * then be stale.
@@ -3715,7 +3733,7 @@
             Font[] fonts = new Font[fontNames.length];
             for (int i=0; i < fontNames.length; i++) {
                 fonts[i] = new Font(fontNames[i], Font.PLAIN, 1);
-                Font2D f2d = (Font2D)fontMapNames.get(fontNames[i]);
+                Font2D f2d = fontMapNames.get(fontNames[i]);
                 if (f2d  != null) {
                     FontAccess.getFontAccess().setFont2D(fonts[i], f2d.handle);
                 }
@@ -3798,7 +3816,7 @@
 
     public void register1dot0Fonts() {
         java.security.AccessController.doPrivileged(
-                            new java.security.PrivilegedAction() {
+                            new java.security.PrivilegedAction<Object>() {
             public Object run() {
                 String type1Dir = "/usr/openwin/lib/X11/fonts/Type1";
                 registerFontsInDir(type1Dir, true, Font2D.TYPE1_RANK,
@@ -3840,7 +3858,7 @@
         if (systemLocale == null) {
             systemLocale = (Locale)
                 java.security.AccessController.doPrivileged(
-                                    new java.security.PrivilegedAction() {
+                                    new java.security.PrivilegedAction<Object>() {
             public Object run() {
                 /* On windows the system locale may be different than the
                  * user locale. This is an unsupported configuration, but
--- a/jdk/src/share/classes/sun/font/SunLayoutEngine.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/SunLayoutEngine.java	Wed Jul 05 19:33:51 2017 +0200
@@ -129,13 +129,13 @@
 
   // !!! don't need this unless we have more than one sun layout engine...
     public LayoutEngine getEngine(LayoutEngineKey key) {
-        ConcurrentHashMap cache = (ConcurrentHashMap)cacheref.get();
+        ConcurrentHashMap<LayoutEngineKey, LayoutEngine> cache = cacheref.get();
         if (cache == null) {
-            cache = new ConcurrentHashMap();
-            cacheref = new SoftReference(cache);
+            cache = new ConcurrentHashMap<>();
+            cacheref = new SoftReference<>(cache);
         }
 
-        LayoutEngine e = (LayoutEngine)cache.get(key);
+        LayoutEngine e = cache.get(key);
         if (e == null) {
             LayoutEngineKey copy = key.copy();
             e = new SunLayoutEngine(copy);
@@ -143,7 +143,8 @@
         }
         return e;
     }
-    private SoftReference cacheref = new SoftReference(null);
+    private SoftReference<ConcurrentHashMap<LayoutEngineKey, LayoutEngine>> cacheref =
+        new SoftReference<>(null);
 
     private SunLayoutEngine(LayoutEngineKey key) {
         this.key = key;
--- a/jdk/src/share/classes/sun/font/TrueTypeFont.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/TrueTypeFont.java	Wed Jul 05 19:33:51 2017 +0200
@@ -290,7 +290,7 @@
             try {
                 RandomAccessFile raf = (RandomAccessFile)
                 java.security.AccessController.doPrivileged(
-                    new java.security.PrivilegedAction() {
+                    new java.security.PrivilegedAction<Object>() {
                         public Object run() {
                             try {
                                 return new RandomAccessFile(platName, "r");
@@ -1546,7 +1546,7 @@
      * during typical start-up and the information here is likely never
      * needed.
      */
-    protected void initAllNames(int requestedID, HashSet names) {
+    protected void initAllNames(int requestedID, HashSet<String> names) {
 
         byte[] name = new byte[256];
         ByteBuffer buffer = getTableBuffer(nameTag);
@@ -1584,23 +1584,23 @@
     }
 
     String[] getAllFamilyNames() {
-        HashSet aSet = new HashSet();
+        HashSet<String> aSet = new HashSet<>();
         try {
             initAllNames(FAMILY_NAME_ID, aSet);
         } catch (Exception e) {
             /* In case of malformed font */
         }
-        return (String[])aSet.toArray(new String[0]);
+        return aSet.toArray(new String[0]);
     }
 
     String[] getAllFullNames() {
-        HashSet aSet = new HashSet();
+        HashSet<String> aSet = new HashSet<>();
         try {
             initAllNames(FULL_NAME_ID, aSet);
         } catch (Exception e) {
             /* In case of malformed font */
         }
-        return (String[])aSet.toArray(new String[0]);
+        return aSet.toArray(new String[0]);
     }
 
     /*  Used by the OpenType engine for mark positioning.
--- a/jdk/src/share/classes/sun/font/Type1Font.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/font/Type1Font.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +86,7 @@
 
         public synchronized void dispose() {
             java.security.AccessController.doPrivileged(
-                new java.security.PrivilegedAction() {
+                new java.security.PrivilegedAction<Object>() {
                     public Object run() {
 
                         if (fileName != null) {
@@ -98,16 +98,16 @@
         }
     }
 
-    WeakReference bufferRef = new WeakReference(null);
+    WeakReference<Object> bufferRef = new WeakReference<>(null);
 
     private String psName = null;
 
-    static private HashMap styleAbbreviationsMapping;
-    static private HashSet styleNameTokes;
+    static private HashMap<String, String> styleAbbreviationsMapping;
+    static private HashSet<String> styleNameTokes;
 
     static {
-        styleAbbreviationsMapping = new HashMap();
-        styleNameTokes = new HashSet();
+        styleAbbreviationsMapping = new HashMap<>();
+        styleNameTokes = new HashSet<>();
 
         /* These abbreviation rules are taken from Appendix 1 of Adobe Technical Note #5088 */
         /* NB: this list is not complete - we did not include abbreviations which contain
@@ -192,7 +192,7 @@
             try {
                 RandomAccessFile raf = (RandomAccessFile)
                 java.security.AccessController.doPrivileged(
-                    new java.security.PrivilegedAction() {
+                    new java.security.PrivilegedAction<Object>() {
                         public Object run() {
                             try {
                                 return new RandomAccessFile(platName, "r");
@@ -205,7 +205,7 @@
                 fileSize = (int)fc.size();
                 mapBuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);
                 mapBuf.position(0);
-                bufferRef = new WeakReference(mapBuf);
+                bufferRef = new WeakReference<>(mapBuf);
                 fc.close();
             } catch (NullPointerException e) {
                 throw new FontFormatException(e.toString());
@@ -232,7 +232,7 @@
         try {
             raf = (RandomAccessFile)
                 java.security.AccessController.doPrivileged(
-                    new java.security.PrivilegedAction() {
+                    new java.security.PrivilegedAction<Object>() {
                         public Object run() {
                             try {
                                 return new RandomAccessFile(platName, "r");
@@ -474,7 +474,7 @@
 
     private String expandAbbreviation(String abbr) {
         if (styleAbbreviationsMapping.containsKey(abbr))
-                        return (String) styleAbbreviationsMapping.get(abbr);
+                        return styleAbbreviationsMapping.get(abbr);
         return abbr;
     }
 
--- a/jdk/src/share/classes/sun/java2d/Disposer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/java2d/Disposer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -47,8 +47,9 @@
  * @see DisposerRecord
  */
 public class Disposer implements Runnable {
-    private static final ReferenceQueue queue = new ReferenceQueue();
-    private static final Hashtable records = new Hashtable();
+    private static final ReferenceQueue<Object> queue = new ReferenceQueue<>();
+    private static final Hashtable<java.lang.ref.Reference<Object>, DisposerRecord> records =
+        new Hashtable<>();
 
     private static Disposer disposerInstance;
     public static final int WEAK = 0;
@@ -77,7 +78,7 @@
         }
         disposerInstance = new Disposer();
         java.security.AccessController.doPrivileged(
-            new java.security.PrivilegedAction() {
+            new java.security.PrivilegedAction<Object>() {
                 public Object run() {
                     /* The thread must be a member of a thread group
                      * which will not get GCed before VM exit.
@@ -135,11 +136,11 @@
         if (target instanceof DisposerTarget) {
             target = ((DisposerTarget)target).getDisposerReferent();
         }
-        java.lang.ref.Reference ref;
+        java.lang.ref.Reference<Object> ref;
         if (refType == PHANTOM) {
-            ref = new PhantomReference(target, queue);
+            ref = new PhantomReference<>(target, queue);
         } else {
-            ref = new WeakReference(target, queue);
+            ref = new WeakReference<>(target, queue);
         }
         records.put(ref, rec);
     }
@@ -149,7 +150,7 @@
             try {
                 Object obj = queue.remove();
                 ((Reference)obj).clear();
-                DisposerRecord rec = (DisposerRecord)records.remove(obj);
+                DisposerRecord rec = records.remove(obj);
                 rec.dispose();
                 obj = null;
                 rec = null;
@@ -214,7 +215,7 @@
                    && freed < 10000 && deferred < 100) {
                 freed++;
                 ((Reference)obj).clear();
-                DisposerRecord rec = (DisposerRecord)records.remove(obj);
+                DisposerRecord rec = records.remove(obj);
                 if (rec instanceof PollDisposable) {
                     rec.dispose();
                     obj = null;
@@ -247,17 +248,18 @@
      * so will clutter the records hashmap and no one will be cleaning up
      * the reference queue.
      */
-    public static void addReference(Reference ref, DisposerRecord rec) {
+    @SuppressWarnings("unchecked")
+    public static void addReference(Reference<Object> ref, DisposerRecord rec) {
         records.put(ref, rec);
     }
 
     public static void addObjectRecord(Object obj, DisposerRecord rec) {
-        records.put(new WeakReference(obj, queue) , rec);
+        records.put(new WeakReference<>(obj, queue) , rec);
     }
 
     /* This is intended for use in conjunction with addReference(..)
      */
-    public static ReferenceQueue getQueue() {
+    public static ReferenceQueue<Object> getQueue() {
         return queue;
     }
 
--- a/jdk/src/share/classes/sun/java2d/SunGraphics2D.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/java2d/SunGraphics2D.java	Wed Jul 05 19:33:51 2017 +0200
@@ -61,6 +61,7 @@
 import java.awt.Rectangle;
 import java.text.AttributedCharacterIterator;
 import java.awt.Font;
+import java.awt.Point;
 import java.awt.image.ImageObserver;
 import java.awt.Transparency;
 import java.awt.font.GlyphVector;
@@ -93,6 +94,13 @@
 import sun.misc.PerformanceLogger;
 
 import java.lang.annotation.Native;
+import sun.awt.image.MultiResolutionImage;
+
+import static java.awt.geom.AffineTransform.TYPE_FLIP;
+import static java.awt.geom.AffineTransform.TYPE_MASK_SCALE;
+import static java.awt.geom.AffineTransform.TYPE_TRANSLATION;
+import sun.awt.image.MultiResolutionToolkitImage;
+import sun.awt.image.ToolkitImage;
 
 /**
  * This is a the master Graphics2D superclass for all of the Sun
@@ -237,6 +245,7 @@
     protected Region devClip;           // Actual physical drawable in pixels
 
     private final int devScale;         // Actual physical scale factor
+    private int resolutionVariantHint;
 
     // cached state for text rendering
     private boolean validFontInfo;
@@ -274,6 +283,7 @@
         lcdTextContrast = lcdTextContrastDefaultValue;
         interpolationHint = -1;
         strokeHint = SunHints.INTVAL_STROKE_DEFAULT;
+        resolutionVariantHint = SunHints.INTVAL_RESOLUTION_VARIANT_DEFAULT;
 
         interpolationType = AffineTransformOp.TYPE_NEAREST_NEIGHBOR;
 
@@ -1249,6 +1259,10 @@
                 stateChanged = (strokeHint != newHint);
                 strokeHint = newHint;
                 break;
+            case SunHints.INTKEY_RESOLUTION_VARIANT:
+                stateChanged = (resolutionVariantHint != newHint);
+                resolutionVariantHint = newHint;
+                break;
             default:
                 recognized = false;
                 stateChanged = false;
@@ -1322,6 +1336,9 @@
         case SunHints.INTKEY_STROKE_CONTROL:
             return SunHints.Value.get(SunHints.INTKEY_STROKE_CONTROL,
                                       strokeHint);
+        case SunHints.INTKEY_RESOLUTION_VARIANT:
+            return SunHints.Value.get(SunHints.INTKEY_RESOLUTION_VARIANT,
+                                      resolutionVariantHint);
         }
         return null;
     }
@@ -3050,18 +3067,58 @@
     }
 // end of text rendering methods
 
-    private static boolean isHiDPIImage(final Image img) {
-        return SurfaceManager.getImageScale(img) != 1;
+    private boolean isHiDPIImage(final Image img) {
+        return (SurfaceManager.getImageScale(img) != 1) ||
+               (resolutionVariantHint != SunHints.INTVAL_RESOLUTION_VARIANT_OFF
+                    && img instanceof MultiResolutionImage);
     }
 
     private boolean drawHiDPIImage(Image img, int dx1, int dy1, int dx2,
                                    int dy2, int sx1, int sy1, int sx2, int sy2,
                                    Color bgcolor, ImageObserver observer) {
-        final int scale = SurfaceManager.getImageScale(img);
-        sx1 = Region.clipScale(sx1, scale);
-        sx2 = Region.clipScale(sx2, scale);
-        sy1 = Region.clipScale(sy1, scale);
-        sy2 = Region.clipScale(sy2, scale);
+
+        if (SurfaceManager.getImageScale(img) != 1) {  // Volatile Image
+            final int scale = SurfaceManager.getImageScale(img);
+            sx1 = Region.clipScale(sx1, scale);
+            sx2 = Region.clipScale(sx2, scale);
+            sy1 = Region.clipScale(sy1, scale);
+            sy2 = Region.clipScale(sy2, scale);
+        } else if (img instanceof MultiResolutionImage) {
+            // get scaled destination image size
+
+            int width = img.getWidth(observer);
+            int height = img.getHeight(observer);
+
+            Image resolutionVariant = getResolutionVariant(
+                    (MultiResolutionImage) img, width, height,
+                    dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
+
+            if (resolutionVariant != img && resolutionVariant != null) {
+                // recalculate source region for the resolution variant
+
+                ImageObserver rvObserver = MultiResolutionToolkitImage.
+                        getResolutionVariantObserver(img, observer,
+                                width, height, -1, -1);
+
+                int rvWidth = resolutionVariant.getWidth(rvObserver);
+                int rvHeight = resolutionVariant.getHeight(rvObserver);
+
+                if (0 < width && 0 < height && 0 < rvWidth && 0 < rvHeight) {
+
+                    float widthScale = ((float) rvWidth) / width;
+                    float heightScale = ((float) rvHeight) / height;
+
+                    sx1 = Region.clipScale(sx1, widthScale);
+                    sy1 = Region.clipScale(sy1, heightScale);
+                    sx2 = Region.clipScale(sx2, widthScale);
+                    sy2 = Region.clipScale(sy2, heightScale);
+
+                    observer = rvObserver;
+                    img = resolutionVariant;
+                }
+            }
+        }
+
         try {
             return imagepipe.scaleImage(this, img, dx1, dy1, dx2, dy2, sx1, sy1,
                                         sx2, sy2, bgcolor, observer);
@@ -3081,6 +3138,54 @@
         }
     }
 
+    private Image getResolutionVariant(MultiResolutionImage img,
+            int srcWidth, int srcHeight, int dx1, int dy1, int dx2, int dy2,
+            int sx1, int sy1, int sx2, int sy2) {
+
+        if (srcWidth <= 0 || srcHeight <= 0) {
+            return null;
+        }
+
+        int sw = sx2 - sx1;
+        int sh = sy2 - sy1;
+
+        if (sw == 0 || sh == 0) {
+            return null;
+        }
+
+        int type = transform.getType();
+        int dw = dx2 - dx1;
+        int dh = dy2 - dy1;
+        double destRegionWidth;
+        double destRegionHeight;
+
+        if ((type & ~(TYPE_TRANSLATION | TYPE_FLIP)) == 0) {
+            destRegionWidth = dw;
+            destRegionHeight = dh;
+        } else if ((type & ~(TYPE_TRANSLATION | TYPE_FLIP | TYPE_MASK_SCALE)) == 0) {
+            destRegionWidth = dw * transform.getScaleX();
+            destRegionHeight = dh * transform.getScaleY();
+        } else {
+            destRegionWidth = dw * Math.hypot(
+                    transform.getScaleX(), transform.getShearY());
+            destRegionHeight = dh * Math.hypot(
+                    transform.getShearX(), transform.getScaleY());
+        }
+
+        int destImageWidth = (int) Math.abs(srcWidth * destRegionWidth / sw);
+        int destImageHeight = (int) Math.abs(srcHeight * destRegionHeight / sh);
+
+        Image resolutionVariant
+                = img.getResolutionVariant(destImageWidth, destImageHeight);
+
+        if (resolutionVariant instanceof ToolkitImage
+                && ((ToolkitImage) resolutionVariant).hasError()) {
+            return null;
+        }
+
+        return resolutionVariant;
+    }
+
     /**
      * Draws an image scaled to x,y,w,h in nonblocking mode with a
      * callback object.
--- a/jdk/src/share/classes/sun/management/VMManagementImpl.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/management/VMManagementImpl.java	Wed Jul 05 19:33:51 2017 +0200
@@ -37,7 +37,6 @@
 import java.util.Collections;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
-import sun.security.action.GetPropertyAction;
 
 /**
  * Implementation of VMManagement interface that accesses the management
@@ -173,10 +172,8 @@
     }
 
     public String   getBootClassPath( ) {
-        PrivilegedAction<String> pa
-            = new GetPropertyAction("sun.boot.class.path");
-        String result =  AccessController.doPrivileged(pa);
-        return result;
+        return AccessController.doPrivileged(
+            (PrivilegedAction<String>) () -> System.getProperty("sun.boot.class.path"));
     }
 
     public long getUptime() {
--- a/jdk/src/share/classes/sun/misc/CharacterDecoder.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/misc/CharacterDecoder.java	Wed Jul 05 19:33:51 2017 +0200
@@ -183,25 +183,21 @@
      * buffer and returns a byte array containing the data.
      * @exception CEFormatException An error has occurred while decoding
      */
-    public byte decodeBuffer(String inputString)[] throws IOException {
-        byte    inputBuffer[] = new byte[inputString.length()];
-        ByteArrayInputStream inStream;
-        ByteArrayOutputStream outStream;
-
-        inputString.getBytes(0, inputString.length(), inputBuffer, 0);
-        inStream = new ByteArrayInputStream(inputBuffer);
-        outStream = new ByteArrayOutputStream();
+    public byte[] decodeBuffer(String inputString) throws IOException {
+        byte inputBuffer[] = inputString.getBytes();
+        ByteArrayInputStream inStream = new ByteArrayInputStream(inputBuffer);
+        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
         decodeBuffer(inStream, outStream);
-        return (outStream.toByteArray());
+        return outStream.toByteArray();
     }
 
     /**
      * Decode the contents of the inputstream into a buffer.
      */
-    public byte decodeBuffer(InputStream in)[] throws IOException {
+    public byte[] decodeBuffer(InputStream in) throws IOException {
         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
         decodeBuffer(in, outStream);
-        return (outStream.toByteArray());
+        return outStream.toByteArray();
     }
 
     /**
--- a/jdk/src/share/classes/sun/net/spi/nameservice/dns/DNSNameService.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/net/spi/nameservice/dns/DNSNameService.java	Wed Jul 05 19:33:51 2017 +0200
@@ -36,7 +36,7 @@
 import sun.net.dns.ResolverConfiguration;
 import sun.net.spi.nameservice.*;
 import java.security.AccessController;
-import sun.security.action.*;
+import java.security.PrivilegedAction;
 
 /*
  * A name service provider based on JNDI-DNS.
@@ -231,7 +231,7 @@
 
         // default domain
         String domain = AccessController.doPrivileged(
-            new GetPropertyAction("sun.net.spi.nameservice.domain"));
+            (PrivilegedAction<String>) () -> System.getProperty("sun.net.spi.nameservice.domain"));
         if (domain != null && domain.length() > 0) {
             domainList = new LinkedList<String>();
             domainList.add(domain);
@@ -239,7 +239,7 @@
 
         // name servers
         String nameservers = AccessController.doPrivileged(
-            new GetPropertyAction("sun.net.spi.nameservice.nameservers"));
+            (PrivilegedAction<String>) () -> System.getProperty("sun.net.spi.nameservice.nameservers"));
         if (nameservers != null && nameservers.length() > 0) {
             nameProviderUrl = createProviderURL(nameservers);
             if (nameProviderUrl.length() == 0) {
--- a/jdk/src/share/classes/sun/rmi/log/ReliableLog.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/log/ReliableLog.java	Wed Jul 05 19:33:51 2017 +0200
@@ -30,8 +30,6 @@
 import java.rmi.server.RMIClassLoader;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
-import sun.security.action.GetBooleanAction;
-import sun.security.action.GetPropertyAction;
 
 /**
  * This class is a simple implementation of a reliable Log.  The
@@ -141,7 +139,7 @@
     {
         super();
         this.Debug = AccessController.doPrivileged(
-            new GetBooleanAction("sun.rmi.log.debug")).booleanValue();
+            (PrivilegedAction<Boolean>) () -> Boolean.getBoolean("sun.rmi.log.debug"));
         dir = new File(dirPath);
         if (!(dir.exists() && dir.isDirectory())) {
             // create directory
@@ -334,7 +332,7 @@
         getLogClassConstructor() {
 
         String logClassName = AccessController.doPrivileged(
-            new GetPropertyAction("sun.rmi.log.class"));
+            (PrivilegedAction<String>) () -> System.getProperty("sun.rmi.log.class"));
         if (logClassName != null) {
             try {
                 ClassLoader loader =
--- a/jdk/src/share/classes/sun/rmi/runtime/Log.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/runtime/Log.java	Wed Jul 05 19:33:51 2017 +0200
@@ -26,22 +26,16 @@
 package sun.rmi.runtime;
 
 import java.io.ByteArrayOutputStream;
-import java.io.IOException;
 import java.io.PrintStream;
 import java.io.OutputStream;
 import java.rmi.server.LogStream;
-import java.util.logging.ConsoleHandler;
+import java.security.PrivilegedAction;
 import java.util.logging.Handler;
-import java.util.logging.Formatter;
 import java.util.logging.SimpleFormatter;
-import java.util.logging.StreamHandler;
 import java.util.logging.Level;
 import java.util.logging.Logger;
-import java.util.logging.LogManager;
 import java.util.logging.LogRecord;
 import java.util.logging.StreamHandler;
-import java.util.Map;
-import java.util.HashMap;
 
 /**
  * Utility which provides an abstract "logger" like RMI internal API
@@ -71,10 +65,8 @@
     /* selects log implementation */
     private static final LogFactory logFactory;
     static {
-        boolean useOld =
-            Boolean.valueOf(java.security.AccessController.
-                doPrivileged(new sun.security.action.GetPropertyAction(
-                    "sun.rmi.log.useOld"))).booleanValue();
+        boolean useOld = java.security.AccessController.doPrivileged(
+            (PrivilegedAction<Boolean>) () -> Boolean.getBoolean("sun.rmi.log.useOld"));
 
         /* set factory to select the logging facility to use */
         logFactory = (useOld ? (LogFactory) new LogStreamLogFactory() :
--- a/jdk/src/share/classes/sun/rmi/runtime/RuntimeUtil.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/runtime/RuntimeUtil.java	Wed Jul 05 19:33:51 2017 +0200
@@ -33,7 +33,6 @@
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.logging.Level;
-import sun.security.action.GetIntegerAction;
 
 /**
  * RMI runtime implementation utilities.
@@ -54,8 +53,8 @@
 
     /** number of scheduler threads */
     private static final int schedulerThreads =         // default 1
-        AccessController.doPrivileged(
-            new GetIntegerAction("sun.rmi.runtime.schedulerThreads", 1));
+        AccessController.doPrivileged((PrivilegedAction<Integer>) () ->
+            Integer.getInteger("sun.rmi.runtime.schedulerThreads", 1));
 
     /** permission required to get instance */
     private static final Permission GET_INSTANCE_PERMISSION =
--- a/jdk/src/share/classes/sun/rmi/server/Activation.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/server/Activation.java	Wed Jul 05 19:33:51 2017 +0200
@@ -107,9 +107,6 @@
 import sun.rmi.runtime.NewThreadAction;
 import sun.rmi.server.UnicastServerRef;
 import sun.rmi.transport.LiveRef;
-import sun.security.action.GetBooleanAction;
-import sun.security.action.GetIntegerAction;
-import sun.security.action.GetPropertyAction;
 import sun.security.provider.PolicyFile;
 import com.sun.rmi.rmid.ExecPermission;
 import com.sun.rmi.rmid.ExecOptionPermission;
@@ -184,7 +181,8 @@
 
     // this should be a *private* method since it is privileged
     private static int getInt(String name, int def) {
-        return AccessController.doPrivileged(new GetIntegerAction(name, def));
+        return AccessController.doPrivileged(
+                (PrivilegedAction<Integer>) () -> Integer.getInteger(name, def));
     }
 
     private transient Activator activator;
@@ -2042,13 +2040,13 @@
             }
 
             debugExec = AccessController.doPrivileged(
-                new GetBooleanAction("sun.rmi.server.activation.debugExec"));
+                (PrivilegedAction<Boolean>) () -> Boolean.getBoolean("sun.rmi.server.activation.debugExec"));
 
             /**
              * Determine class name for activation exec policy (if any).
              */
             String execPolicyClassName = AccessController.doPrivileged(
-                new GetPropertyAction("sun.rmi.activation.execPolicy", null));
+                (PrivilegedAction<String>) () -> System.getProperty("sun.rmi.activation.execPolicy"));
             if (execPolicyClassName == null) {
                 if (!stop) {
                     DefaultExecPolicy.checkConfiguration();
@@ -2387,7 +2385,7 @@
 
     static {
         lineSeparator = AccessController.doPrivileged(
-            new GetPropertyAction("line.separator"));
+           (PrivilegedAction<String>) () -> System.getProperty("line.separator"));
         lineSeparatorLength = lineSeparator.length();
     }
 
--- a/jdk/src/share/classes/sun/rmi/server/LoaderHandler.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/server/LoaderHandler.java	Wed Jul 05 19:33:51 2017 +0200
@@ -47,6 +47,7 @@
 import java.security.Policy;
 import java.security.ProtectionDomain;
 import java.rmi.server.LogStream;
+import java.security.PrivilegedAction;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Enumeration;
@@ -57,7 +58,6 @@
 import java.util.WeakHashMap;
 import sun.reflect.misc.ReflectUtil;
 import sun.rmi.runtime.Log;
-import sun.security.action.GetPropertyAction;
 
 /**
  * <code>LoaderHandler</code> provides the implementation of the static
@@ -73,7 +73,7 @@
     /** RMI class loader log level */
     static final int logLevel = LogStream.parseLevel(
         java.security.AccessController.doPrivileged(
-            new GetPropertyAction("sun.rmi.loader.logLevel")));
+            (PrivilegedAction<String>) () -> System.getProperty("sun.rmi.loader.logLevel")));
 
     /* loader system log */
     static final Log loaderLog =
@@ -86,7 +86,7 @@
     private static String codebaseProperty = null;
     static {
         String prop = java.security.AccessController.doPrivileged(
-            new GetPropertyAction("java.rmi.server.codebase"));
+            (PrivilegedAction<String>) () -> System.getProperty("java.rmi.server.codebase"));
         if (prop != null && prop.trim().length() > 0) {
             codebaseProperty = prop;
         }
--- a/jdk/src/share/classes/sun/rmi/server/MarshalInputStream.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/server/MarshalInputStream.java	Wed Jul 05 19:33:51 2017 +0200
@@ -36,6 +36,7 @@
 import java.security.Permission;
 
 import java.rmi.server.RMIClassLoader;
+import java.security.PrivilegedAction;
 
 /**
  * MarshalInputStream is an extension of ObjectInputStream.  When resolving
@@ -65,7 +66,7 @@
      */
     private static final boolean useCodebaseOnlyProperty =
         ! java.security.AccessController.doPrivileged(
-            new sun.security.action.GetPropertyAction(
+            (PrivilegedAction<String>) () -> System.getProperty(
                 "java.rmi.server.useCodebaseOnly", "true"))
             .equalsIgnoreCase("false");
 
--- a/jdk/src/share/classes/sun/rmi/server/UnicastRef.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/server/UnicastRef.java	Wed Jul 05 19:33:51 2017 +0200
@@ -39,11 +39,11 @@
 import java.rmi.server.RemoteObject;
 import java.rmi.server.RemoteRef;
 import java.security.AccessController;
+import java.security.PrivilegedAction;
 import sun.rmi.runtime.Log;
 import sun.rmi.transport.Connection;
 import sun.rmi.transport.LiveRef;
 import sun.rmi.transport.StreamRemoteCall;
-import sun.security.action.GetBooleanAction;
 
 /**
  * NOTE: There is a JDK-internal dependency on the existence of this
@@ -64,8 +64,8 @@
      */
     public static final Log clientCallLog =
         Log.getLog("sun.rmi.client.call", "RMI",
-                   AccessController.doPrivileged(
-                       new GetBooleanAction("sun.rmi.client.logCalls")));
+                   AccessController.doPrivileged((PrivilegedAction<Boolean>) () ->
+                       Boolean.getBoolean("sun.rmi.client.logCalls")));
     private static final long serialVersionUID = 8258372400816541186L;
 
     protected LiveRef ref;
--- a/jdk/src/share/classes/sun/rmi/server/UnicastServerRef.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/server/UnicastServerRef.java	Wed Jul 05 19:33:51 2017 +0200
@@ -56,7 +56,6 @@
 import sun.rmi.transport.LiveRef;
 import sun.rmi.transport.Target;
 import sun.rmi.transport.tcp.TCPTransport;
-import sun.security.action.GetBooleanAction;
 
 /**
  * UnicastServerRef implements the remote reference layer server-side
@@ -73,7 +72,7 @@
 {
     /** value of server call log property */
     public static final boolean logCalls = AccessController.doPrivileged(
-        new GetBooleanAction("java.rmi.server.logCalls"));
+        (PrivilegedAction<Boolean>) () -> Boolean.getBoolean("java.rmi.server.logCalls"));
 
     /** server call log */
     public static final Log callLog =
@@ -84,8 +83,8 @@
 
     /** flag to enable writing exceptions to System.err */
     private static final boolean wantExceptionLog =
-        AccessController.doPrivileged(
-            new GetBooleanAction("sun.rmi.server.exceptionTrace"));
+        AccessController.doPrivileged((PrivilegedAction<Boolean>) () ->
+            Boolean.getBoolean("sun.rmi.server.exceptionTrace"));
 
     private boolean forceStubUse = false;
 
@@ -94,9 +93,8 @@
      * exceptions thrown by remote invocations to this VM
      */
     private static final boolean suppressStackTraces =
-        AccessController.doPrivileged(
-            new GetBooleanAction(
-                "sun.rmi.server.suppressStackTraces"));
+        AccessController.doPrivileged((PrivilegedAction<Boolean>) () ->
+            Boolean.getBoolean("sun.rmi.server.suppressStackTraces"));
 
     /**
      * skeleton to dispatch remote calls through, for 1.1 stub protocol
--- a/jdk/src/share/classes/sun/rmi/server/Util.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/server/Util.java	Wed Jul 05 19:33:51 2017 +0200
@@ -57,8 +57,6 @@
 import sun.rmi.runtime.Log;
 import sun.rmi.transport.LiveRef;
 import sun.rmi.transport.tcp.TCPEndpoint;
-import sun.security.action.GetBooleanAction;
-import sun.security.action.GetPropertyAction;
 
 /**
  * A utility class with static methods for creating stubs/proxies and
@@ -70,7 +68,7 @@
     /** "server" package log level */
     static final int logLevel = LogStream.parseLevel(
         AccessController.doPrivileged(
-            new GetPropertyAction("sun.rmi.server.logLevel")));
+            (PrivilegedAction<String>) () -> System.getProperty("sun.rmi.server.logLevel")));
 
     /** server reference log */
     public static final Log serverRefLog =
@@ -79,8 +77,7 @@
     /** cached value of property java.rmi.server.ignoreStubClasses */
     private static final boolean ignoreStubClasses =
         AccessController.doPrivileged(
-            new GetBooleanAction("java.rmi.server.ignoreStubClasses")).
-            booleanValue();
+            (PrivilegedAction<Boolean>) () -> Boolean.getBoolean("java.rmi.server.ignoreStubClasses"));
 
     /** cache of  impl classes that have no corresponding stub class */
     private static final Map<Class<?>, Void> withoutStubs =
--- a/jdk/src/share/classes/sun/rmi/transport/DGCAckHandler.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/transport/DGCAckHandler.java	Wed Jul 05 19:33:51 2017 +0200
@@ -27,6 +27,7 @@
 
 import java.rmi.server.UID;
 import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
@@ -36,7 +37,6 @@
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 import sun.rmi.runtime.RuntimeUtil;
-import sun.security.action.GetLongAction;
 
 /**
  * Holds strong references to a set of remote objects, or live remote
@@ -65,8 +65,8 @@
 
     /** timeout for holding references without receiving an acknowledgment */
     private static final long dgcAckTimeout =           // default 5 minutes
-        AccessController.doPrivileged(
-            new GetLongAction("sun.rmi.dgc.ackTimeout", 300000));
+        AccessController.doPrivileged((PrivilegedAction<Long>) () ->
+            Long.getLong("sun.rmi.dgc.ackTimeout", 300000));
 
     /** thread pool for scheduling delayed tasks */
     private static final ScheduledExecutorService scheduler =
--- a/jdk/src/share/classes/sun/rmi/transport/DGCClient.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/transport/DGCClient.java	Wed Jul 05 19:33:51 2017 +0200
@@ -44,7 +44,6 @@
 import sun.rmi.runtime.NewThreadAction;
 import sun.rmi.server.UnicastRef;
 import sun.rmi.server.Util;
-import sun.security.action.GetLongAction;
 
 /**
  * DGCClient implements the client-side of the RMI distributed garbage
@@ -85,21 +84,18 @@
 
     /** lease duration to request (usually ignored by server) */
     private static final long leaseValue =              // default 10 minutes
-        AccessController.doPrivileged(
-            new GetLongAction("java.rmi.dgc.leaseValue",
-                              600000)).longValue();
+        AccessController.doPrivileged((PrivilegedAction<Long>) () ->
+            Long.getLong("java.rmi.dgc.leaseValue", 600000));
 
     /** maximum interval between retries of failed clean calls */
     private static final long cleanInterval =           // default 3 minutes
-        AccessController.doPrivileged(
-            new GetLongAction("sun.rmi.dgc.cleanInterval",
-                              180000)).longValue();
+        AccessController.doPrivileged((PrivilegedAction<Long>) () ->
+            Long.getLong("sun.rmi.dgc.cleanInterval", 180000));
 
     /** maximum interval between complete garbage collections of local heap */
     private static final long gcInterval =              // default 1 hour
-        AccessController.doPrivileged(
-            new GetLongAction("sun.rmi.dgc.client.gcInterval",
-                              3600000)).longValue();
+        AccessController.doPrivileged((PrivilegedAction<Long>) () ->
+            Long.getLong("sun.rmi.dgc.client.gcInterval", 3600000));
 
     /** minimum retry count for dirty calls that fail */
     private static final int dirtyFailureRetries = 5;
--- a/jdk/src/share/classes/sun/rmi/transport/DGCImpl.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/transport/DGCImpl.java	Wed Jul 05 19:33:51 2017 +0200
@@ -50,8 +50,6 @@
 import sun.rmi.server.UnicastRef;
 import sun.rmi.server.UnicastServerRef;
 import sun.rmi.server.Util;
-import sun.security.action.GetLongAction;
-import sun.security.action.GetPropertyAction;
 
 /**
  * This class implements the guts of the server-side distributed GC
@@ -65,17 +63,17 @@
     /* dgc system log */
     static final Log dgcLog = Log.getLog("sun.rmi.dgc", "dgc",
         LogStream.parseLevel(AccessController.doPrivileged(
-            new GetPropertyAction("sun.rmi.dgc.logLevel"))));
+            (PrivilegedAction<String>) () -> System.getProperty("sun.rmi.dgc.logLevel"))));
 
     /** lease duration to grant to clients */
     private static final long leaseValue =              // default 10 minutes
         AccessController.doPrivileged(
-            new GetLongAction("java.rmi.dgc.leaseValue", 600000));
+            (PrivilegedAction<Long>) () -> Long.getLong("java.rmi.dgc.leaseValue", 600000));
 
     /** lease check interval; default is half of lease grant duration */
     private static final long leaseCheckInterval =
         AccessController.doPrivileged(
-            new GetLongAction("sun.rmi.dgc.checkInterval", leaseValue / 2));
+            (PrivilegedAction<Long>) () -> Long.getLong("sun.rmi.dgc.checkInterval", leaseValue / 2));
 
     /** thread pool for scheduling delayed tasks */
     private static final ScheduledExecutorService scheduler =
--- a/jdk/src/share/classes/sun/rmi/transport/ObjectTable.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/transport/ObjectTable.java	Wed Jul 05 19:33:51 2017 +0200
@@ -37,7 +37,6 @@
 import sun.misc.GC;
 import sun.rmi.runtime.Log;
 import sun.rmi.runtime.NewThreadAction;
-import sun.security.action.GetLongAction;
 
 /**
  * Object table shared by all implementors of the Transport interface.
@@ -51,8 +50,8 @@
 
     /** maximum interval between complete garbage collections of local heap */
     private final static long gcInterval =              // default 1 hour
-        AccessController.doPrivileged(
-            new GetLongAction("sun.rmi.dgc.server.gcInterval", 3600000));
+        AccessController.doPrivileged((PrivilegedAction<Long>) () ->
+            Long.getLong("sun.rmi.dgc.server.gcInterval", 3600000));
 
     /**
      * lock guarding objTable and implTable.
--- a/jdk/src/share/classes/sun/rmi/transport/Transport.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/transport/Transport.java	Wed Jul 05 19:33:51 2017 +0200
@@ -37,6 +37,7 @@
 import java.rmi.server.RemoteServer;
 import java.rmi.server.ServerNotActiveException;
 import java.security.AccessControlContext;
+import java.security.PrivilegedAction;
 import sun.rmi.runtime.Log;
 import sun.rmi.server.Dispatcher;
 import sun.rmi.server.UnicastServerRef;
@@ -55,7 +56,7 @@
 
     private static String getLogLevel() {
         return java.security.AccessController.doPrivileged(
-            new sun.security.action.GetPropertyAction("sun.rmi.transport.logLevel"));
+            (PrivilegedAction<String>) () -> System.getProperty("sun.rmi.transport.logLevel"));
     }
 
     /* transport package log */
--- a/jdk/src/share/classes/sun/rmi/transport/proxy/HttpSendSocket.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/transport/proxy/HttpSendSocket.java	Wed Jul 05 19:33:51 2017 +0200
@@ -26,6 +26,7 @@
 
 import java.io.*;
 import java.net.*;
+import java.security.PrivilegedAction;
 
 import sun.rmi.runtime.Log;
 
@@ -79,7 +80,7 @@
      */
     private String lineSeparator =
         java.security.AccessController.doPrivileged(
-            new sun.security.action.GetPropertyAction("line.separator"));
+            (PrivilegedAction<String>) () -> System.getProperty("line.separator"));
 
     /**
      * Create a stream socket and connect it to the specified port on
--- a/jdk/src/share/classes/sun/rmi/transport/proxy/RMIMasterSocketFactory.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/transport/proxy/RMIMasterSocketFactory.java	Wed Jul 05 19:33:51 2017 +0200
@@ -32,9 +32,6 @@
 import java.rmi.server.RMISocketFactory;
 import sun.rmi.runtime.Log;
 import sun.rmi.runtime.NewThreadAction;
-import sun.security.action.GetBooleanAction;
-import sun.security.action.GetLongAction;
-import sun.security.action.GetPropertyAction;
 
 /**
  * RMIMasterSocketFactory attempts to create a socket connection to the
@@ -53,7 +50,7 @@
 
     private static String getLogLevel() {
         return java.security.AccessController.doPrivileged(
-            new sun.security.action.GetPropertyAction("sun.rmi.transport.proxy.logLevel"));
+            (PrivilegedAction<String>) () -> System.getProperty("sun.rmi.transport.proxy.logLevel"));
     }
 
     /* proxy package log */
@@ -65,15 +62,14 @@
     private static long connectTimeout = getConnectTimeout();
 
     private static long getConnectTimeout() {
-        return java.security.AccessController.doPrivileged(
-                new GetLongAction("sun.rmi.transport.proxy.connectTimeout",
-                              15000)).longValue(); // default: 15 seconds
+        return java.security.AccessController.doPrivileged((PrivilegedAction<Long>) () ->
+            Long.getLong("sun.rmi.transport.proxy.connectTimeout", 15000)); // default: 15 seconds
     }
 
     /** whether to fallback to HTTP on general connect failures */
     private static final boolean eagerHttpFallback =
-        java.security.AccessController.doPrivileged(new GetBooleanAction(
-            "sun.rmi.transport.proxy.eagerHttpFallback")).booleanValue();
+        java.security.AccessController.doPrivileged((PrivilegedAction<Boolean>) () ->
+            Boolean.getBoolean("sun.rmi.transport.proxy.eagerHttpFallback"));
 
     /** table of hosts successfully connected to and the factory used */
     private Hashtable<String, RMISocketFactory> successTable =
@@ -104,14 +100,14 @@
         try {
             String proxyHost;
             proxyHost = java.security.AccessController.doPrivileged(
-                new GetPropertyAction("http.proxyHost"));
+               (PrivilegedAction<String>) () -> System.getProperty("http.proxyHost"));
 
             if (proxyHost == null)
                 proxyHost = java.security.AccessController.doPrivileged(
-                    new GetPropertyAction("proxyHost"));
+                    (PrivilegedAction<String>) () -> System.getProperty("proxyHost"));
 
             boolean disable = java.security.AccessController.doPrivileged(
-                new GetPropertyAction("java.rmi.server.disableHttp", "true"))
+                (PrivilegedAction<String>) () -> System.getProperty("java.rmi.server.disableHttp", "true"))
                 .equalsIgnoreCase("true");
 
             if (!disable && proxyHost != null && proxyHost.length() > 0) {
--- a/jdk/src/share/classes/sun/rmi/transport/tcp/ConnectionMultiplexer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/transport/tcp/ConnectionMultiplexer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -27,6 +27,7 @@
 import java.io.*;
 import java.util.*;
 import java.rmi.server.LogStream;
+import java.security.PrivilegedAction;
 
 import sun.rmi.runtime.Log;
 
@@ -51,7 +52,7 @@
 
     private static String getLogLevel() {
         return java.security.AccessController.doPrivileged(
-            new sun.security.action.GetPropertyAction("sun.rmi.transport.tcp.multiplex.logLevel"));
+           (PrivilegedAction<String>) () -> System.getProperty("sun.rmi.transport.tcp.multiplex.logLevel"));
     }
 
     /* multiplex system log */
--- a/jdk/src/share/classes/sun/rmi/transport/tcp/TCPChannel.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/transport/tcp/TCPChannel.java	Wed Jul 05 19:33:51 2017 +0200
@@ -34,6 +34,7 @@
 import java.rmi.RemoteException;
 import java.security.AccessControlContext;
 import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.ListIterator;
@@ -48,8 +49,6 @@
 import sun.rmi.transport.Connection;
 import sun.rmi.transport.Endpoint;
 import sun.rmi.transport.TransportConstants;
-import sun.security.action.GetIntegerAction;
-import sun.security.action.GetLongAction;
 
 /**
  * TCPChannel is the socket-based implementation of the RMI Channel
@@ -87,19 +86,18 @@
 
     /** client-side connection idle usage timeout */
     private static final long idleTimeout =             // default 15 seconds
-        AccessController.doPrivileged(
-            new GetLongAction("sun.rmi.transport.connectionTimeout", 15000));
+        AccessController.doPrivileged((PrivilegedAction<Long>) () ->
+            Long.getLong("sun.rmi.transport.connectionTimeout", 15000));
 
     /** client-side connection handshake read timeout */
     private static final int handshakeTimeout =         // default 1 minute
-        AccessController.doPrivileged(
-            new GetIntegerAction("sun.rmi.transport.tcp.handshakeTimeout",
-                                 60000));
+        AccessController.doPrivileged((PrivilegedAction<Integer>) () ->
+            Integer.getInteger("sun.rmi.transport.tcp.handshakeTimeout", 60000));
 
     /** client-side connection response read timeout (after handshake) */
     private static final int responseTimeout =          // default infinity
-        AccessController.doPrivileged(
-            new GetIntegerAction("sun.rmi.transport.tcp.responseTimeout", 0));
+        AccessController.doPrivileged((PrivilegedAction<Integer>) () ->
+            Integer.getInteger("sun.rmi.transport.tcp.responseTimeout", 0));
 
     /** thread pool for scheduling delayed tasks */
     private static final ScheduledExecutorService scheduler =
--- a/jdk/src/share/classes/sun/rmi/transport/tcp/TCPEndpoint.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/transport/tcp/TCPEndpoint.java	Wed Jul 05 19:33:51 2017 +0200
@@ -38,6 +38,7 @@
 import java.rmi.server.RMIServerSocketFactory;
 import java.rmi.server.RMISocketFactory;
 import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -50,9 +51,6 @@
 import sun.rmi.transport.Endpoint;
 import sun.rmi.transport.Target;
 import sun.rmi.transport.Transport;
-import sun.security.action.GetBooleanAction;
-import sun.security.action.GetIntegerAction;
-import sun.security.action.GetPropertyAction;
 
 /**
  * TCPEndpoint represents some communication endpoint for an address
@@ -82,12 +80,14 @@
 
     // this should be a *private* method since it is privileged
     private static int getInt(String name, int def) {
-        return AccessController.doPrivileged(new GetIntegerAction(name, def));
+        return AccessController.doPrivileged(
+                (PrivilegedAction<Integer>) () -> Integer.getInteger(name, def));
     }
 
     // this should be a *private* method since it is privileged
     private static boolean getBoolean(String name) {
-        return AccessController.doPrivileged(new GetBooleanAction(name));
+        return AccessController.doPrivileged(
+                (PrivilegedAction<Boolean>) () -> Boolean.getBoolean(name));
     }
 
     /**
@@ -95,7 +95,7 @@
      */
     private static String getHostnameProperty() {
         return AccessController.doPrivileged(
-            new GetPropertyAction("java.rmi.server.hostname"));
+            (PrivilegedAction<String>) () -> System.getProperty("java.rmi.server.hostname"));
     }
 
     /**
--- a/jdk/src/share/classes/sun/rmi/transport/tcp/TCPTransport.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/rmi/transport/tcp/TCPTransport.java	Wed Jul 05 19:33:51 2017 +0200
@@ -49,6 +49,7 @@
 import java.rmi.server.UID;
 import java.security.AccessControlContext;
 import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.ArrayList;
 import java.util.LinkedList;
 import java.util.List;
@@ -73,9 +74,6 @@
 import sun.rmi.transport.Transport;
 import sun.rmi.transport.TransportConstants;
 import sun.rmi.transport.proxy.HttpReceiveSocket;
-import sun.security.action.GetIntegerAction;
-import sun.security.action.GetLongAction;
-import sun.security.action.GetPropertyAction;
 
 /**
  * TCPTransport is the socket-based implementation of the RMI Transport
@@ -90,19 +88,18 @@
     /* tcp package log */
     static final Log tcpLog = Log.getLog("sun.rmi.transport.tcp", "tcp",
         LogStream.parseLevel(AccessController.doPrivileged(
-            new GetPropertyAction("sun.rmi.transport.tcp.logLevel"))));
+            (PrivilegedAction<String>) () -> System.getProperty("sun.rmi.transport.tcp.logLevel"))));
 
     /** maximum number of connection handler threads */
     private static final int maxConnectionThreads =     // default no limit
-        AccessController.doPrivileged(
-            new GetIntegerAction("sun.rmi.transport.tcp.maxConnectionThreads",
-                                 Integer.MAX_VALUE));
+        AccessController.doPrivileged((PrivilegedAction<Integer>) () ->
+            Integer.getInteger("sun.rmi.transport.tcp.maxConnectionThreads",
+                               Integer.MAX_VALUE));
 
     /** keep alive time for idle connection handler threads */
     private static final long threadKeepAliveTime =     // default 1 minute
-        AccessController.doPrivileged(
-            new GetLongAction("sun.rmi.transport.tcp.threadKeepAliveTime",
-                              60000));
+        AccessController.doPrivileged((PrivilegedAction<Long>) () ->
+            Long.getLong("sun.rmi.transport.tcp.threadKeepAliveTime", 60000));
 
     /** thread pool for connection handlers */
     private static final ExecutorService connectionThreadPool =
@@ -143,9 +140,8 @@
      * and 20 hours.
      */
     private static final int connectionReadTimeout =    // default 2 hours
-        AccessController.doPrivileged(
-            new GetIntegerAction("sun.rmi.transport.tcp.readTimeout",
-                                 2 * 3600 * 1000));
+        AccessController.doPrivileged((PrivilegedAction<Integer>) () ->
+            Integer.getInteger("sun.rmi.transport.tcp.readTimeout", 2 * 3600 * 1000));
 
     /**
      * Constructs a TCPTransport.
--- a/jdk/src/share/classes/sun/security/krb5/Config.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/Config.java	Wed Jul 05 19:33:51 2017 +0200
@@ -549,12 +549,11 @@
                             previous = line.substring(1).trim();
                         }
                     } else {
-                        if (previous == null) {
-                            throw new KrbException(
-                                "Config file must starts with a section");
+                        // Lines before the first section are ignored
+                        if (previous != null) {
+                            v.add(previous);
+                            previous = line;
                         }
-                        v.add(previous);
-                        previous = line;
                     }
                 }
                 if (previous != null) {
--- a/jdk/src/share/classes/sun/security/krb5/KrbApReq.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/KrbApReq.java	Wed Jul 05 19:33:51 2017 +0200
@@ -284,7 +284,7 @@
 
         if (dkey == null) {
             throw new KrbException(Krb5.API_INVALID_ARG,
-                "Cannot find key of appropriate type to decrypt AP REP - " +
+                "Cannot find key of appropriate type to decrypt AP-REQ - " +
                                    EType.toString(encPartKeyType));
         }
 
@@ -380,7 +380,7 @@
 
     /**
      * Returns the credentials that are contained in the ticket that
-     * is part of this this AP-REP.
+     * is part of this AP-REQ.
      */
     public Credentials getCreds() {
         return creds;
--- a/jdk/src/share/classes/sun/security/provider/certpath/PKIXCertPathValidator.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/security/provider/certpath/PKIXCertPathValidator.java	Wed Jul 05 19:33:51 2017 +0200
@@ -94,9 +94,6 @@
             X509Certificate firstCert = certList.get(0);
             // check trusted certificate's subject
             selector.setSubject(firstCert.getIssuerX500Principal());
-            // check the validity period
-            selector.setValidityPeriod(firstCert.getNotBefore(),
-                                       firstCert.getNotAfter());
             /*
              * Facilitate certification path construction with authority
              * key identifier and subject key identifier.
--- a/jdk/src/share/classes/sun/security/tools/policytool/PolicyTool.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/security/tools/policytool/PolicyTool.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1160,7 +1160,7 @@
         if (policyFile == null) {
             String userHome;
             userHome = java.security.AccessController.doPrivileged(
-                    new sun.security.action.GetPropertyAction("user.home"));
+                (PrivilegedAction<String>) () -> System.getProperty("user.home"));
             policyFile = userHome + File.separatorChar + ".java.policy";
         }
 
--- a/jdk/src/share/classes/sun/security/util/DerInputStream.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/security/util/DerInputStream.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +167,7 @@
         if (buffer.read() != DerValue.tag_Integer) {
             throw new IOException("DER input, Integer tag error");
         }
-        return buffer.getInteger(getLength(buffer));
+        return buffer.getInteger(getDefiniteLength(buffer));
     }
 
     /**
@@ -179,7 +179,7 @@
         if (buffer.read() != DerValue.tag_Integer) {
             throw new IOException("DER input, Integer tag error");
         }
-        return buffer.getBigInteger(getLength(buffer), false);
+        return buffer.getBigInteger(getDefiniteLength(buffer), false);
     }
 
     /**
@@ -193,7 +193,7 @@
         if (buffer.read() != DerValue.tag_Integer) {
             throw new IOException("DER input, Integer tag error");
         }
-        return buffer.getBigInteger(getLength(buffer), true);
+        return buffer.getBigInteger(getDefiniteLength(buffer), true);
     }
 
     /**
@@ -205,7 +205,7 @@
         if (buffer.read() != DerValue.tag_Enumerated) {
             throw new IOException("DER input, Enumerated tag error");
         }
-        return buffer.getInteger(getLength(buffer));
+        return buffer.getInteger(getDefiniteLength(buffer));
     }
 
     /**
@@ -216,7 +216,7 @@
         if (buffer.read() != DerValue.tag_BitString)
             throw new IOException("DER input not an bit string");
 
-        return buffer.getBitString(getLength(buffer));
+        return buffer.getBitString(getDefiniteLength(buffer));
     }
 
     /**
@@ -224,21 +224,32 @@
      * not be byte-aligned.
      */
     public BitArray getUnalignedBitString() throws IOException {
-        if (buffer.read() != DerValue.tag_BitString)
+        if (buffer.read() != DerValue.tag_BitString) {
             throw new IOException("DER input not a bit string");
+        }
 
-        int length = getLength(buffer) - 1;
+        int length = getDefiniteLength(buffer);
+
+        if (length == 0) {
+            return new BitArray(0);
+        }
 
         /*
          * First byte = number of excess bits in the last octet of the
          * representation.
          */
+        length--;
         int validBits = length*8 - buffer.read();
+        if (validBits < 0) {
+            throw new IOException("valid bits of bit string invalid");
+        }
 
         byte[] repn = new byte[length];
 
-        if ((length != 0) && (buffer.read(repn) != length))
+        if ((length != 0) && (buffer.read(repn) != length)) {
             throw new IOException("short read of DER bit string");
+        }
+
         return new BitArray(validBits, repn);
     }
 
@@ -249,7 +260,7 @@
         if (buffer.read() != DerValue.tag_OctetString)
             throw new IOException("DER input not an octet string");
 
-        int length = getLength(buffer);
+        int length = getDefiniteLength(buffer);
         byte[] retval = new byte[length];
         if ((length != 0) && (buffer.read(retval) != length))
             throw new IOException("short read of DER octet string");
@@ -363,7 +374,7 @@
            if (tag != buffer.read())
                 throw new IOException("Indefinite length encoding" +
                         " not supported");
-           len = DerInputStream.getLength(buffer);
+           len = DerInputStream.getDefiniteLength(buffer);
         }
 
         if (len == 0)
@@ -480,7 +491,7 @@
             throw new IOException("DER input not a " +
                                   stringName + " string");
 
-        int length = getLength(buffer);
+        int length = getDefiniteLength(buffer);
         byte[] retval = new byte[length];
         if ((length != 0) && (buffer.read(retval) != length))
             throw new IOException("short read of DER " +
@@ -495,7 +506,7 @@
     public Date getUTCTime() throws IOException {
         if (buffer.read() != DerValue.tag_UtcTime)
             throw new IOException("DER input, UTCtime tag invalid ");
-        return buffer.getUTCTime(getLength(buffer));
+        return buffer.getUTCTime(getDefiniteLength(buffer));
     }
 
     /**
@@ -504,7 +515,7 @@
     public Date getGeneralizedTime() throws IOException {
         if (buffer.read() != DerValue.tag_GeneralizedTime)
             throw new IOException("DER input, GeneralizedTime tag invalid ");
-        return buffer.getGeneralizedTime(getLength(buffer));
+        return buffer.getGeneralizedTime(getDefiniteLength(buffer));
     }
 
     /*
@@ -570,6 +581,24 @@
         return value;
     }
 
+    int getDefiniteLength() throws IOException {
+        return getDefiniteLength(buffer);
+    }
+
+    /*
+     * Get a length from the input stream.
+     *
+     * @return the length
+     * @exception IOException on parsing error or if indefinite length found.
+     */
+    static int getDefiniteLength(InputStream in) throws IOException {
+        int len = getLength(in);
+        if (len < 0) {
+            throw new IOException("Indefinite length encoding not supported");
+        }
+        return len;
+    }
+
     /**
      * Mark the current position in the buffer, so that
      * a later call to <code>reset</code> will return here.
--- a/jdk/src/share/classes/sun/security/util/DerValue.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/security/util/DerValue.java	Wed Jul 05 19:33:51 2017 +0200
@@ -265,7 +265,7 @@
             if (tag != inbuf.read())
                 throw new IOException
                         ("Indefinite length encoding not supported");
-            length = DerInputStream.getLength(inbuf);
+            length = DerInputStream.getDefiniteLength(inbuf);
             buffer = inbuf.dup();
             buffer.truncate(length);
             data = new DerInputStream(buffer);
@@ -377,7 +377,7 @@
             if (tag != in.read())
                 throw new IOException
                         ("Indefinite length encoding not supported");
-            length = DerInputStream.getLength(in);
+            length = DerInputStream.getDefiniteLength(in);
         }
 
         if (fullyBuffered && in.available() != length)
--- a/jdk/src/share/classes/sun/security/util/ObjectIdentifier.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/security/util/ObjectIdentifier.java	Wed Jul 05 19:33:51 2017 +0200
@@ -255,7 +255,7 @@
                 + " (tag = " +  type_id + ")"
                 );
 
-        encoding = new byte[in.getLength()];
+        encoding = new byte[in.getDefiniteLength()];
         in.getBytes(encoding);
         check(encoding);
     }
--- a/jdk/src/share/classes/sun/swing/AbstractFilterComboBoxModel.java	Tue Mar 25 12:31:49 2014 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,105 +0,0 @@
-/*
- * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
- * 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.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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.swing;
-
-import javax.swing.AbstractListModel;
-import javax.swing.ComboBoxModel;
-import javax.swing.JFileChooser;
-import javax.swing.filechooser.FileFilter;
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-
-/**
- * Data model for a type-face selection combo-box.
- */
-@SuppressWarnings("serial") // JDK-implementation class
-public abstract class AbstractFilterComboBoxModel
-        extends AbstractListModel<FileFilter>
-        implements ComboBoxModel<FileFilter>, PropertyChangeListener {
-
-    protected FileFilter[] filters;
-
-    protected AbstractFilterComboBoxModel() {
-        this.filters = getFileChooser().getChoosableFileFilters();
-    }
-
-    protected abstract JFileChooser getFileChooser();
-
-    @Override
-    public void propertyChange(PropertyChangeEvent event) {
-        String property = event.getPropertyName();
-        if (property == JFileChooser.CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY) {
-            this.filters = (FileFilter[]) event.getNewValue();
-            fireContentsChanged(this, -1, -1);
-        } else if (property == JFileChooser.FILE_FILTER_CHANGED_PROPERTY) {
-            fireContentsChanged(this, -1, -1);
-        }
-    }
-
-    @Override
-    public void setSelectedItem(Object filter) {
-        if (filter != null) {
-            getFileChooser().setFileFilter((FileFilter) filter);
-            fireContentsChanged(this, -1, -1);
-        }
-    }
-
-    @Override
-    public Object getSelectedItem() {
-        // Ensure that the current filter is in the list.
-        // NOTE: we should not have to do this, since JFileChooser adds
-        // the filter to the choosable filters list when the filter
-        // is set. Lets be paranoid just in case someone overrides
-        // setFileFilter in JFileChooser.
-        FileFilter currentFilter = getFileChooser().getFileFilter();
-        if (currentFilter != null) {
-            for (FileFilter filter : this.filters) {
-                if (filter == currentFilter) {
-                    return currentFilter;
-                }
-            }
-            getFileChooser().addChoosableFileFilter(currentFilter);
-        }
-        return currentFilter;
-    }
-
-    @Override
-    public int getSize() {
-        return (this.filters != null)
-                ? filters.length
-                : 0;
-    }
-
-    @Override
-    public FileFilter getElementAt(int index) {
-        if (index >= getSize()) {
-            // This shouldn't happen. Try to recover gracefully.
-            return getFileChooser().getFileFilter();
-        }
-        return (this.filters != null)
-                ? filters[index]
-                : null;
-    }
-}
--- a/jdk/src/share/classes/sun/swing/JLightweightFrame.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/swing/JLightweightFrame.java	Wed Jul 05 19:33:51 2017 +0200
@@ -36,6 +36,7 @@
 import java.awt.MouseInfo;
 import java.awt.Point;
 import java.awt.Rectangle;
+import java.awt.Window;
 import java.awt.event.ContainerEvent;
 import java.awt.event.ContainerListener;
 import java.awt.image.BufferedImage;
@@ -43,16 +44,19 @@
 import java.beans.PropertyChangeEvent;
 import java.beans.PropertyChangeListener;
 import java.security.AccessController;
+import javax.swing.JComponent;
 
 import javax.swing.JLayeredPane;
 import javax.swing.JPanel;
 import javax.swing.JRootPane;
 import javax.swing.LayoutFocusTraversalPolicy;
+import javax.swing.RepaintManager;
 import javax.swing.RootPaneContainer;
 import javax.swing.SwingUtilities;
 
 import sun.awt.LightweightFrame;
 import sun.security.action.GetPropertyAction;
+import sun.swing.SwingUtilities2.RepaintListener;
 
 /**
  * The frame serves as a lightweight container which paints its content
@@ -90,6 +94,7 @@
     private int[] copyBuffer;
 
     private PropertyChangeListener layoutSizeListener;
+    private RepaintListener repaintListener;
 
     static {
         SwingAccessor.setJLightweightFrameAccessor(new SwingAccessor.JLightweightFrameAccessor() {
@@ -131,6 +136,30 @@
                 }
             }
         };
+
+        repaintListener = (JComponent c, int x, int y, int w, int h) -> {
+            Window jlf = SwingUtilities.getWindowAncestor(c);
+            if (jlf != JLightweightFrame.this) {
+                return;
+            }
+            Point p = SwingUtilities.convertPoint(c, x, y, jlf);
+            Rectangle r = new Rectangle(p.x, p.y, w, h).intersection(
+                    new Rectangle(0, 0, bbImage.getWidth(), bbImage.getHeight()));
+
+            if (!r.isEmpty()) {
+                notifyImageUpdated(r.x, r.y, r.width, r.height);
+            }
+        };
+
+        SwingAccessor.getRepaintManagerAccessor().addRepaintListener(
+            RepaintManager.currentManager(this), repaintListener);
+    }
+
+    @Override
+    public void dispose() {
+        SwingAccessor.getRepaintManagerAccessor().removeRepaintListener(
+            RepaintManager.currentManager(this), repaintListener);
+        super.dispose();
     }
 
     /**
@@ -210,6 +239,13 @@
         }
     }
 
+    private void notifyImageUpdated(int x, int y, int width, int height) {
+        if (copyBufferEnabled) {
+            syncCopyBuffer(false, x, y, width, height);
+        }
+        content.imageUpdated(x, y, width, height);
+    }
+
     @SuppressWarnings("serial") // anonymous class inside
     private void initInterior() {
         contentPane = new JPanel() {
@@ -233,10 +269,7 @@
                     EventQueue.invokeLater(new Runnable() {
                         @Override
                         public void run() {
-                            if (copyBufferEnabled) {
-                                syncCopyBuffer(false, clip.x, clip.y, clip.width, clip.height);
-                            }
-                            content.imageUpdated(clip.x, clip.y, clip.width, clip.height);
+                            notifyImageUpdated(clip.x, clip.y, clip.width, clip.height);
                         }
                     });
                 } finally {
--- a/jdk/src/share/classes/sun/swing/SwingAccessor.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/swing/SwingAccessor.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 import sun.misc.Unsafe;
 
 import java.awt.Point;
+import javax.swing.RepaintManager;
 
 import javax.swing.text.JTextComponent;
 import javax.swing.TransferHandler;
@@ -82,6 +83,14 @@
     }
 
     /**
+     * An accessor for the RepaintManager class.
+     */
+    public interface RepaintManagerAccessor {
+        void addRepaintListener(RepaintManager rm, SwingUtilities2.RepaintListener l);
+        void removeRepaintListener(RepaintManager rm, SwingUtilities2.RepaintListener l);
+    }
+
+    /**
      * The javax.swing.text.JTextComponent class accessor object.
      */
     private static JTextComponentAccessor jtextComponentAccessor;
@@ -120,6 +129,31 @@
      * Retrieve the accessor object for the JLightweightFrame class
      */
     public static JLightweightFrameAccessor getJLightweightFrameAccessor() {
+        if (jLightweightFrameAccessor == null) {
+            unsafe.ensureClassInitialized(JLightweightFrame.class);
+        }
         return jLightweightFrameAccessor;
     }
+
+    /**
+     * The RepaintManager class accessor object.
+     */
+    private static RepaintManagerAccessor repaintManagerAccessor;
+
+    /**
+     * Set an accessor object for the RepaintManager class.
+     */
+    public static void setRepaintManagerAccessor(RepaintManagerAccessor accessor) {
+        repaintManagerAccessor = accessor;
+    }
+
+    /**
+     * Retrieve the accessor object for the RepaintManager class.
+     */
+    public static RepaintManagerAccessor getRepaintManagerAccessor() {
+        if (repaintManagerAccessor == null) {
+            unsafe.ensureClassInitialized(RepaintManager.class);
+        }
+        return repaintManagerAccessor;
+    }
 }
--- a/jdk/src/share/classes/sun/swing/SwingLazyValue.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/swing/SwingLazyValue.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,9 +26,6 @@
 
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Method;
-import java.lang.reflect.AccessibleObject;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
 import javax.swing.UIDefaults;
 import sun.reflect.misc.ReflectUtil;
 
@@ -69,12 +66,10 @@
             if (methodName != null) {
                 Class<?>[] types = getClassArray(args);
                 Method m = c.getMethod(methodName, types);
-                makeAccessible(m);
                 return m.invoke(c, args);
             } else {
                 Class<?>[] types = getClassArray(args);
                 Constructor<?> constructor = c.getConstructor(types);
-                makeAccessible(constructor);
                 return constructor.newInstance(args);
             }
         } catch (Exception e) {
@@ -87,15 +82,6 @@
         return null;
     }
 
-    private void makeAccessible(final AccessibleObject object) {
-        AccessController.doPrivileged(new PrivilegedAction<Void>() {
-            public Void run() {
-                object.setAccessible(true);
-                return null;
-            }
-        });
-    }
-
     private Class<?>[] getClassArray(Object[] args) {
         Class<?>[] types = null;
         if (args!=null) {
--- a/jdk/src/share/classes/sun/swing/SwingUtilities2.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/swing/SwingUtilities2.java	Wed Jul 05 19:33:51 2017 +0200
@@ -80,6 +80,9 @@
     public static final Object LAF_STATE_KEY =
             new StringBuffer("LookAndFeel State");
 
+    public static final Object MENU_SELECTION_MANAGER_LISTENER_KEY =
+            new StringBuffer("MenuSelectionManager listener key");
+
     // Maintain a cache of CACHE_SIZE fonts and the left side bearing
      // of the characters falling into the range MIN_CHAR_INDEX to
      // MAX_CHAR_INDEX. The values in fontCache are created as needed.
@@ -189,7 +192,6 @@
         new StringUIClientPropertyKey ("maxTextOffset");
 
     // security stuff
-    private static Field inputEvent_CanAccessSystemClipboard_Field = null;
     private static final String UntrustedClipboardAccess =
         "UNTRUSTED_CLIPBOARD_ACCESS_KEY";
 
@@ -1263,41 +1265,6 @@
     }
 
     /**
-     * returns canAccessSystemClipboard field from InputEvent
-     *
-     * @param ie InputEvent to get the field from
-     */
-    private static synchronized boolean inputEvent_canAccessSystemClipboard(InputEvent ie) {
-        if (inputEvent_CanAccessSystemClipboard_Field == null) {
-            inputEvent_CanAccessSystemClipboard_Field =
-                AccessController.doPrivileged(
-                    new java.security.PrivilegedAction<Field>() {
-                        public Field run() {
-                            try {
-                                Field field = InputEvent.class.
-                                    getDeclaredField("canAccessSystemClipboard");
-                                field.setAccessible(true);
-                                return field;
-                            } catch (SecurityException e) {
-                            } catch (NoSuchFieldException e) {
-                            }
-                            return null;
-                        }
-                    });
-        }
-        if (inputEvent_CanAccessSystemClipboard_Field == null) {
-            return false;
-        }
-        boolean ret = false;
-        try {
-            ret = inputEvent_CanAccessSystemClipboard_Field.
-                getBoolean(ie);
-        } catch(IllegalAccessException e) {
-        }
-        return ret;
-    }
-
-    /**
      * Returns true if the given event is corrent gesture for
      * accessing clipboard
      *
@@ -1350,7 +1317,8 @@
              */
             if (e instanceof InputEvent
                 && (! checkGesture || isAccessClipboardGesture((InputEvent)e))) {
-                return inputEvent_canAccessSystemClipboard((InputEvent)e);
+                return AWTAccessor.getInputEventAccessor().
+                        canAccessSystemClipboard((InputEvent) e);
             } else {
                 return false;
             }
@@ -1966,4 +1934,11 @@
         }
         return path;
     }
+
+    /**
+     * Used to listen to "blit" repaints in RepaintManager.
+     */
+    public interface RepaintListener {
+        void repaintPerformed(JComponent c, int x, int y, int w, int h);
+    }
 }
--- a/jdk/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/classes/sun/swing/plaf/synth/SynthFileChooserUIImpl.java	Wed Jul 05 19:33:51 2017 +0200
@@ -927,9 +927,70 @@
      * Data model for a type-face selection combo-box.
      */
     @SuppressWarnings("serial") // JDK-implementation class
-    protected class FilterComboBoxModel extends AbstractFilterComboBoxModel {
-        protected JFileChooser getFileChooser() {
-            return SynthFileChooserUIImpl.this.getFileChooser();
+    protected class FilterComboBoxModel extends AbstractListModel<FileFilter> implements ComboBoxModel<FileFilter>,
+            PropertyChangeListener {
+        protected FileFilter[] filters;
+        protected FilterComboBoxModel() {
+            super();
+            filters = getFileChooser().getChoosableFileFilters();
+        }
+
+        public void propertyChange(PropertyChangeEvent e) {
+            String prop = e.getPropertyName();
+            if(prop == JFileChooser.CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY) {
+                filters = (FileFilter[]) e.getNewValue();
+                fireContentsChanged(this, -1, -1);
+            } else if (prop == JFileChooser.FILE_FILTER_CHANGED_PROPERTY) {
+                fireContentsChanged(this, -1, -1);
+            }
+        }
+
+        public void setSelectedItem(Object filter) {
+            if(filter != null) {
+                getFileChooser().setFileFilter((FileFilter) filter);
+                fireContentsChanged(this, -1, -1);
+            }
+        }
+
+        public Object getSelectedItem() {
+            // Ensure that the current filter is in the list.
+            // NOTE: we shouldnt' have to do this, since JFileChooser adds
+            // the filter to the choosable filters list when the filter
+            // is set. Lets be paranoid just in case someone overrides
+            // setFileFilter in JFileChooser.
+            FileFilter currentFilter = getFileChooser().getFileFilter();
+            boolean found = false;
+            if(currentFilter != null) {
+                for (FileFilter filter : filters) {
+                    if (filter == currentFilter) {
+                        found = true;
+                    }
+                }
+                if(found == false) {
+                    getFileChooser().addChoosableFileFilter(currentFilter);
+                }
+            }
+            return getFileChooser().getFileFilter();
+        }
+
+        public int getSize() {
+            if(filters != null) {
+                return filters.length;
+            } else {
+                return 0;
+            }
+        }
+
+        public FileFilter getElementAt(int index) {
+            if(index > getSize() - 1) {
+                // This shouldn't happen. Try to recover gracefully.
+                return getFileChooser().getFileFilter();
+            }
+            if(filters != null) {
+                return filters[index];
+            } else {
+                return null;
+            }
         }
     }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/tools/serialver/resources/serialver.properties	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,20 @@
+SerialVersionInspector=Serial Version Inspector
+File=File
+Exit=Exit
+Show=Show
+FullClassName=Full Class Name:
+SerialVersion=Serial Version:
+NotSerializable=\
+	Class {0} is not Serializable.
+ClassNotFound=\
+	Class {0} not found.
+error.parsing.classpath=\
+	Error parsing classpath {0}.
+error.missing.classpath=\
+	Missing argument for -classpath option
+invalid.flag=\
+	Invalid flag {0}.
+ignoring.classes=\
+	Cannot specify class arguments with the -show option
+usage=\
+	use: serialver [-classpath classpath] [-show] [classname...]
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/tools/serialver/resources/serialver_ja.properties	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,13 @@
+SerialVersionInspector=\u30B7\u30EA\u30A2\u30EB\u30FB\u30D0\u30FC\u30B8\u30E7\u30F3\u30FB\u30A4\u30F3\u30B9\u30DA\u30AF\u30BF
+File=\u30D5\u30A1\u30A4\u30EB
+Exit=\u7D42\u4E86
+Show=\u8868\u793A
+FullClassName=\u5B8C\u5168\u30AF\u30E9\u30B9\u540D:
+SerialVersion=\u30B7\u30EA\u30A2\u30EB\u30FB\u30D0\u30FC\u30B8\u30E7\u30F3:
+NotSerializable=\u30AF\u30E9\u30B9{0}\u306F\u76F4\u5217\u5316\u3067\u304D\u307E\u305B\u3093\u3002
+ClassNotFound=\u30AF\u30E9\u30B9{0}\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002
+error.parsing.classpath=\u30AF\u30E9\u30B9\u30D1\u30B9{0}\u306E\u89E3\u6790\u30A8\u30E9\u30FC\u3067\u3059\u3002
+error.missing.classpath=-classpath\u30AA\u30D7\u30B7\u30E7\u30F3\u306E\u5F15\u6570\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093
+invalid.flag=\u7121\u52B9\u306A\u30D5\u30E9\u30B0{0}\u3002
+ignoring.classes=-show\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u6301\u3064\u30AF\u30E9\u30B9\u5F15\u6570\u3092\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093
+usage=\u4F7F\u7528\u65B9\u6CD5: serialver [-classpath classpath] [-show] [classname...]
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/tools/serialver/resources/serialver_zh_CN.properties	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,13 @@
+SerialVersionInspector=\u5E8F\u5217\u7248\u672C\u68C0\u67E5\u5668
+File=\u6587\u4EF6
+Exit=\u9000\u51FA
+Show=\u663E\u793A
+FullClassName=\u5B8C\u6574\u7684\u7C7B\u540D:
+SerialVersion=\u5E8F\u5217\u7248\u672C:
+NotSerializable=\u7C7B{0}\u65E0\u6CD5\u5E8F\u5217\u5316\u3002
+ClassNotFound=\u627E\u4E0D\u5230\u7C7B{0}\u3002
+error.parsing.classpath=\u89E3\u6790\u7C7B\u8DEF\u5F84 {0} \u65F6\u51FA\u9519\u3002
+error.missing.classpath=\u7F3A\u5C11 -classpath \u9009\u9879\u7684\u53C2\u6570
+invalid.flag=\u65E0\u6548\u6807\u8BB0{0}\u3002
+ignoring.classes=\u65E0\u6CD5\u4F7F\u7528 -show \u9009\u9879\u6307\u5B9A\u7C7B\u53C2\u6570
+usage=\u7528\u6CD5: serialver [-classpath \u7C7B\u8DEF\u5F84] [-show] [\u7C7B\u540D\u79F0...]
--- a/jdk/src/share/classes/sun/tools/serialver/serialver.properties	Tue Mar 25 12:31:49 2014 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,20 +0,0 @@
-SerialVersionInspector=Serial Version Inspector
-File=File
-Exit=Exit
-Show=Show
-FullClassName=Full Class Name:
-SerialVersion=Serial Version:
-NotSerializable=\
-	Class {0} is not Serializable.
-ClassNotFound=\
-	Class {0} not found.
-error.parsing.classpath=\
-	Error parsing classpath {0}.
-error.missing.classpath=\
-	Missing argument for -classpath option
-invalid.flag=\
-	Invalid flag {0}.
-ignoring.classes=\
-	Cannot specify class arguments with the -show option
-usage=\
-	use: serialver [-classpath classpath] [-show] [classname...]
--- a/jdk/src/share/classes/sun/tools/serialver/serialver_ja.properties	Tue Mar 25 12:31:49 2014 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,13 +0,0 @@
-SerialVersionInspector=\u30B7\u30EA\u30A2\u30EB\u30FB\u30D0\u30FC\u30B8\u30E7\u30F3\u30FB\u30A4\u30F3\u30B9\u30DA\u30AF\u30BF
-File=\u30D5\u30A1\u30A4\u30EB
-Exit=\u7D42\u4E86
-Show=\u8868\u793A
-FullClassName=\u5B8C\u5168\u30AF\u30E9\u30B9\u540D:
-SerialVersion=\u30B7\u30EA\u30A2\u30EB\u30FB\u30D0\u30FC\u30B8\u30E7\u30F3:
-NotSerializable=\u30AF\u30E9\u30B9{0}\u306F\u76F4\u5217\u5316\u3067\u304D\u307E\u305B\u3093\u3002
-ClassNotFound=\u30AF\u30E9\u30B9{0}\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002
-error.parsing.classpath=\u30AF\u30E9\u30B9\u30D1\u30B9{0}\u306E\u89E3\u6790\u30A8\u30E9\u30FC\u3067\u3059\u3002
-error.missing.classpath=-classpath\u30AA\u30D7\u30B7\u30E7\u30F3\u306E\u5F15\u6570\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093
-invalid.flag=\u7121\u52B9\u306A\u30D5\u30E9\u30B0{0}\u3002
-ignoring.classes=-show\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u6301\u3064\u30AF\u30E9\u30B9\u5F15\u6570\u3092\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093
-usage=\u4F7F\u7528\u65B9\u6CD5: serialver [-classpath classpath] [-show] [classname...]
--- a/jdk/src/share/classes/sun/tools/serialver/serialver_zh_CN.properties	Tue Mar 25 12:31:49 2014 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,13 +0,0 @@
-SerialVersionInspector=\u5E8F\u5217\u7248\u672C\u68C0\u67E5\u5668
-File=\u6587\u4EF6
-Exit=\u9000\u51FA
-Show=\u663E\u793A
-FullClassName=\u5B8C\u6574\u7684\u7C7B\u540D:
-SerialVersion=\u5E8F\u5217\u7248\u672C:
-NotSerializable=\u7C7B{0}\u65E0\u6CD5\u5E8F\u5217\u5316\u3002
-ClassNotFound=\u627E\u4E0D\u5230\u7C7B{0}\u3002
-error.parsing.classpath=\u89E3\u6790\u7C7B\u8DEF\u5F84 {0} \u65F6\u51FA\u9519\u3002
-error.missing.classpath=\u7F3A\u5C11 -classpath \u9009\u9879\u7684\u53C2\u6570
-invalid.flag=\u65E0\u6548\u6807\u8BB0{0}\u3002
-ignoring.classes=\u65E0\u6CD5\u4F7F\u7528 -show \u9009\u9879\u6307\u5B9A\u7C7B\u53C2\u6570
-usage=\u7528\u6CD5: serialver [-classpath \u7C7B\u8DEF\u5F84] [-show] [\u7C7B\u540D\u79F0...]
--- a/jdk/src/share/instrument/FileSystemSupport.h	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/instrument/FileSystemSupport.h	Wed Jul 05 19:33:51 2017 +0200
@@ -65,9 +65,3 @@
  * Resolve the child pathname string against the parent.
  */
 char* resolve(const char* parent, const char* child);
-
-/**
- * Convert a pathname to canonical form.
- * -- compiled in from src/<platform>/native/java/io/canonicalize_md.c
- */
-int canonicalize(char *original, char *resolved, int len);
--- a/jdk/src/share/instrument/InvocationAdapter.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/instrument/InvocationAdapter.c	Wed Jul 05 19:33:51 2017 +0200
@@ -669,6 +669,13 @@
     jplis_assert((void*)res != (void*)NULL);     \
 }
 
+/**
+ * Convert a pathname to canonical form.
+ * This method is exported from libjava.
+ */
+extern int
+Canonicalize(JNIEnv *unused, char *orig, char *out, int len);
+
 
 /*
  * This function takes the value of the Boot-Class-Path attribute,
@@ -790,7 +797,8 @@
             char* resolved;
 
             if (!haveBasePath) {
-                if (canonicalize((char*)jarfile, canonicalPath, sizeof(canonicalPath)) != 0) {
+                /* Use NULL as the JNIEnv since we know that Canonicalize does not use it. */
+                if (Canonicalize(NULL, (char*)jarfile, canonicalPath, sizeof(canonicalPath)) != 0) {
                     fprintf(stderr, "WARNING: unable to canonicalize %s\n", jarfile);
                     free(path);
                     continue;
--- a/jdk/src/share/native/com/sun/java/util/jar/pack/bands.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/native/com/sun/java/util/jar/pack/bands.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -288,7 +288,7 @@
   { e_##name,  #name, /*debug only*/ \
     cspec, ix }
 
-const band_init all_band_inits[] = {
+const band_init all_band_inits[BAND_LIMIT+1] = {
 //BAND_INIT(archive_magic, BYTE1_spec, 0),
 //BAND_INIT(archive_header, UNSIGNED5_spec, 0),
 //BAND_INIT(band_headers, BYTE1_spec, 0),
@@ -448,14 +448,8 @@
   BAND_INIT(file_modtime, DELTA5_spec, 0),
   BAND_INIT(file_options, UNSIGNED5_spec, 0),
 //BAND_INIT(file_bits, BYTE1_spec, 0),
-#ifndef PRODUCT
-  { 0, 0, 0, 0 }
-#else
-  { 0, 0 }
-#endif
+  { 0, NULL, 0, 0 }
 };
-#define NUM_BAND_INITS \
-        (sizeof(all_band_inits)/sizeof(all_band_inits[0]))
 
 band* band::makeBands(unpacker* u) {
   band* tmp_all_bands = U_NEW(band, BAND_LIMIT);
--- a/jdk/src/share/native/common/jni_util.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/native/common/jni_util.c	Wed Jul 05 19:33:51 2017 +0200
@@ -834,12 +834,12 @@
 /*
  * Export the platform dependent path canonicalization so that
  * VM can find it when loading system classes.
- *
+ * This function is also used by the instrumentation agent.
  */
 extern int canonicalize(char *path, const char *out, int len);
 
 JNIEXPORT int
-Canonicalize(JNIEnv *env, char *orig, char *out, int len)
+Canonicalize(JNIEnv *unused, char *orig, char *out, int len)
 {
     /* canonicalize an already natived path */
     return canonicalize(orig, out, len);
--- a/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1106,6 +1106,7 @@
     if (ddata == NULL) {
         /* Need to store it back into the array */
         if (storeRasterArray(env, srcRasterP, dstRasterP, dst) < 0) {
+            (*env)->ExceptionClear(env); // Could not store the array, try another way
             retStatus = awt_setPixels(env, dstRasterP, mlib_ImageGetData(dst));
         }
     }
@@ -2014,6 +2015,7 @@
 
     jpixels = (*env)->NewIntArray(env, nbytes);
     if (JNU_IsNull(env, jpixels)) {
+        (*env)->ExceptionClear(env);
         JNU_ThrowOutOfMemoryError(env, "Out of Memory");
         return -1;
     }
@@ -2079,6 +2081,7 @@
 
     jpixels = (*env)->NewIntArray(env, nbytes);
     if (JNU_IsNull(env, jpixels)) {
+        (*env)->ExceptionClear(env);
         JNU_ThrowOutOfMemoryError(env, "Out of Memory");
         return -1;
     }
@@ -2775,21 +2778,14 @@
 
     /* Need to grab the lookup tables.  Right now only bytes */
     rgb = (int *) (*env)->GetPrimitiveArrayCritical(env, cmP->jrgb, NULL);
+    CHECK_NULL_RETURN(rgb, -1);
 
     /* Interleaved with shared data */
     dataP = (void *) (*env)->GetPrimitiveArrayCritical(env,
                                                        rasterP->jdata, NULL);
-    if (rgb == NULL || dataP == NULL) {
+    if (dataP == NULL) {
         /* Release the lookup tables */
-        if (rgb) {
-            (*env)->ReleasePrimitiveArrayCritical(env, cmP->jrgb, rgb,
-                                                  JNI_ABORT);
-        }
-        if (dataP) {
-            (*env)->ReleasePrimitiveArrayCritical(env,
-                                                  rasterP->jdata, dataP,
-                                                  JNI_ABORT);
-        }
+        (*env)->ReleasePrimitiveArrayCritical(env, cmP->jrgb, rgb, JNI_ABORT);
         return -1;
     }
 
--- a/jdk/src/share/native/sun/awt/splashscreen/java_awt_SplashScreen.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/native/sun/awt/splashscreen/java_awt_SplashScreen.c	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,8 +24,9 @@
  */
 
 #include "splashscreen_impl.h"
+#include <jlong_md.h>
 #include <jni.h>
-#include <jlong_md.h>
+#include <jni_util.h>
 #include <sizecalc.h>
 
 JNIEXPORT jint JNICALL
@@ -212,8 +213,9 @@
     if (!splash) {
         return JNI_FALSE;
     }
+    pBytes = (*env)->GetByteArrayElements(env, data, NULL);
+    CHECK_NULL_RETURN(pBytes, JNI_FALSE);
     size = (*env)->GetArrayLength(env, data);
-    pBytes = (*env)->GetByteArrayElements(env, data, NULL);
     rc = SplashLoadMemory(pBytes, size);
     (*env)->ReleaseByteArrayElements(env, data, pBytes, JNI_ABORT);
     return rc ? JNI_TRUE : JNI_FALSE;
--- a/jdk/src/share/native/sun/awt/splashscreen/splashscreen_gfx_impl.h	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/native/sun/awt/splashscreen/splashscreen_gfx_impl.h	Wed Jul 05 19:33:51 2017 +0200
@@ -189,7 +189,11 @@
             PUT(rgbquad_t, ptr, value);
             break;
         case 3:                /* not supported, LSB or MSB should always be specified */
-            *(int *) 0 = 0;    /* crash */
+            PUT(byte_t, ptr, 0xff); /* Put a stub value */
+            INCP(byte_t, ptr);
+            PUT(byte_t, ptr, 0xff);
+            INCP(byte_t, ptr);
+            PUT(byte_t, ptr, 0xff);
             break;
         case 2:
             PUT(word_t, ptr, value);
@@ -253,7 +257,7 @@
             value = GET(rgbquad_t, ptr);
             break;
         case 3:                /* not supported, LSB or MSB should always be specified */
-            *(int *) 0 = 0;
+            value = 0xFFFFFFFF; /*return a stub value */
             break;
         case 2:
             value = (rgbquad_t) GET(word_t, ptr);
--- a/jdk/src/share/native/sun/awt/splashscreen/splashscreen_png.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/native/sun/awt/splashscreen/splashscreen_png.c	Wed Jul 05 19:33:51 2017 +0200
@@ -25,7 +25,7 @@
 
 #include "splashscreen_impl.h"
 
-#include "../libpng/png.h"
+#include <png.h>
 
 #include <setjmp.h>
 
--- a/jdk/src/share/native/sun/java2d/opengl/OGLContext.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/native/sun/java2d/opengl/OGLContext.c	Wed Jul 05 19:33:51 2017 +0200
@@ -38,6 +38,8 @@
 #include "GraphicsPrimitiveMgr.h"
 #include "Region.h"
 
+#include "jvm.h"
+
 /**
  * The following methods are implemented in the windowing system (i.e. GLX
  * and WGL) source files.
--- a/jdk/src/share/native/sun/security/pkcs11/j2secmod.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/share/native/sun/security/pkcs11/j2secmod.c	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,20 +30,27 @@
 // #define SECMOD_DEBUG
 
 #include "j2secmod.h"
+#include "jni_util.h"
 
 
 JNIEXPORT jboolean JNICALL Java_sun_security_pkcs11_Secmod_nssVersionCheck
   (JNIEnv *env, jclass thisClass, jlong jHandle, jstring jVersion)
 {
-    const char *requiredVersion = (*env)->GetStringUTFChars(env, jVersion, NULL);
-    int res;
-    FPTR_VersionCheck versionCheck =
-        (FPTR_VersionCheck)findFunction(env, jHandle, "NSS_VersionCheck");
+    int res = 0;
+    FPTR_VersionCheck versionCheck;
+    const char *requiredVersion;
 
+    versionCheck = (FPTR_VersionCheck)findFunction(env, jHandle,
+        "NSS_VersionCheck");
     if (versionCheck == NULL) {
         return JNI_FALSE;
     }
 
+    requiredVersion = (*env)->GetStringUTFChars(env, jVersion, NULL);
+    if (requiredVersion == NULL)  {
+        return JNI_FALSE;
+    }
+
     res = versionCheck(requiredVersion);
     dprintf2("-version >=%s: %d\n", requiredVersion, res);
     (*env)->ReleaseStringUTFChars(env, jVersion, requiredVersion);
@@ -59,55 +66,73 @@
 JNIEXPORT jboolean JNICALL Java_sun_security_pkcs11_Secmod_nssInitialize
   (JNIEnv *env, jclass thisClass, jstring jFunctionName, jlong jHandle, jstring jConfigDir, jboolean jNssOptimizeSpace)
 {
-    const char *functionName =
-        (*env)->GetStringUTFChars(env, jFunctionName, NULL);
-    const char *configDir = (jConfigDir == NULL)
-        ? NULL : (*env)->GetStringUTFChars(env, jConfigDir, NULL);
+    int res = 0;
     FPTR_Initialize initialize =
         (FPTR_Initialize)findFunction(env, jHandle, "NSS_Initialize");
-    int res = 0;
     unsigned int flags = 0x00;
+    const char *configDir = NULL;
+    const char *functionName = NULL;
+
+    /* If we cannot initialize, exit now */
+    if (initialize == NULL) {
+        res = 1;
+        goto cleanup;
+    }
+
+    functionName = (*env)->GetStringUTFChars(env, jFunctionName, NULL);
+    if (functionName == NULL) {
+        res = 1;
+        goto cleanup;
+    }
+
+    if (jConfigDir != NULL) {
+        configDir = (*env)->GetStringUTFChars(env, jConfigDir, NULL);
+        if (!configDir) {
+            res = 1;
+            goto cleanup;
+        }
+    }
 
     if (jNssOptimizeSpace == JNI_TRUE) {
         flags = 0x20; // NSS_INIT_OPTIMIZESPACE flag
     }
 
-    if (initialize != NULL) {
-        /*
-         * If the NSS_Init function is requested then call NSS_Initialize to
-         * open the Cert, Key and Security Module databases, read only.
-         */
-        if (strcmp("NSS_Init", functionName) == 0) {
-            flags = flags | 0x01; // NSS_INIT_READONLY flag
-            res = initialize(configDir, "", "", "secmod.db", flags);
+    /*
+     * If the NSS_Init function is requested then call NSS_Initialize to
+     * open the Cert, Key and Security Module databases, read only.
+     */
+    if (strcmp("NSS_Init", functionName) == 0) {
+        flags = flags | 0x01; // NSS_INIT_READONLY flag
+        res = initialize(configDir, "", "", "secmod.db", flags);
 
-        /*
-         * If the NSS_InitReadWrite function is requested then call
-         * NSS_Initialize to open the Cert, Key and Security Module databases,
-         * read/write.
-         */
-        } else if (strcmp("NSS_InitReadWrite", functionName) == 0) {
-            res = initialize(configDir, "", "", "secmod.db", flags);
+    /*
+     * If the NSS_InitReadWrite function is requested then call
+     * NSS_Initialize to open the Cert, Key and Security Module databases,
+     * read/write.
+     */
+    } else if (strcmp("NSS_InitReadWrite", functionName) == 0) {
+        res = initialize(configDir, "", "", "secmod.db", flags);
 
-        /*
-         * If the NSS_NoDB_Init function is requested then call
-         * NSS_Initialize without creating Cert, Key or Security Module
-         * databases.
-         */
-        } else if (strcmp("NSS_NoDB_Init", functionName) == 0) {
-            flags = flags | 0x02  // NSS_INIT_NOCERTDB flag
-                          | 0x04  // NSS_INIT_NOMODDB flag
-                          | 0x08  // NSS_INIT_FORCEOPEN flag
-                          | 0x10; // NSS_INIT_NOROOTINIT flag
-            res = initialize("", "", "", "", flags);
+    /*
+     * If the NSS_NoDB_Init function is requested then call
+     * NSS_Initialize without creating Cert, Key or Security Module
+     * databases.
+     */
+    } else if (strcmp("NSS_NoDB_Init", functionName) == 0) {
+        flags = flags | 0x02  // NSS_INIT_NOCERTDB flag
+                      | 0x04  // NSS_INIT_NOMODDB flag
+                      | 0x08  // NSS_INIT_FORCEOPEN flag
+                      | 0x10; // NSS_INIT_NOROOTINIT flag
+        res = initialize("", "", "", "", flags);
 
-        } else {
-            res = 2;
-        }
     } else {
-        res = 1;
+        res = 2;
     }
-    (*env)->ReleaseStringUTFChars(env, jFunctionName, functionName);
+
+cleanup:
+    if (functionName != NULL) {
+        (*env)->ReleaseStringUTFChars(env, jFunctionName, functionName);
+    }
     if (configDir != NULL) {
         (*env)->ReleaseStringUTFChars(env, jConfigDir, configDir);
     }
@@ -142,13 +167,30 @@
     }
 
     jListClass = (*env)->FindClass(env, "java/util/ArrayList");
+    if (jListClass == NULL) {
+        return NULL;
+    }
     jListConstructor = (*env)->GetMethodID(env, jListClass, "<init>", "()V");
+    if (jListConstructor == NULL) {
+        return NULL;
+    }
     jAdd = (*env)->GetMethodID(env, jListClass, "add", "(Ljava/lang/Object;)Z");
+    if (jAdd == NULL) {
+        return NULL;
+    }
     jList = (*env)->NewObject(env, jListClass, jListConstructor);
-
+    if (jList == NULL) {
+        return NULL;
+    }
     jModuleClass = (*env)->FindClass(env, "sun/security/pkcs11/Secmod$Module");
+    if (jModuleClass == NULL) {
+        return NULL;
+    }
     jModuleConstructor = (*env)->GetMethodID(env, jModuleClass, "<init>",
         "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZI)V");
+    if (jModuleConstructor == NULL) {
+        return NULL;
+    }
 
     while (list != NULL) {
         module = list->module;
@@ -160,16 +202,28 @@
         dprintf1("-internal: %d\n", module->internal);
         dprintf1("-fips: %d\n", module->isFIPS);
         jCommonName = (*env)->NewStringUTF(env, module->commonName);
+        if (jCommonName == NULL) {
+            return NULL;
+        }
         if (module->dllName == NULL) {
             jDllName = NULL;
         } else {
             jDllName = (*env)->NewStringUTF(env, module->dllName);
+            if (jDllName == NULL) {
+                return NULL;
+            }
         }
         jFIPS = module->isFIPS;
         for (i = 0; i < module->slotCount; i++ ) {
             jModule = (*env)->NewObject(env, jModuleClass, jModuleConstructor,
                 jLibDir, jDllName, jCommonName, jFIPS, i);
+            if (jModule == NULL) {
+                return NULL;
+            }
             (*env)->CallVoidMethod(env, jList, jAdd, jModule);
+            if ((*env)->ExceptionCheck(env)) {
+                return NULL;
+            }
         }
         list = list->next;
     }
--- a/jdk/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -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
@@ -24,7 +24,6 @@
  */
 package sun.awt.X11;
 
-import java.awt.Dialog;
 import java.awt.FileDialog;
 import java.awt.peer.FileDialogPeer;
 import java.io.File;
@@ -36,15 +35,15 @@
  *
  * @author Costantino Cerbo (c.cerbo@gmail.com)
  */
-class GtkFileDialogPeer extends XDialogPeer implements FileDialogPeer {
+final class GtkFileDialogPeer extends XDialogPeer implements FileDialogPeer {
 
-    private FileDialog fd;
+    private final FileDialog fd;
 
     // A pointer to the native GTK FileChooser widget
     private volatile long widget = 0L;
 
-    public GtkFileDialogPeer(FileDialog fd) {
-        super((Dialog) fd);
+    GtkFileDialogPeer(FileDialog fd) {
+        super(fd);
         this.fd = fd;
     }
 
@@ -172,9 +171,7 @@
                 dirname = file.getParent();
             }
         }
-        GtkFileDialogPeer.this.run(fd.getTitle(), fd.getMode(), dirname,
-                                   filename, fd.getFilenameFilter(),
-                                   fd.isMultipleMode(), fd.getX(), fd.getY());
+        run(fd.getTitle(), fd.getMode(), dirname, filename,
+            fd.getFilenameFilter(), fd.isMultipleMode(), fd.getX(), fd.getY());
     }
-
 }
--- a/jdk/src/solaris/classes/sun/awt/X11/XAWTFormatter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XAWTFormatter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -43,8 +43,7 @@
 
     // Line separator string.  This is the value of the line.separator
     // property at the moment that the SimpleFormatter was created.
-    private String lineSeparator = java.security.AccessController.doPrivileged(
-               new sun.security.action.GetPropertyAction("line.separator"));
+    private String lineSeparator = System.lineSeparator();
 
     boolean displayFullRecord = false;
     boolean useANSI = false;
--- a/jdk/src/solaris/classes/sun/awt/X11/XDataTransferer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XDataTransferer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -56,6 +56,7 @@
 import sun.awt.datatransfer.ToolkitThreadBlockedHandler;
 
 import java.io.ByteArrayOutputStream;
+import java.util.stream.Stream;
 
 /**
  * Platform-specific support for the data transfer subsystem.
@@ -77,11 +78,9 @@
 
     private static XDataTransferer transferer;
 
-    static XDataTransferer getInstanceImpl() {
-        synchronized (XDataTransferer.class) {
-            if (transferer == null) {
-                transferer = new XDataTransferer();
-            }
+    static synchronized XDataTransferer getInstanceImpl() {
+        if (transferer == null) {
+            transferer = new XDataTransferer();
         }
         return transferer;
     }
@@ -242,6 +241,7 @@
         }
     }
 
+    @Override
     protected String[] dragQueryFile(byte[] bytes) {
         XToolkit.awtLock();
         try {
@@ -252,8 +252,8 @@
         }
     }
 
+    @Override
     protected URI[] dragQueryURIs(InputStream stream,
-                                  byte[] bytes,
                                   long format,
                                   Transferable localeTransferable)
       throws IOException {
@@ -281,7 +281,7 @@
         try {
             reader = new BufferedReader(new InputStreamReader(stream, charset));
             String line;
-            ArrayList<URI> uriList = new ArrayList<URI>();
+            ArrayList<URI> uriList = new ArrayList<>();
             URI uri;
             while ((line = reader.readLine()) != null) {
                 try {
@@ -329,8 +329,9 @@
      * a valid MIME and return a list of flavors to which the data in this MIME
      * type can be translated by the Data Transfer subsystem.
      */
-    public List <DataFlavor> getPlatformMappingsForNative(String nat) {
-        List <DataFlavor> flavors = new ArrayList();
+    @Override
+    public List<DataFlavor> getPlatformMappingsForNative(String nat) {
+        List<DataFlavor> flavors = new ArrayList<>();
 
         if (nat == null) {
             return flavors;
@@ -390,8 +391,9 @@
      * MIME types to which the data in this flavor can be translated by the Data
      * Transfer subsystem.
      */
-    public List getPlatformMappingsForFlavor(DataFlavor df) {
-        List natives = new ArrayList(1);
+    @Override
+    public List<String> getPlatformMappingsForFlavor(DataFlavor df) {
+        List<String> natives = new ArrayList<>(1);
 
         if (df == null) {
             return natives;
@@ -410,25 +412,22 @@
         if (df.getRepresentationClass() != null &&
             (df.isRepresentationClassInputStream() ||
              df.isRepresentationClassByteBuffer() ||
-             byteArrayClass.equals(df.getRepresentationClass()))) {
+             byte[].class.equals(df.getRepresentationClass()))) {
             natives.add(mimeType);
         }
 
         if (DataFlavor.imageFlavor.equals(df)) {
             String[] mimeTypes = ImageIO.getWriterMIMETypes();
             if (mimeTypes != null) {
-                for (int i = 0; i < mimeTypes.length; i++) {
-                    Iterator writers =
-                        ImageIO.getImageWritersByMIMEType(mimeTypes[i]);
-
+                for (String mime : mimeTypes) {
+                    Iterator<ImageWriter> writers = ImageIO.getImageWritersByMIMEType(mime);
                     while (writers.hasNext()) {
-                        ImageWriter imageWriter = (ImageWriter)writers.next();
-                        ImageWriterSpi writerSpi =
-                            imageWriter.getOriginatingProvider();
+                        ImageWriter imageWriter = writers.next();
+                        ImageWriterSpi writerSpi = imageWriter.getOriginatingProvider();
 
                         if (writerSpi != null &&
-                            writerSpi.canEncodeImage(getDefaultImageTypeSpecifier())) {
-                            natives.add(mimeTypes[i]);
+                                writerSpi.canEncodeImage(getDefaultImageTypeSpecifier())) {
+                            natives.add(mime);
                             break;
                         }
                     }
--- a/jdk/src/solaris/classes/sun/awt/X11/XDesktopPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XDesktopPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -33,6 +33,9 @@
 
 import java.awt.Desktop.Action;
 import java.awt.peer.DesktopPeer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
 
 
 /**
@@ -43,6 +46,10 @@
  */
 public class XDesktopPeer implements DesktopPeer {
 
+    // supportedActions may be changed from native within an init() call
+    private static final List<Action> supportedActions
+            = new ArrayList<>(Arrays.asList(Action.OPEN, Action.MAIL, Action.BROWSE));
+
     private static boolean nativeLibraryLoaded = false;
     private static boolean initExecuted = false;
 
@@ -65,11 +72,11 @@
 
     static boolean isDesktopSupported() {
         initWithLock();
-        return nativeLibraryLoaded;
+        return nativeLibraryLoaded && !supportedActions.isEmpty();
     }
 
     public boolean isSupported(Action type) {
-        return type != Action.PRINT && type != Action.EDIT;
+        return supportedActions.contains(type);
     }
 
     public void open(File file) throws IOException {
--- a/jdk/src/solaris/classes/sun/awt/X11/XRepaintArea.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XRepaintArea.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,8 +28,8 @@
 
 import java.awt.Component;
 import java.awt.Graphics;
+
 import sun.awt.RepaintArea;
-import java.awt.peer.ComponentPeer;
 
 /**
  * The <code>RepaintArea</code> is a geometric construct created for the
@@ -39,24 +39,15 @@
  *
  * @author      Eric Hawkes
  */
-class XRepaintArea extends RepaintArea {
-
-    /**
-     * Constructs a new <code>XRepaintArea</code>
-     * @since   1.3
-     */
-    public XRepaintArea() {
-    }
+final class XRepaintArea extends RepaintArea {
 
     /**
      * Calls <code>Component.update(Graphics)</code> with given Graphics.
      */
     protected void updateComponent(Component comp, Graphics g) {
         if (comp != null) {
-            final XComponentPeer peer = (XComponentPeer) comp.getPeer();
-            if (peer != null) {
-                peer.paintPeer(g);
-            }
+            // We don't call peer.paintPeer() here, because we shouldn't paint
+            // native component when processing UPDATE events.
             super.updateComponent(comp, g);
         }
     }
--- a/jdk/src/solaris/classes/sun/awt/X11/XRootWindow.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XRootWindow.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -46,7 +46,8 @@
     }
 
     private XRootWindow() {
-        super(new XCreateWindowParams(new Object[] {DELAYED, Boolean.TRUE}));
+        super(new XCreateWindowParams(new Object[] { DELAYED, Boolean.TRUE,
+                                                     EVENT_MASK, XConstants.StructureNotifyMask }));
     }
 
     public void postInit(XCreateWindowParams params){
--- a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java	Wed Jul 05 19:33:51 2017 +0200
@@ -47,6 +47,7 @@
 import javax.swing.LookAndFeel;
 import javax.swing.UIDefaults;
 import sun.awt.*;
+import sun.awt.datatransfer.DataTransferer;
 import sun.font.FontConfigManager;
 import sun.java2d.SunGraphicsEnvironment;
 import sun.misc.PerformanceLogger;
@@ -299,8 +300,6 @@
         return awtAppClassName;
     }
 
-    static final String DATA_TRANSFERER_CLASS_NAME = "sun.awt.X11.XDataTransferer";
-
     public XToolkit() {
         super();
         if (PerformanceLogger.loggingEnabled()) {
@@ -322,7 +321,6 @@
 
             init();
             XWM.init();
-            SunToolkit.setDataTransfererClassName(DATA_TRANSFERER_CLASS_NAME);
 
             PrivilegedAction<Thread> action = new PrivilegedAction() {
                 public Thread run() {
@@ -823,10 +821,32 @@
                     // managers don't set this hint correctly, so we just get intersection with windowBounds
                     if (windowBounds != null && windowBounds.intersects(screenBounds))
                     {
-                        insets.left = Math.max((int)Native.getLong(native_ptr, 0), insets.left);
-                        insets.right = Math.max((int)Native.getLong(native_ptr, 1), insets.right);
-                        insets.top = Math.max((int)Native.getLong(native_ptr, 2), insets.top);
-                        insets.bottom = Math.max((int)Native.getLong(native_ptr, 3), insets.bottom);
+                        int left = (int)Native.getLong(native_ptr, 0);
+                        int right = (int)Native.getLong(native_ptr, 1);
+                        int top = (int)Native.getLong(native_ptr, 2);
+                        int bottom = (int)Native.getLong(native_ptr, 3);
+
+                        /*
+                         * struts could be relative to root window bounds, so
+                         * make them relative to the screen bounds in this case
+                         */
+                        left = rootBounds.x + left > screenBounds.x ?
+                                rootBounds.x + left - screenBounds.x : 0;
+                        right = rootBounds.x + rootBounds.width - right <
+                                screenBounds.x + screenBounds.width ?
+                                screenBounds.x + screenBounds.width -
+                                (rootBounds.x + rootBounds.width - right) : 0;
+                        top = rootBounds.y + top > screenBounds.y ?
+                                rootBounds.y + top - screenBounds.y : 0;
+                        bottom = rootBounds.y + rootBounds.height - bottom <
+                                screenBounds.y + screenBounds.height ?
+                                screenBounds.y + screenBounds.height -
+                                (rootBounds.y + rootBounds.height - bottom) : 0;
+
+                        insets.left = Math.max(left, insets.left);
+                        insets.right = Math.max(right, insets.right);
+                        insets.top = Math.max(top, insets.top);
+                        insets.bottom = Math.max(bottom, insets.bottom);
                     }
                 }
             }
@@ -1124,6 +1144,11 @@
         return false;
     }
 
+    @Override
+    public DataTransferer getDataTransferer() {
+        return XDataTransferer.getInstanceImpl();
+    }
+
     /**
      * Returns the supported cursor size
      */
@@ -2357,9 +2382,7 @@
 
     private static XEventDispatcher oops_waiter;
     private static boolean oops_updated;
-    private static boolean oops_failed;
-    private XAtom oops;
-    private static final long WORKAROUND_SLEEP = 100;
+    private static boolean oops_move;
 
     /**
      * @inheritDoc
@@ -2370,52 +2393,33 @@
         if (oops_waiter == null) {
             oops_waiter = new XEventDispatcher() {
                     public void dispatchEvent(XEvent e) {
-                        if (e.get_type() == XConstants.SelectionNotify) {
-                            XSelectionEvent pe = e.get_xselection();
-                            if (pe.get_property() == oops.getAtom()) {
-                                oops_updated = true;
-                                awtLockNotifyAll();
-                            } else if (pe.get_selection() == XAtom.get("WM_S0").getAtom() &&
-                                       pe.get_target() == XAtom.get("VERSION").getAtom() &&
-                                       pe.get_property() == 0 &&
-                                       XlibWrapper.XGetSelectionOwner(getDisplay(), XAtom.get("WM_S0").getAtom()) == 0)
-                            {
-                                // WM forgot to acquire selection  or there is no WM
-                                oops_failed = true;
-                                awtLockNotifyAll();
-                            }
-
+                        if (e.get_type() == XConstants.ConfigureNotify) {
+                            // OOPS ConfigureNotify event catched
+                            oops_updated = true;
+                            awtLockNotifyAll();
                         }
                     }
                 };
         }
 
-        if (oops == null) {
-            oops = XAtom.get("OOPS");
-        }
-
         awtLock();
         try {
             addEventDispatcher(win.getWindow(), oops_waiter);
 
             oops_updated = false;
-            oops_failed = false;
-            // Wait for selection notify for oops on win
             long event_number = getEventNumber();
-            XAtom atom = XAtom.get("WM_S0");
-            if (eventLog.isLoggable(PlatformLogger.Level.FINER)) {
-                eventLog.finer("WM_S0 selection owner {0}", XlibWrapper.XGetSelectionOwner(getDisplay(), atom.getAtom()));
-            }
-            XlibWrapper.XConvertSelection(getDisplay(), atom.getAtom(),
-                                          XAtom.get("VERSION").getAtom(), oops.getAtom(),
-                                          win.getWindow(), XConstants.CurrentTime);
+            // Generate OOPS ConfigureNotify event
+            XlibWrapper.XMoveWindow(getDisplay(), win.getWindow(), oops_move ? 0 : 1, 0);
+            // Change win position each time to avoid system optimization
+            oops_move = !oops_move;
             XSync();
 
-            eventLog.finer("Requested OOPS");
+            eventLog.finer("Generated OOPS ConfigureNotify event");
 
             long start = System.currentTimeMillis();
-            while (!oops_updated && !oops_failed) {
+            while (!oops_updated) {
                 try {
+                    // Wait for OOPS ConfigureNotify event
                     awtLockWait(timeout);
                 } catch (InterruptedException e) {
                     throw new RuntimeException(e);
@@ -2426,20 +2430,8 @@
                     throw new OperationTimedOut(Long.toString(System.currentTimeMillis() - start));
                 }
             }
-            if (oops_failed && getEventNumber() - event_number == 1) {
-                // If selection update failed we can simply wait some time
-                // hoping some events will arrive
-                awtUnlock();
-                eventLog.finest("Emergency sleep");
-                try {
-                    Thread.sleep(WORKAROUND_SLEEP);
-                } catch (InterruptedException ie) {
-                    throw new RuntimeException(ie);
-                } finally {
-                    awtLock();
-                }
-            }
-            return getEventNumber() - event_number > 2;
+            // Don't take into account OOPS ConfigureNotify event
+            return getEventNumber() - event_number > 1;
         } finally {
             removeEventDispatcher(win.getWindow(), oops_waiter);
             eventLog.finer("Exiting syncNativeQueue");
--- a/jdk/src/solaris/classes/sun/awt/X11/XWindow.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XWindow.java	Wed Jul 05 19:33:51 2017 +0200
@@ -456,6 +456,7 @@
             ColorModel cm = getColorModel();
             int pixel = PixelConverter.instance.rgbToPixel(c.getRGB(), cm);
             XlibWrapper.XSetWindowBackground(XToolkit.getDisplay(), getContentWindow(), pixel);
+            XlibWrapper.XClearWindow(XToolkit.getDisplay(), getContentWindow());
         }
         finally {
             XToolkit.awtUnlock();
--- a/jdk/src/solaris/classes/sun/awt/windows/ThemeReader.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/awt/windows/ThemeReader.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,10 @@
 
 package sun.awt.windows;
 
-import java.awt.*;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Insets;
+import java.awt.Point;
 
 
 /**
@@ -36,7 +39,8 @@
  *
  * @author Leif Samuelsson
  */
-public class ThemeReader {
+public final class ThemeReader {
+
     public static boolean isThemed() {
         return false;
     }
@@ -84,16 +88,18 @@
     public static Dimension getPartSize(String widget, int part, int state) {
         return null;
     }
+
     public static long getThemeTransitionDuration(String widget, int part,
                                        int stateFrom, int stateTo, int propId) {
         return 0;
     }
+
     public static boolean isGetThemeTransitionDurationDefined() {
         return false;
     }
+
     public static Insets getThemeBackgroundContentMargins(String widget,
                     int part, int state, int boundingWidth, int boundingHeight) {
         return null;
     }
-
 }
--- a/jdk/src/solaris/classes/sun/font/FcFontConfiguration.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/font/FcFontConfiguration.java	Wed Jul 05 19:33:51 2017 +0200
@@ -33,6 +33,7 @@
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -173,8 +174,16 @@
     }
 
     @Override
-    public FontDescriptor[] getFontDescriptors(String fontName, int style) {
-        return new FontDescriptor[0];
+    protected FontDescriptor[] buildFontDescriptors(int fontIndex, int styleIndex) {
+        CompositeFontDescriptor[] cfi = get2DCompositeFontInfo();
+        int idx = fontIndex * NUM_STYLES + styleIndex;
+        String[] componentFaceNames = cfi[idx].getComponentFaceNames();
+        FontDescriptor[] ret = new FontDescriptor[componentFaceNames.length];
+        for (int i = 0; i < componentFaceNames.length; i++) {
+            ret[i] = new FontDescriptor(componentFaceNames[i], StandardCharsets.UTF_8.newEncoder(), new int[0]);
+        }
+
+        return ret;
     }
 
     @Override
@@ -250,10 +259,12 @@
                 }
 
                 String[] fileNames = new String[numFonts];
+                String[] faceNames = new String[numFonts];
 
                 int index;
                 for (index = 0; index < fcFonts.length; index++) {
                     fileNames[index] = fcFonts[index].fontFile;
+                    faceNames[index] = fcFonts[index].familyName;
                 }
 
                 if (installedFallbackFontFiles != null) {
@@ -266,7 +277,7 @@
                         = new CompositeFontDescriptor(
                             faceName,
                             1,
-                            null,
+                            faceNames,
                             fileNames,
                             null, null);
             }
--- a/jdk/src/solaris/classes/sun/print/CUPSPrinter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/print/CUPSPrinter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -252,6 +252,7 @@
                             try {
                                 return urlConnection.getOutputStream();
                             } catch (Exception e) {
+                               IPPPrintService.debug_println(debugPrefix+e);
                             }
                             return null;
                         }
@@ -282,6 +283,9 @@
 
                     if (responseMap != null && responseMap.length > 0) {
                         defaultMap = responseMap[0];
+                    } else {
+                       IPPPrintService.debug_println(debugPrefix+
+                           " empty response map for GET_DEFAULT.");
                     }
 
                     if (defaultMap == null) {
@@ -310,7 +314,10 @@
 
                     if (attribClass != null) {
                         printerInfo[0] = attribClass.getStringValue();
-                        attribClass = (AttributeClass)defaultMap.get("device-uri");
+                        attribClass = (AttributeClass)
+                            defaultMap.get("printer-uri-supported");
+                        IPPPrintService.debug_println(debugPrefix+
+                          "printer-uri-supported="+attribClass);
                         if (attribClass != null) {
                             printerInfo[1] = attribClass.getStringValue();
                         } else {
--- a/jdk/src/solaris/classes/sun/print/IPPPrintService.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/print/IPPPrintService.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1904,9 +1904,8 @@
                                   new HashMap[respList.size()]);
             } else {
                 debug_println(debugPrefix+
-                              "readIPPResponse client error, IPP status code-"
-                                   +Integer.toHexString(response[2])+" & "
-                                   +Integer.toHexString(response[3]));
+                          "readIPPResponse client error, IPP status code: 0x"+
+                          toHex(response[2]) + toHex(response[3]));
                 return null;
             }
 
@@ -1919,6 +1918,10 @@
         }
     }
 
+    private static String toHex(byte v) {
+        String s = Integer.toHexString(v&0xff);
+        return (s.length() == 2) ? s :  "0"+s;
+    }
 
     public String toString() {
         return "IPP Printer : " + getName();
--- a/jdk/src/solaris/classes/sun/print/UnixPrintJob.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/print/UnixPrintJob.java	Wed Jul 05 19:33:51 2017 +0200
@@ -409,7 +409,11 @@
                     ((IPPPrintService)service).isIPPSupportedImages(
                                                 flavor.getMimeType()))) {
                     printableJob(new ImagePrinter(instream));
-                    ((UnixPrintService)service).wakeNotifier();
+                    if (service instanceof IPPPrintService) {
+                        ((IPPPrintService)service).wakeNotifier();
+                    } else {
+                        ((UnixPrintService)service).wakeNotifier();
+                    }
                     return;
                 }
             } catch (ClassCastException cce) {
@@ -430,7 +434,11 @@
                     instream = url.openStream();
                 } else {
                     printableJob(new ImagePrinter(url));
-                    ((UnixPrintService)service).wakeNotifier();
+                    if (service instanceof IPPPrintService) {
+                        ((IPPPrintService)service).wakeNotifier();
+                    } else {
+                        ((UnixPrintService)service).wakeNotifier();
+                    }
                     return;
                 }
             } catch (ClassCastException cce) {
--- a/jdk/src/solaris/classes/sun/print/UnixPrintServiceLookup.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/classes/sun/print/UnixPrintServiceLookup.java	Wed Jul 05 19:33:51 2017 +0200
@@ -273,9 +273,25 @@
         String[] printers = null; // array of printer names
         String[] printerURIs = null; //array of printer URIs
 
-        getDefaultPrintService();
+        try {
+            getDefaultPrintService();
+        } catch (Throwable t) {
+            IPPPrintService.debug_println(debugPrefix+
+              "Exception getting default printer : " + t);
+        }
         if (CUPSPrinter.isCupsRunning()) {
-            printerURIs = CUPSPrinter.getAllPrinters();
+            try {
+                printerURIs = CUPSPrinter.getAllPrinters();
+                IPPPrintService.debug_println("CUPS URIs = " + printerURIs);
+                if (printerURIs != null) {
+                    for (int p = 0; p < printerURIs.length; p++) {
+                       IPPPrintService.debug_println("URI="+printerURIs[p]);
+                    }
+                }
+            } catch (Throwable t) {
+            IPPPrintService.debug_println(debugPrefix+
+              "Exception getting all CUPS printers : " + t);
+            }
             if ((printerURIs != null) && (printerURIs.length > 0)) {
                 printers = new String[printerURIs.length];
                 for (int i=0; i<printerURIs.length; i++) {
@@ -632,8 +648,10 @@
                                       (CUPSPrinter.isCupsRunning()));
         if (CUPSPrinter.isCupsRunning()) {
             String[] printerInfo = CUPSPrinter.getDefaultPrinter();
-            defaultPrinter = printerInfo[0];
-            psuri = printerInfo[1];
+            if (printerInfo != null && printerInfo.length >= 2) {
+                defaultPrinter = printerInfo[0];
+                psuri = printerInfo[1];
+            }
         } else {
             if (isMac() || isSysV()) {
                 defaultPrinter = getDefaultPrinterNameSysV();
--- a/jdk/src/solaris/native/sun/awt/awt_Font.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/native/sun/awt/awt_Font.c	Wed Jul 05 19:33:51 2017 +0200
@@ -452,6 +452,7 @@
         int32_t i, size;
         char *fontsetname = NULL;
         char *nativename = NULL;
+        Boolean doFree = FALSE;
         jobjectArray componentFonts = NULL;
         jobject peer = NULL;
         jobject fontDescriptor = NULL;
@@ -491,8 +492,10 @@
 
             if (!JNU_IsNull(env, fontDescriptorName)) {
                 nativename = (char *) JNU_GetStringPlatformChars(env, fontDescriptorName, NULL);
+                doFree = TRUE;
             } else {
                 nativename = "";
+                doFree = FALSE;
             }
 
             fdata->flist[i].xlfd = malloc(strlen(nativename)
@@ -500,7 +503,7 @@
             jio_snprintf(fdata->flist[i].xlfd, strlen(nativename) + 10,
                          nativename, size * 10);
 
-            if (nativename != NULL && nativename != "")
+            if (nativename != NULL && doFree)
                 JNU_ReleaseStringPlatformChars(env, fontDescriptorName, (const char *) nativename);
 
             /*
--- a/jdk/src/solaris/native/sun/awt/awt_LoadLibrary.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/native/sun/awt/awt_LoadLibrary.c	Wed Jul 05 19:33:51 2017 +0200
@@ -113,7 +113,7 @@
     jvm = vm;
 
     /* Get address of this library and the directory containing it. */
-    dladdr((void *)JNI_OnLoad, &dlinfo);
+    dladdr((void *)AWT_OnLoad, &dlinfo);
     realpath((char *)dlinfo.dli_fname, buf);
     len = strlen(buf);
     p = strrchr(buf, '/');
@@ -227,7 +227,7 @@
 
 
 #define REFLECT_VOID_FUNCTION(name, arglist, paramlist)                 \
-typedef name##_type arglist;                                            \
+typedef void name##_type arglist;                                       \
 void name arglist                                                       \
 {                                                                       \
     static name##_type *name##_ptr = NULL;                              \
--- a/jdk/src/solaris/native/sun/awt/gtk2_interface.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/native/sun/awt/gtk2_interface.c	Wed Jul 05 19:33:51 2017 +0200
@@ -32,6 +32,7 @@
 #include "java_awt_Transparency.h"
 #include "jvm_md.h"
 #include "sizecalc.h"
+#include <jni_util.h>
 
 #define GTK2_LIB_VERSIONED VERSIONED_JNI_LIB_NAME("gtk-x11-2.0", "0")
 #define GTK2_LIB JNI_LIB_NAME("gtk-x11-2.0")
@@ -438,10 +439,82 @@
     }
 }
 
+#define ADD_SUPPORTED_ACTION(actionStr) \
+do { \
+    jfieldID fld_action = (*env)->GetStaticFieldID(env, cls_action, actionStr, "Ljava/awt/Desktop$Action;"); \
+    if (!(*env)->ExceptionCheck(env)) { \
+        jobject action = (*env)->GetStaticObjectField(env, cls_action, fld_action); \
+        (*env)->CallBooleanMethod(env, supportedActions, mid_arrayListAdd, action); \
+    } else { \
+        (*env)->ExceptionClear(env); \
+    } \
+} while(0);
+
+
+void update_supported_actions(JNIEnv *env) {
+    GVfs * (*fp_g_vfs_get_default) (void);
+    const gchar * const * (*fp_g_vfs_get_supported_uri_schemes) (GVfs * vfs);
+    const gchar * const * schemes = NULL;
+
+    jclass cls_action = (*env)->FindClass(env, "java/awt/Desktop$Action");
+    CHECK_NULL(cls_action);
+    jclass cls_xDesktopPeer = (*env)->FindClass(env, "sun/awt/X11/XDesktopPeer");
+    CHECK_NULL(cls_xDesktopPeer);
+    jfieldID fld_supportedActions = (*env)->GetStaticFieldID(env, cls_xDesktopPeer, "supportedActions", "Ljava/util/List;");
+    CHECK_NULL(fld_supportedActions);
+    jobject supportedActions = (*env)->GetStaticObjectField(env, cls_xDesktopPeer, fld_supportedActions);
+
+    jclass cls_arrayList = (*env)->FindClass(env, "java/util/ArrayList");
+    CHECK_NULL(cls_arrayList);
+    jmethodID mid_arrayListAdd = (*env)->GetMethodID(env, cls_arrayList, "add", "(Ljava/lang/Object;)Z");
+    CHECK_NULL(mid_arrayListAdd);
+    jmethodID mid_arrayListClear = (*env)->GetMethodID(env, cls_arrayList, "clear", "()V");
+    CHECK_NULL(mid_arrayListClear);
+
+    (*env)->CallVoidMethod(env, supportedActions, mid_arrayListClear);
+
+    ADD_SUPPORTED_ACTION("OPEN");
+
+    /**
+     * gtk_show_uri() documentation says:
+     *
+     * > you need to install gvfs to get support for uri schemes such as http://
+     * > or ftp://, as only local files are handled by GIO itself.
+     *
+     * So OPEN action was safely added here.
+     * However, it looks like Solaris 11 have gvfs support only for 32-bit
+     * applications only by default.
+     */
+
+    fp_g_vfs_get_default = dl_symbol("g_vfs_get_default");
+    fp_g_vfs_get_supported_uri_schemes = dl_symbol("g_vfs_get_supported_uri_schemes");
+    dlerror();
+
+    if (fp_g_vfs_get_default && fp_g_vfs_get_supported_uri_schemes) {
+        GVfs * vfs = fp_g_vfs_get_default();
+        schemes = vfs ? fp_g_vfs_get_supported_uri_schemes(vfs) : NULL;
+        if (schemes) {
+            int i = 0;
+            while (schemes[i]) {
+                if (strcmp(schemes[i], "http") == 0) {
+                    ADD_SUPPORTED_ACTION("BROWSE");
+                    ADD_SUPPORTED_ACTION("MAIL");
+                    break;
+                }
+                i++;
+            }
+        }
+    } else {
+#ifdef INTERNAL_BUILD
+        fprintf(stderr, "Cannot load g_vfs_get_supported_uri_schemes\n");
+#endif /* INTERNAL_BUILD */
+    }
+
+}
 /**
  * Functions for awt_Desktop.c
  */
-gboolean gtk2_show_uri_load() {
+gboolean gtk2_show_uri_load(JNIEnv *env) {
      gboolean success = FALSE;
      dlerror();
      const char *gtk_version = fp_gtk_check_version(2, 14, 0);
@@ -464,9 +537,12 @@
 #ifdef INTERNAL_BUILD
              fprintf(stderr, "dlsym(gtk_show_uri) returned NULL\n");
 #endif /* INTERNAL_BUILD */
-         } else {
-             success = TRUE;
-         }
+        } else {
+#ifdef __solaris__
+            update_supported_actions(env);
+#endif
+            success = TRUE;
+        }
      }
      return success;
 }
@@ -533,7 +609,10 @@
         }
 
         /* GLib */
-        fp_glib_check_version = dl_symbol("glib_check_version");
+        fp_glib_check_version = dlsym(gtk2_libhandle, "glib_check_version");
+        if (!fp_glib_check_version) {
+            dlerror();
+        }
         fp_g_free = dl_symbol("g_free");
         fp_g_object_unref = dl_symbol("g_object_unref");
 
@@ -709,7 +788,7 @@
         /**
          * GLib thread system
          */
-        if (fp_glib_check_version(2, 20, 0) == NULL) {
+        if (GLIB_CHECK_VERSION(2, 20, 0)) {
             fp_g_thread_get_initialized = dl_symbol_gthread("g_thread_get_initialized");
         }
         fp_g_thread_init = dl_symbol_gthread("g_thread_init");
@@ -827,7 +906,7 @@
         // We can use g_thread_get_initialized () but it is available only for
         // GLib >= 2.20. We rely on GThreadHelper for GLib < 2.20.
         gboolean is_g_thread_get_initialized = FALSE;
-        if (fp_glib_check_version(2, 20, 0) == NULL) {
+        if (GLIB_CHECK_VERSION(2, 20, 0)) {
             is_g_thread_get_initialized = fp_g_thread_get_initialized();
         }
 
--- a/jdk/src/solaris/native/sun/awt/gtk2_interface.h	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/native/sun/awt/gtk2_interface.h	Wed Jul 05 19:33:51 2017 +0200
@@ -270,6 +270,7 @@
 /* We define all structure pointers to be void* */
 typedef void GError;
 typedef void GMainContext;
+typedef void GVfs;
 
 typedef struct _GSList GSList;
 struct _GSList
@@ -647,10 +648,19 @@
  * Returns :
  * NULL if the GLib library is compatible with the given version, or a string
  * describing the version mismatch.
+ * Please note that the glib_check_version() is available since 2.6,
+ * so you should use GLIB_CHECK_VERSION macro instead.
  */
 gchar* (*fp_glib_check_version)(guint required_major, guint required_minor,
                        guint required_micro);
 
+/**
+ * Returns :
+ *  TRUE if the GLib library is compatible with the given version
+ */
+#define GLIB_CHECK_VERSION(major, minor, micro) \
+    (fp_glib_check_version && fp_glib_check_version(major, minor, micro) == NULL)
+
 /*
  * Check whether the gtk2 library is available and meets the minimum
  * version requirement.  If the library is already loaded this method has no
@@ -680,7 +690,7 @@
  * gtk2_load, so it must be invoked only after a successful gtk2_load
  * invocation
  */
-gboolean gtk2_show_uri_load();
+gboolean gtk2_show_uri_load(JNIEnv *env);
 
 /*
  * Unload the gtk2 library.  If the library is already unloaded this method has
@@ -811,7 +821,7 @@
 
 /**
  * This function is available for GLIB > 2.20, so it MUST be
- * called within (fp_glib_check_version(2, 20, 0) == NULL) check.
+ * called within GLIB_CHECK_VERSION(2, 20, 0) check.
  */
 gboolean (*fp_g_thread_get_initialized)(void);
 
--- a/jdk/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c	Wed Jul 05 19:33:51 2017 +0200
@@ -1,3 +1,28 @@
+/*
+ * Copyright (c) 2010, 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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>
 #include <stdio.h>
 #include <jni_util.h>
--- a/jdk/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h	Tue Mar 25 12:31:49 2014 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,55 +0,0 @@
-/* DO NOT EDIT THIS FILE - it is machine generated */
-#include <jni.h>
-/* Header for class sun_awt_X11_GtkFileDialogPeer */
-
-#ifndef _Included_sun_awt_X11_GtkFileDialogPeer
-#define _Included_sun_awt_X11_GtkFileDialogPeer
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-
-/*
- * Class:     sun_awt_X11_GtkFileDialogPeer
- * Method:    initIDs
- * Signature: ()V
- */
-JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_initIDs
-(JNIEnv *, jclass);
-
-/*
- * Class:     sun_awt_X11_GtkFileDialogPeer
- * Method:    run
- * Signature: (Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/io/FilenameFilter;ZII)V
- */
-JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_run
-(JNIEnv *, jobject, jstring, jint, jstring, jstring, jobject, jboolean, jint, jint);
-
-/*
- * Class:     sun_awt_X11_GtkFileDialogPeer
- * Method:    quit
- * Signature: ()V
- */
-JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_quit
-(JNIEnv *, jobject);
-
-/*
- * Class:     sun_awt_X11_GtkFileDialogPeer
- * Method:    toFront
- * Signature: ()V
- */
-JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_toFront
-(JNIEnv *, jobject);
-
-/*
- * Class:     sun_awt_X11_GtkFileDialogPeer
- * Method:    setBounds
- * Signature: (IIIII)V
- */
-JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_setBounds
-(JNIEnv * env, jobject jpeer, jint x, jint y, jint width, jint height, jint op);
-
-#ifdef __cplusplus
-}
-#endif
-#endif
--- a/jdk/src/solaris/native/sun/java2d/x11/X11SurfaceData.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/native/sun/java2d/x11/X11SurfaceData.c	Wed Jul 05 19:33:51 2017 +0200
@@ -510,7 +510,7 @@
     xsdo->cData = xsdo->configData->color_data;
 
     XShared_initSurface(env, xsdo, depth, width, height, drawable);
-    xsdo->xrPic = NULL;
+    xsdo->xrPic = None;
 #endif /* !HEADLESS */
 }
 
--- a/jdk/src/solaris/native/sun/security/pkcs11/j2secmod_md.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/native/sun/security/pkcs11/j2secmod_md.c	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,6 +50,10 @@
   (JNIEnv *env, jclass thisClass, jstring jLibName)
 {
     const char *libName = (*env)->GetStringUTFChars(env, jLibName, NULL);
+    if (libName == NULL) {
+        return 0L;
+    }
+
     // look up existing handle only, do not load
 #if defined(AIX)
     void *hModule = dlopen(libName, RTLD_LAZY);
@@ -66,6 +70,9 @@
 {
     void *hModule;
     const char *libName = (*env)->GetStringUTFChars(env, jLibName, NULL);
+    if (libName == NULL) {
+       return 0L;
+    }
 
     dprintf1("-lib %s\n", libName);
     hModule = dlopen(libName, RTLD_LAZY);
--- a/jdk/src/solaris/native/sun/security/pkcs11/wrapper/p11_md.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/native/sun/security/pkcs11/wrapper/p11_md.c	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  */
 
 /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
@@ -88,6 +88,9 @@
     const char *getFunctionListStr;
 
     const char *libraryNameStr = (*env)->GetStringUTFChars(env, jPkcs11ModulePath, 0);
+    if (libraryNameStr == NULL) {
+        return;
+    }
     TRACE1("DEBUG: connect to PKCS#11 module: %s ... ", libraryNameStr);
 
 
@@ -123,6 +126,9 @@
     // with the old JAR file jGetFunctionList is null, temporarily check for that
     if (jGetFunctionList != NULL) {
         getFunctionListStr = (*env)->GetStringUTFChars(env, jGetFunctionList, 0);
+        if (getFunctionListStr == NULL) {
+            return;
+        }
         C_GetFunctionList = (CK_C_GetFunctionList) dlsym(hModule, getFunctionListStr);
         (*env)->ReleaseStringUTFChars(env, jGetFunctionList, getFunctionListStr);
     }
--- a/jdk/src/solaris/native/sun/xawt/XToolkit.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/native/sun/xawt/XToolkit.c	Wed Jul 05 19:33:51 2017 +0200
@@ -699,7 +699,7 @@
     if (pollFds[0].revents) {
         // Events in X pipe
         update_poll_timeout(TIMEOUT_EVENTS);
-        PRINT2("performPoll(): TIMEOUT_EVENTS curPollTimeout = %ld \n", curPollTimeout);
+        PRINT2("performPoll(): TIMEOUT_EVENTS curPollTimeout = %d \n", curPollTimeout);
     }
     return;
 
--- a/jdk/src/solaris/native/sun/xawt/awt_Desktop.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/solaris/native/sun/xawt/awt_Desktop.c	Wed Jul 05 19:33:51 2017 +0200
@@ -42,7 +42,7 @@
         return JNI_TRUE;
     }
 
-    if (gtk2_load(env) && gtk2_show_uri_load()) {
+    if (gtk2_load(env) && gtk2_show_uri_load(env)) {
         gtk_has_been_loaded = TRUE;
         return JNI_TRUE;
     } else if (gnome_load()) {
--- a/jdk/src/windows/classes/sun/awt/windows/ThemeReader.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/ThemeReader.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,15 @@
 
 package sun.awt.windows;
 
-import java.awt.*;
-import java.util.*;
-import java.util.concurrent.locks.*;
-import java.beans.*;
-import javax.swing.SwingUtilities;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Insets;
+import java.awt.Point;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
 
 /* !!!! WARNING !!!!
  * This class has to be in sync with
@@ -45,9 +49,9 @@
  * @author Bino George
  * @author Igor Kushnirskiy
  */
-public class ThemeReader {
-    private static final HashMap<String, Long> widgetToTheme =
-        new HashMap<String, Long>();
+public final class ThemeReader {
+
+    private static final Map<String, Long> widgetToTheme = new HashMap<>();
 
     // lock for the cache
     // reading should be done with readLock
@@ -70,7 +74,7 @@
         }
     }
 
-    public native static boolean isThemed();
+    public static native boolean isThemed();
 
     // this should be called only with writeLock held
     private static Long getThemeImpl(String widget) {
@@ -109,8 +113,9 @@
         return theme;
     }
 
-    public native static void paintBackground(int[] buffer, long theme, int part, int state,
-                             int x, int y, int w, int h, int stride);
+    private static native void paintBackground(int[] buffer, long theme,
+                                               int part, int state, int x,
+                                               int y, int w, int h, int stride);
 
     public static void paintBackground(int[] buffer, String widget,
            int part, int state, int x, int y, int w, int h, int stride) {
@@ -122,8 +127,8 @@
         }
     }
 
-    public native static Insets getThemeMargins(long theme, int part, int state,
- int marginType);
+    private static native Insets getThemeMargins(long theme, int part,
+                                                 int state, int marginType);
 
     public static Insets getThemeMargins(String widget, int part, int state, int marginType) {
         readLock.lock();
@@ -134,7 +139,7 @@
         }
     }
 
-    private native static boolean isThemePartDefined(long theme, int part, int state);
+    private static native boolean isThemePartDefined(long theme, int part, int state);
 
     public static boolean isThemePartDefined(String widget, int part, int state) {
         readLock.lock();
@@ -145,8 +150,8 @@
         }
     }
 
-    public native static Color getColor(long theme, int part, int state,
-                                                               int property);
+    private static native Color getColor(long theme, int part, int state,
+                                         int property);
 
     public static Color getColor(String widget, int part, int state, int property) {
         readLock.lock();
@@ -157,8 +162,8 @@
         }
     }
 
-    public native static int getInt(long theme, int part, int state,
-                                                                int property);
+    private static native int getInt(long theme, int part, int state,
+                                     int property);
 
     public static int getInt(String widget, int part, int state, int property) {
         readLock.lock();
@@ -169,8 +174,8 @@
         }
     }
 
-    public native static int getEnum(long theme, int part, int state,
-                                                                int property);
+    private static native int getEnum(long theme, int part, int state,
+                                      int property);
 
     public static int getEnum(String widget, int part, int state, int property) {
         readLock.lock();
@@ -181,8 +186,8 @@
         }
     }
 
-    public native static boolean getBoolean(long theme, int part, int state,
-                                                                int property);
+    private static native boolean getBoolean(long theme, int part, int state,
+                                             int property);
 
     public static boolean getBoolean(String widget, int part, int state,
                                      int property) {
@@ -194,7 +199,7 @@
         }
     }
 
-    public native static boolean getSysBoolean(long theme, int property);
+    private static native boolean getSysBoolean(long theme, int property);
 
     public static boolean getSysBoolean(String widget, int property) {
         readLock.lock();
@@ -205,8 +210,8 @@
         }
     }
 
-    public native static Point getPoint(long theme, int part, int state,
-                                                                int property);
+    private static native Point getPoint(long theme, int part, int state,
+                                         int property);
 
     public static Point getPoint(String widget, int part, int state, int property) {
         readLock.lock();
@@ -217,8 +222,8 @@
         }
     }
 
-    public native static Dimension getPosition(long theme, int part, int state,
-                                                                 int property);
+    private static native Dimension getPosition(long theme, int part, int state,
+                                                int property);
 
     public static Dimension getPosition(String widget, int part, int state,
                                         int property) {
@@ -230,7 +235,8 @@
         }
     }
 
-    public native static Dimension getPartSize(long theme, int part, int state);
+    private static native Dimension getPartSize(long theme, int part,
+                                                int state);
 
     public static Dimension getPartSize(String widget, int part, int state) {
         readLock.lock();
@@ -241,14 +247,15 @@
         }
     }
 
-    public native static long openTheme(String widget);
+    private static native long openTheme(String widget);
 
-    public native static void closeTheme(long theme);
+    private static native void closeTheme(long theme);
 
-    public native static void setWindowTheme(String subAppName);
+    private static native void setWindowTheme(String subAppName);
 
-    private native static long getThemeTransitionDuration(long theme, int part,
+    private static native long getThemeTransitionDuration(long theme, int part,
                                         int stateFrom, int stateTo, int propId);
+
     public static long getThemeTransitionDuration(String widget, int part,
                                        int stateFrom, int stateTo, int propId) {
         readLock.lock();
@@ -259,10 +266,12 @@
             readLock.unlock();
         }
     }
-    public native static boolean isGetThemeTransitionDurationDefined();
+
+    public static native boolean isGetThemeTransitionDurationDefined();
 
-    private native static Insets getThemeBackgroundContentMargins(long theme,
+    private static native Insets getThemeBackgroundContentMargins(long theme,
                      int part, int state, int boundingWidth, int boundingHeight);
+
     public static Insets getThemeBackgroundContentMargins(String widget,
                     int part, int state, int boundingWidth, int boundingHeight) {
         readLock.lock();
--- a/jdk/src/windows/classes/sun/awt/windows/TranslucentWindowPainter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/TranslucentWindowPainter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +33,6 @@
 import java.awt.image.BufferedImage;
 import java.awt.image.DataBufferInt;
 import java.awt.image.VolatileImage;
-import java.lang.ref.WeakReference;
 import java.security.AccessController;
 import sun.awt.image.BufImgSurfaceData;
 import sun.java2d.DestSurfaceProvider;
@@ -46,7 +45,6 @@
 import sun.security.action.GetPropertyAction;
 
 import static java.awt.image.VolatileImage.*;
-import static java.awt.Transparency.*;
 import static sun.java2d.pipe.hw.AccelSurface.*;
 import static sun.java2d.pipe.hw.ContextCapabilities.*;
 
@@ -59,7 +57,7 @@
  * Note: this class does not attempt to be thread safe, it is expected to be
  * called from a single thread (EDT).
  */
-public abstract class TranslucentWindowPainter {
+abstract class TranslucentWindowPainter {
 
     protected Window window;
     protected WWindowPeer peer;
@@ -231,6 +229,7 @@
             return (viBB != null ? !viBB.contentsLost() : true);
         }
 
+        @Override
         public void flush() {
             if (backBuffer != null) {
                 backBuffer.flush();
@@ -313,6 +312,7 @@
                     try {
                         BufferedContext.validateContext(as);
                         rq.flushAndInvokeNow(new Runnable() {
+                            @Override
                             public void run() {
                                 long psdops = as.getNativeOps();
                                 arr[0] = updateWindowAccel(psdops, w, h);
--- a/jdk/src/windows/classes/sun/awt/windows/WBufferStrategy.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WBufferStrategy.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,8 +34,9 @@
  * the back buffer associated with a Component.  If that
  * Component has a BufferStrategy with >1 buffer, then the
  * Image subclass associated with that buffer will be returned.
+ * Note: the class is used by the JAWT3d.
  */
-public class WBufferStrategy {
+public final class WBufferStrategy {
 
     private static native void initIDs(Class <?> componentClass);
 
--- a/jdk/src/windows/classes/sun/awt/windows/WButtonPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WButtonPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,6 +37,7 @@
 
     // ComponentPeer overrides
 
+    @Override
     public Dimension getMinimumSize() {
         FontMetrics fm = getFontMetrics(((Button)target).getFont());
         String label = ((Button)target).getLabel();
@@ -46,12 +47,14 @@
         return new Dimension(fm.stringWidth(label) + 14,
                              fm.getHeight() + 8);
     }
+    @Override
     public boolean isFocusable() {
         return true;
     }
 
     // ButtonPeer implementation
 
+    @Override
     public native void setLabel(String label);
 
     // Toolkit & peer internals
@@ -60,6 +63,7 @@
         super(target);
     }
 
+    @Override
     native void create(WComponentPeer peer);
 
     // native callbacks
@@ -70,6 +74,7 @@
         // Fixed 5064013: the InvocationEvent time should be equals
         // the time of the ActionEvent
         WToolkit.executeOnEventHandlerThread(target, new Runnable() {
+            @Override
             public void run() {
                 postEvent(new ActionEvent(target, ActionEvent.ACTION_PERFORMED,
                                           ((Button)target).getActionCommand(),
@@ -79,6 +84,7 @@
     }
 
 
+    @Override
     public boolean shouldClearRectBeforePaint() {
         return false;
     }
@@ -88,6 +94,7 @@
      */
     private static native void initIDs();
 
+    @Override
     public boolean handleJavaKeyEvent(KeyEvent e) {
          switch (e.getID()) {
             case KeyEvent.KEY_RELEASED:
--- a/jdk/src/windows/classes/sun/awt/windows/WCanvasPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WCanvasPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,12 +24,16 @@
  */
 package sun.awt.windows;
 
-import java.awt.*;
-import java.awt.peer.*;
-import java.lang.ref.WeakReference;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.GraphicsConfiguration;
+import java.awt.peer.CanvasPeer;
+
+import sun.awt.PaintEventDispatcher;
 import sun.awt.SunToolkit;
-import sun.awt.Win32GraphicsDevice;
-import sun.awt.PaintEventDispatcher;
 
 class WCanvasPeer extends WComponentPeer implements CanvasPeer {
 
@@ -41,8 +45,10 @@
         super(target);
     }
 
+    @Override
     native void create(WComponentPeer parent);
 
+    @Override
     void initialize() {
         eraseBackground = !SunToolkit.getSunAwtNoerasebackground();
         boolean eraseBackgroundOnResize = SunToolkit.getSunAwtErasebackgroundonresize();
@@ -60,6 +66,7 @@
         }
     }
 
+    @Override
     public void paint(Graphics g) {
         Dimension d = ((Component)target).getSize();
         if (g instanceof Graphics2D ||
@@ -75,6 +82,7 @@
         super.paint(g);
     }
 
+    @Override
     public boolean shouldClearRectBeforePaint() {
         return eraseBackground;
     }
@@ -99,6 +107,7 @@
     private native void setNativeBackgroundErase(boolean doErase,
                                                  boolean doEraseOnResize);
 
+    @Override
     public GraphicsConfiguration getAppropriateGraphicsConfiguration(
             GraphicsConfiguration gc)
     {
--- a/jdk/src/windows/classes/sun/awt/windows/WCheckboxMenuItemPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WCheckboxMenuItemPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,14 +24,16 @@
  */
 package sun.awt.windows;
 
-import java.awt.*;
-import java.awt.peer.*;
+import java.awt.CheckboxMenuItem;
 import java.awt.event.ItemEvent;
+import java.awt.peer.CheckboxMenuItemPeer;
 
-class WCheckboxMenuItemPeer extends WMenuItemPeer implements CheckboxMenuItemPeer {
+final class WCheckboxMenuItemPeer extends WMenuItemPeer
+        implements CheckboxMenuItemPeer {
 
     // CheckboxMenuItemPeer implementation
 
+    @Override
     public native void setState(boolean t);
 
     // Toolkit & peer internals
@@ -46,6 +48,7 @@
     public void handleAction(final boolean state) {
         final CheckboxMenuItem target = (CheckboxMenuItem)this.target;
         WToolkit.executeOnEventHandlerThread(target, new Runnable() {
+            @Override
             public void run() {
                 target.setState(state);
                 postEvent(new ItemEvent(target, ItemEvent.ITEM_STATE_CHANGED,
--- a/jdk/src/windows/classes/sun/awt/windows/WCheckboxPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WCheckboxPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,12 +32,16 @@
 
     // CheckboxPeer implementation
 
+    @Override
     public native void setState(boolean state);
+    @Override
     public native void setCheckboxGroup(CheckboxGroup g);
+    @Override
     public native void setLabel(String label);
 
     private static native int getCheckMarkSize();
 
+    @Override
     public Dimension getMinimumSize() {
         String lbl = ((Checkbox)target).getLabel();
         int marksize = getCheckMarkSize();
@@ -54,6 +58,7 @@
                              Math.max(fm.getHeight() + 8,  marksize));
     }
 
+    @Override
     public boolean isFocusable() {
         return true;
     }
@@ -64,8 +69,10 @@
         super(target);
     }
 
+    @Override
     native void create(WComponentPeer parent);
 
+    @Override
     void initialize() {
         Checkbox t = (Checkbox)target;
         setState(t.getState());
@@ -79,6 +86,7 @@
         super.initialize();
     }
 
+    @Override
     public boolean shouldClearRectBeforePaint() {
         return false;
     }
@@ -88,6 +96,7 @@
     void handleAction(final boolean state) {
         final Checkbox cb = (Checkbox)this.target;
         WToolkit.executeOnEventHandlerThread(cb, new Runnable() {
+            @Override
             public void run() {
                 CheckboxGroup chg = cb.getCheckboxGroup();
                 if ((chg != null) && (cb == chg.getSelectedCheckbox()) && cb.getState()) {
--- a/jdk/src/windows/classes/sun/awt/windows/WChoicePeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WChoicePeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 
     // WComponentPeer overrides
 
+    @Override
     public Dimension getMinimumSize() {
         FontMetrics fm = getFontMetrics(((Choice)target).getFont());
         Choice c = (Choice)target;
@@ -45,23 +46,29 @@
         }
         return new Dimension(28 + w, Math.max(fm.getHeight() + 6, 15));
     }
+    @Override
     public boolean isFocusable() {
         return true;
     }
 
     // ChoicePeer implementation
 
+    @Override
     public native void select(int index);
 
+    @Override
     public void add(String item, int index) {
         addItem(item, index);
     }
 
+    @Override
     public boolean shouldClearRectBeforePaint() {
         return false;
     }
 
+    @Override
     public native void removeAll();
+    @Override
     public native void remove(int index);
 
     /**
@@ -72,6 +79,7 @@
     }
     public native void addItems(String[] items, int index);
 
+    @Override
     public synchronized native void reshape(int x, int y, int width, int height);
 
     private WindowListener windowListener;
@@ -82,8 +90,10 @@
         super(target);
     }
 
+    @Override
     native void create(WComponentPeer parent);
 
+    @Override
     @SuppressWarnings("deprecation")
     void initialize() {
         Choice opt = (Choice)target;
@@ -104,9 +114,11 @@
             WWindowPeer wpeer = (WWindowPeer)parentWindow.getPeer();
             if (wpeer != null) {
                 windowListener = new WindowAdapter() {
+                        @Override
                         public void windowIconified(WindowEvent e) {
                             closeList();
                         }
+                        @Override
                         public void windowClosing(WindowEvent e) {
                             closeList();
                         }
@@ -117,6 +129,7 @@
         super.initialize();
     }
 
+    @Override
     @SuppressWarnings("deprecation")
     protected void disposeImpl() {
         // TODO: we should somehow reset the listener when the choice
@@ -136,6 +149,7 @@
     void handleAction(final int index) {
         final Choice c = (Choice)target;
         WToolkit.executeOnEventHandlerThread(c, new Runnable() {
+            @Override
             public void run() {
                 c.select(index);
                 postEvent(new ItemEvent(c, ItemEvent.ITEM_STATE_CHANGED,
--- a/jdk/src/windows/classes/sun/awt/windows/WClipboard.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WClipboard.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,14 +28,11 @@
 import java.awt.datatransfer.DataFlavor;
 import java.awt.datatransfer.Transferable;
 import java.awt.datatransfer.UnsupportedFlavorException;
-
 import java.io.IOException;
-
-import java.util.Iterator;
 import java.util.Map;
 
+import sun.awt.datatransfer.DataTransferer;
 import sun.awt.datatransfer.SunClipboard;
-import sun.awt.datatransfer.DataTransferer;
 
 
 /**
@@ -50,18 +47,20 @@
  *
  * @since JDK1.1
  */
-public class WClipboard extends SunClipboard {
+final class WClipboard extends SunClipboard {
 
     private boolean isClipboardViewerRegistered;
 
-    public WClipboard() {
+    WClipboard() {
         super("System");
     }
 
+    @Override
     public long getID() {
         return 0;
     }
 
+    @Override
     protected void setContentsNative(Transferable contents) {
 
         // Don't use delayed Clipboard rendering for the Transferable's data.
@@ -107,6 +106,7 @@
      * Currently delayed data rendering is not used for the Windows clipboard,
      * so there is no native context to clear.
      */
+    @Override
     protected void clearNativeContext() {}
 
     /**
@@ -115,11 +115,13 @@
      *
      * @throws IllegalStateException if the clipboard has not been opened
      */
+    @Override
     public native void openClipboard(SunClipboard newOwner) throws IllegalStateException;
     /**
      * Call the Win32 CloseClipboard function if we have clipboard ownership,
      * does nothing if we have not ownership.
      */
+    @Override
     public native void closeClipboard();
     /**
      * Call the Win32 SetClipboardData function.
@@ -131,9 +133,12 @@
         init();
     }
 
+    @Override
     protected native long[] getClipboardFormats();
+    @Override
     protected native byte[] getClipboardData(long format) throws IOException;
 
+    @Override
     protected void registerClipboardViewerChecked() {
         if (!isClipboardViewerRegistered) {
             registerClipboardViewer();
@@ -148,6 +153,7 @@
      * until the toolkit window disposing since MSDN suggests removing
      * the window from the clipboard viewer chain just before it is destroyed.
      */
+    @Override
     protected void unregisterClipboardViewerChecked() {}
 
     /**
@@ -175,6 +181,7 @@
      *
      * @since 1.5
      */
+    @Override
     protected Transferable createLocaleTransferable(long[] formats) throws IOException {
         boolean found = false;
         for (int i = 0; i < formats.length; i++) {
@@ -197,12 +204,15 @@
         final byte[] localeDataFinal = localeData;
 
         return new Transferable() {
+                @Override
                 public DataFlavor[] getTransferDataFlavors() {
                     return new DataFlavor[] { DataTransferer.javaTextEncodingFlavor };
                 }
+                @Override
                 public boolean isDataFlavorSupported(DataFlavor flavor) {
                     return flavor.equals(DataTransferer.javaTextEncodingFlavor);
                 }
+                @Override
                 public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
                     if (isDataFlavorSupported(flavor)) {
                         return localeDataFinal;
@@ -211,5 +221,4 @@
                 }
             };
     }
-
 }
--- a/jdk/src/windows/classes/sun/awt/windows/WColor.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WColor.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +29,7 @@
 /*
  * This helper class maps Windows system colors to AWT Color objects.
  */
-class WColor {
+final class WColor {
 
     static final int WINDOW_BKGND = 1;  // COLOR_WINDOW
     static final int WINDOW_TEXT  = 2;  // COLOR_WINDOWTEXT
--- a/jdk/src/windows/classes/sun/awt/windows/WComponentPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WComponentPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +93,9 @@
     private Color background;
     private Font font;
 
+    @Override
     public native boolean isObscured();
+    @Override
     public boolean canDetermineObscurity() { return true; }
 
     // DropTarget support
@@ -101,19 +103,21 @@
     int nDropTargets;
     long nativeDropTargetContext; // native pointer
 
-    public synchronized native void pShow();
-    public synchronized native void hide();
-    public synchronized native void enable();
-    public synchronized native void disable();
+    private synchronized native void pShow();
+    synchronized native void hide();
+    synchronized native void enable();
+    synchronized native void disable();
 
     public long getHWnd() {
         return hwnd;
     }
 
     /* New 1.1 API */
+    @Override
     public native Point getLocationOnScreen();
 
     /* New 1.1 API */
+    @Override
     public void setVisible(boolean b) {
         if (b) {
             show();
@@ -130,6 +134,7 @@
     }
 
     /* New 1.1 API */
+    @Override
     public void setEnabled(boolean b) {
         if (b) {
             enable();
@@ -143,6 +148,7 @@
     private native void reshapeNoCheck(int x, int y, int width, int height);
 
     /* New 1.1 API */
+    @Override
     public void setBounds(int x, int y, int width, int height, int op) {
         // Should set paintPending before reahape to prevent
         // thread race between paint events
@@ -185,6 +191,7 @@
         final Container cont = (Container)target;
 
         WToolkit.executeOnEventHandlerThread(cont, new Runnable() {
+            @Override
             public void run() {
                 // Discarding old paint events doesn't seem to be necessary.
                 cont.invalidate();
@@ -228,6 +235,7 @@
 
     native synchronized void updateWindow();
 
+    @Override
     public void paint(Graphics g) {
         ((Component)target).paint(g);
     }
@@ -239,6 +247,7 @@
     private native int[] createPrintedPixels(int srcX, int srcY,
                                              int srcW, int srcH,
                                              int alpha);
+    @Override
     public void print(Graphics g) {
 
         Component comp = (Component)target;
@@ -275,6 +284,7 @@
         comp.print(g);
     }
 
+    @Override
     public void coalescePaintEvent(PaintEvent e) {
         Rectangle r = e.getUpdateRect();
         if (!(e instanceof IgnorePaintEvent)) {
@@ -319,6 +329,7 @@
 
     native void nativeHandleEvent(AWTEvent e);
 
+    @Override
     @SuppressWarnings("fallthrough")
     public void handleEvent(AWTEvent e) {
         int id = e.getID();
@@ -367,21 +378,25 @@
 
     native void setFocus(boolean doSetFocus);
 
+    @Override
     public Dimension getMinimumSize() {
         return ((Component)target).getSize();
     }
 
+    @Override
     public Dimension getPreferredSize() {
         return getMinimumSize();
     }
 
     // Do nothing for heavyweight implementation
+    @Override
     public void layout() {}
 
     public Rectangle getBounds() {
         return ((Component)target).getBounds();
     }
 
+    @Override
     public boolean isFocusable() {
         return false;
     }
@@ -390,6 +405,7 @@
      * Return the GraphicsConfiguration associated with this peer, either
      * the locally stored winGraphicsConfig, or that of the target Component.
      */
+    @Override
     public GraphicsConfiguration getGraphicsConfiguration() {
         if (winGraphicsConfig != null) {
             return winGraphicsConfig;
@@ -481,6 +497,7 @@
 
     public void replaceSurfaceDataLater() {
         Runnable r = new Runnable() {
+            @Override
             public void run() {
                 // Shouldn't do anything if object is disposed in meanwhile
                 // No need for sync as disposeAction in Window is performed
@@ -501,6 +518,7 @@
         }
     }
 
+    @Override
     public boolean updateGraphicsData(GraphicsConfiguration gc) {
         winGraphicsConfig = (Win32GraphicsConfig)gc;
         try {
@@ -512,6 +530,7 @@
     }
 
     //This will return null for Components not yet added to a Container
+    @Override
     public ColorModel getColorModel() {
         GraphicsConfiguration gc = getGraphicsConfiguration();
         if (gc != null) {
@@ -549,6 +568,7 @@
     // fallback default font object
     final static Font defaultFont = new Font(Font.DIALOG, Font.PLAIN, 12);
 
+    @Override
     @SuppressWarnings("deprecation")
     public Graphics getGraphics() {
         if (isDisposed()) {
@@ -601,11 +621,13 @@
         }
         return null;
     }
+    @Override
     public FontMetrics getFontMetrics(Font font) {
         return WFontMetrics.getFontMetrics(font);
     }
 
     private synchronized native void _dispose();
+    @Override
     protected void disposeImpl() {
         SurfaceData oldData = surfaceData;
         surfaceData = null;
@@ -618,17 +640,20 @@
 
     public void disposeLater() {
         postEvent(new InvocationEvent(target, new Runnable() {
+            @Override
             public void run() {
                 dispose();
             }
         }));
     }
 
+    @Override
     public synchronized void setForeground(Color c) {
         foreground = c;
         _setForeground(c.getRGB());
     }
 
+    @Override
     public synchronized void setBackground(Color c) {
         background = c;
         _setBackground(c.getRGB());
@@ -644,19 +669,22 @@
         return background;
     }
 
-    public native void _setForeground(int rgb);
-    public native void _setBackground(int rgb);
+    private native void _setForeground(int rgb);
+    private native void _setBackground(int rgb);
 
+    @Override
     public synchronized void setFont(Font f) {
         font = f;
         _setFont(f);
     }
-    public synchronized native void _setFont(Font f);
+    synchronized native void _setFont(Font f);
+    @Override
     public void updateCursorImmediately() {
         WGlobalCursorManager.getCursorManager().updateCursorImmediately();
     }
 
     // TODO: consider moving it to KeyboardFocusManagerPeerImpl
+    @Override
     @SuppressWarnings("deprecation")
     public boolean requestFocus(Component lightweightChild, boolean temporary,
                                 boolean focusedWindowChangeAllowed, long time,
@@ -720,24 +748,29 @@
         return false;
     }
 
+    @Override
     public Image createImage(ImageProducer producer) {
         return new ToolkitImage(producer);
     }
 
+    @Override
     public Image createImage(int width, int height) {
         Win32GraphicsConfig gc =
             (Win32GraphicsConfig)getGraphicsConfiguration();
         return gc.createAcceleratedImage((Component)target, width, height);
     }
 
+    @Override
     public VolatileImage createVolatileImage(int width, int height) {
         return new SunVolatileImage((Component)target, width, height);
     }
 
+    @Override
     public boolean prepareImage(Image img, int w, int h, ImageObserver o) {
         return Toolkit.getDefaultToolkit().prepareImage(img, w, h, o);
     }
 
+    @Override
     public int checkImage(Image img, int w, int h, ImageObserver o) {
         return Toolkit.getDefaultToolkit().checkImage(img, w, h, o);
     }
@@ -891,6 +924,7 @@
      * register a DropTarget with this native peer
      */
 
+    @Override
     public synchronized void addDropTarget(DropTarget dt) {
         if (nDropTargets == 0) {
             nativeDropTargetContext = addNativeDropTarget();
@@ -902,6 +936,7 @@
      * unregister a DropTarget with this native peer
      */
 
+    @Override
     public synchronized void removeDropTarget(DropTarget dt) {
         nDropTargets--;
         if (nDropTargets == 0) {
@@ -924,6 +959,7 @@
     native void removeNativeDropTarget();
     native boolean nativeHandlesWheelScrolling();
 
+    @Override
     public boolean handlesWheelScrolling() {
         // should this be cached?
         return nativeHandlesWheelScrolling();
@@ -1001,6 +1037,7 @@
     /**
      * @see java.awt.peer.ComponentPeer#reparent
      */
+    @Override
     public void reparent(ContainerPeer newNativeParent) {
         pSetParent(newNativeParent);
     }
@@ -1008,6 +1045,7 @@
     /**
      * @see java.awt.peer.ComponentPeer#isReparentSupported
      */
+    @Override
     public boolean isReparentSupported() {
         return true;
     }
@@ -1081,6 +1119,7 @@
      * Applies the shape to the native component window.
      * @since 1.7
      */
+    @Override
     @SuppressWarnings("deprecation")
     public void applyShape(Region shape) {
         if (shapeLog.isLoggable(PlatformLogger.Level.FINER)) {
@@ -1101,6 +1140,7 @@
      * Lowers this component at the bottom of the above component. If the above parameter
      * is null then the method places this component at the top of the Z-order.
      */
+    @Override
     public void setZOrder(ComponentPeer above) {
         long aboveHWND = (above != null) ? ((WComponentPeer)above).getHWnd() : 0;
 
--- a/jdk/src/windows/classes/sun/awt/windows/WCustomCursor.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WCustomCursor.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,13 +38,14 @@
  * @see Component#setCursor
  * @author      ThomasBall
  */
-public class WCustomCursor extends CustomCursor {
+final class WCustomCursor extends CustomCursor {
 
-    public WCustomCursor(Image cursor, Point hotSpot, String name)
+    WCustomCursor(Image cursor, Point hotSpot, String name)
             throws IndexOutOfBoundsException {
         super(cursor, hotSpot, name);
     }
 
+    @Override
     protected void createNativeCursor(Image im, int[] pixels, int w, int h,
                                       int xHotSpot, int yHotSpot) {
         BufferedImage bimage = new BufferedImage(w, h,
--- a/jdk/src/windows/classes/sun/awt/windows/WDataTransferer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WDataTransferer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 
 import java.io.BufferedInputStream;
 import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.IOException;
@@ -85,7 +84,7 @@
  *
  * @since 1.3.1
  */
-public class WDataTransferer extends DataTransferer {
+final class WDataTransferer extends DataTransferer {
     private static final String[] predefinedClipboardNames = {
             "",
             "TEXT",
@@ -159,17 +158,14 @@
 
     private static WDataTransferer transferer;
 
-    public static WDataTransferer getInstanceImpl() {
+    static synchronized WDataTransferer getInstanceImpl() {
         if (transferer == null) {
-            synchronized (WDataTransferer.class) {
-                if (transferer == null) {
-                    transferer = new WDataTransferer();
-                }
-            }
+            transferer = new WDataTransferer();
         }
         return transferer;
     }
 
+    @Override
     public SortedMap <Long, DataFlavor> getFormatsForFlavors(
             DataFlavor[] flavors, FlavorTable map)
     {
@@ -183,10 +179,12 @@
         return retval;
     }
 
+    @Override
     public String getDefaultUnicodeEncoding() {
         return "utf-16le";
     }
 
+    @Override
     public byte[] translateTransferable(Transferable contents,
                                         DataFlavor flavor,
                                         long format) throws IOException
@@ -224,6 +222,7 @@
     }
 
     // The stream is closed as a closable object
+    @Override
     public Object translateStream(InputStream str,
                                  DataFlavor flavor, long format,
                                  Transferable localeTransferable)
@@ -239,6 +238,7 @@
 
     }
 
+    @Override
     public Object translateBytes(byte[] bytes, DataFlavor flavor, long format,
         Transferable localeTransferable) throws IOException
     {
@@ -286,14 +286,17 @@
 
     }
 
+    @Override
     public boolean isLocaleDependentTextFormat(long format) {
         return format == CF_TEXT || format == CFSTR_INETURL;
     }
 
+    @Override
     public boolean isFileFormat(long format) {
         return format == CF_HDROP || format == CF_FILEGROUPDESCRIPTORA || format == CF_FILEGROUPDESCRIPTORW;
     }
 
+    @Override
     protected Long getFormatForNativeAsLong(String str) {
         Long format = predefinedClipboardNameMap.get(str);
         if (format == null) {
@@ -302,6 +305,7 @@
         return format;
     }
 
+    @Override
     protected String getNativeForFormat(long format) {
         return (format < predefinedClipboardNames.length)
                 ? predefinedClipboardNames[(int)format]
@@ -311,6 +315,7 @@
     private final ToolkitThreadBlockedHandler handler =
             new WToolkitThreadBlockedHandler();
 
+    @Override
     public ToolkitThreadBlockedHandler getToolkitThreadBlockedHandler() {
         return handler;
     }
@@ -327,12 +332,14 @@
      */
     private static native String getClipboardFormatName(long format);
 
+    @Override
     public boolean isImageFormat(long format) {
         return format == CF_DIB || format == CF_ENHMETAFILE ||
                 format == CF_METAFILEPICT || format == CF_PNG ||
                 format == CF_JFIF;
     }
 
+    @Override
     protected byte[] imageToPlatformBytes(Image image, long format)
             throws IOException {
         String mimeType = null;
@@ -406,6 +413,7 @@
 
     private static final byte [] UNICODE_NULL_TERMINATOR =  new byte [] {0,0};
 
+    @Override
     protected ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList)
             throws IOException
     {
@@ -443,6 +451,7 @@
      * Translates either a byte array or an input stream which contain
      * platform-specific image data in the given format into an Image.
      */
+    @Override
     protected Image platformImageBytesToImage(byte[] bytes, long format)
             throws IOException {
         String mimeType = null;
@@ -482,12 +491,14 @@
                                                        long format)
             throws IOException;
 
+    @Override
     protected native String[] dragQueryFile(byte[] bytes);
 }
 
 final class WToolkitThreadBlockedHandler extends Mutex
         implements ToolkitThreadBlockedHandler {
 
+    @Override
     public void enter() {
         if (!isOwned()) {
             throw new IllegalMonitorStateException();
@@ -497,6 +508,7 @@
         lock();
     }
 
+    @Override
     public void exit() {
         if (!isOwned()) {
             throw new IllegalMonitorStateException();
@@ -880,6 +892,7 @@
         descriptionParsed = true;
     }
 
+    @Override
     public synchronized int read() throws IOException {
         if( closed ){
             throw new IOException("Stream closed");
@@ -900,6 +913,7 @@
         return retval;
     }
 
+    @Override
     public synchronized void close() throws IOException {
         if( !closed ){
             closed = true;
--- a/jdk/src/windows/classes/sun/awt/windows/WDefaultFontCharset.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WDefaultFontCharset.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 import java.nio.charset.*;
 import sun.awt.AWTCharset;
 
-public class WDefaultFontCharset extends AWTCharset
+final class WDefaultFontCharset extends AWTCharset
 {
     static {
        initIDs();
@@ -36,22 +36,24 @@
     // Name for Windows FontSet.
     private String fontName;
 
-    public WDefaultFontCharset(String name){
+    WDefaultFontCharset(String name){
         super("WDefaultFontCharset", Charset.forName("windows-1252"));
         fontName = name;
     }
 
+    @Override
     public CharsetEncoder newEncoder() {
         return new Encoder();
     }
 
     private class Encoder extends AWTCharset.Encoder {
+        @Override
         public boolean canEncode(char c){
             return canConvert(c);
         }
     }
 
-    public synchronized native boolean canConvert(char ch);
+    private synchronized native boolean canConvert(char ch);
 
     /**
      * Initialize JNI field and method IDs
--- a/jdk/src/windows/classes/sun/awt/windows/WDesktopPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WDesktopPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,33 +39,39 @@
  *
  * @see DesktopPeer
  */
-public class WDesktopPeer implements DesktopPeer {
+final class WDesktopPeer implements DesktopPeer {
     /* Contants for the operation verbs */
     private static String ACTION_OPEN_VERB = "open";
     private static String ACTION_EDIT_VERB = "edit";
     private static String ACTION_PRINT_VERB = "print";
 
+    @Override
     public boolean isSupported(Action action) {
         // OPEN, EDIT, PRINT, MAIL, BROWSE all supported on windows.
         return true;
     }
 
+    @Override
     public void open(File file) throws IOException {
         this.ShellExecute(file, ACTION_OPEN_VERB);
     }
 
+    @Override
     public void edit(File file) throws IOException {
         this.ShellExecute(file, ACTION_EDIT_VERB);
     }
 
+    @Override
     public void print(File file) throws IOException {
         this.ShellExecute(file, ACTION_PRINT_VERB);
     }
 
+    @Override
     public void mail(URI uri) throws IOException {
         this.ShellExecute(uri, ACTION_OPEN_VERB);
     }
 
+    @Override
     public void browse(URI uri) throws IOException {
         this.ShellExecute(uri, ACTION_OPEN_VERB);
     }
--- a/jdk/src/windows/classes/sun/awt/windows/WDesktopProperties.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WDesktopProperties.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 @@
  * like the Windows Pluggable Look-and-Feel can better adapt
  * itself when running on a Windows platform.
  */
-class WDesktopProperties {
+final class WDesktopProperties {
     private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.windows.WDesktopProperties");
     private static final String PREFIX = "win.";
     private static final String FILE_PREFIX = "awt.file.";
@@ -210,6 +210,7 @@
             this.winEventName = winEventName;
         }
 
+        @Override
         public void run() {
             WDesktopProperties.this.playWindowsSound(winEventName);
         }
--- a/jdk/src/windows/classes/sun/awt/windows/WDialogPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WDialogPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,14 +24,13 @@
  */
 package sun.awt.windows;
 
-import java.util.*;
 import java.awt.*;
 import java.awt.peer.*;
 
 import sun.awt.*;
 import sun.awt.im.*;
 
-class WDialogPeer extends WWindowPeer implements DialogPeer {
+final class WDialogPeer extends WWindowPeer implements DialogPeer {
     // Toolkit & peer internals
 
     // Platform default background for dialogs.  Gets set on target if
@@ -54,6 +53,7 @@
     }
 
     native void createAwtDialog(WComponentPeer parent);
+    @Override
     void create(WComponentPeer parent) {
         preCreate(parent);
         createAwtDialog(parent);
@@ -62,6 +62,7 @@
     native void showModal();
     native void endModal();
 
+    @Override
     void initialize() {
         Dialog target = (Dialog)this.target;
         // Need to set target's background to default _before_ a call
@@ -78,6 +79,7 @@
         setResizable(target.isResizable());
     }
 
+    @Override
     protected void realShow() {
         Dialog dlg = (Dialog)target;
         if (dlg.getModalityType() != Dialog.ModalityType.MODELESS) {
@@ -87,8 +89,9 @@
         }
     }
 
+    @Override
     @SuppressWarnings("deprecation")
-    public void hide() {
+    void hide() {
         Dialog dlg = (Dialog)target;
         if (dlg.getModalityType() != Dialog.ModalityType.MODELESS) {
             endModal();
@@ -97,6 +100,7 @@
         }
     }
 
+    @Override
     public void blockWindows(java.util.List<Window> toBlock) {
         for (Window w : toBlock) {
             WWindowPeer wp = (WWindowPeer)AWTAccessor.getComponentAccessor().getPeer(w);
@@ -106,6 +110,7 @@
         }
     }
 
+    @Override
     public Dimension getMinimumSize() {
         if (((Dialog)target).isUndecorated()) {
             return super.getMinimumSize();
@@ -119,6 +124,7 @@
         return ((Dialog)target).isUndecorated();
     }
 
+    @Override
     public void reshape(int x, int y, int width, int height) {
         if (((Dialog)target).isUndecorated()) {
             super.reshape(x, y, width, height);
--- a/jdk/src/windows/classes/sun/awt/windows/WDropTargetContextPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WDropTargetContextPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -79,6 +79,7 @@
         return new WDropTargetContextPeerIStream(istream);
     }
 
+    @Override
     protected Object getNativeData(long format) {
         return getData(getNativeDragContext(), format);
     }
@@ -87,14 +88,17 @@
      * signal drop complete
      */
 
+    @Override
     protected void doDropDone(boolean success, int dropAction,
                               boolean isLocal) {
         dropDone(getNativeDragContext(), success, dropAction);
     }
 
+    @Override
     protected void eventPosted(final SunDropTargetEvent e) {
         if (e.getID() != SunDropTargetEvent.MOUSE_DROPPED) {
             Runnable runnable = new Runnable() {
+                    @Override
                     public void run() {
                         e.getDispatcher().unregisterAllEvents();
                     }
@@ -124,7 +128,7 @@
  * package private class to handle file transfers
  */
 
-class WDropTargetContextPeerFileStream extends FileInputStream {
+final class WDropTargetContextPeerFileStream extends FileInputStream {
 
     /**
      * construct file input stream
@@ -142,6 +146,7 @@
      * close
      */
 
+    @Override
     public void close() throws IOException {
         if (stgmedium != 0) {
             super.close();
@@ -167,7 +172,7 @@
  * Package private class to access IStream objects
  */
 
-class WDropTargetContextPeerIStream extends InputStream {
+final class WDropTargetContextPeerIStream extends InputStream {
 
     /**
      * construct a WDropTargetContextPeerIStream wrapper
@@ -185,6 +190,7 @@
      * @return bytes available
      */
 
+    @Override
     public int available() throws IOException {
         if (istream == 0) throw new IOException("No IStream");
         return Available(istream);
@@ -196,6 +202,7 @@
      * read
      */
 
+    @Override
     public int read() throws IOException {
         if (istream == 0) throw new IOException("No IStream");
         return Read(istream);
@@ -207,6 +214,7 @@
      * read into buffer
      */
 
+    @Override
     public int read(byte[] b, int off, int len) throws IOException {
         if (istream == 0) throw new IOException("No IStream");
         return ReadBytes(istream, b, off, len);
@@ -218,6 +226,7 @@
      * close
      */
 
+    @Override
     public void close() throws IOException {
         if (istream != 0) {
             super.close();
--- a/jdk/src/windows/classes/sun/awt/windows/WEmbeddedFrame.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WEmbeddedFrame.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -203,11 +203,11 @@
     }
 
 
-    protected native boolean isPrinterDC(long hdc);
+    private native boolean isPrinterDC(long hdc);
 
-    protected native void printBand(long hdc, byte[] data, int offset,
-                                    int sx, int sy, int swidth, int sheight,
-                                    int dx, int dy, int dwidth, int dheight);
+    private native void printBand(long hdc, byte[] data, int offset, int sx,
+                                  int sy, int swidth, int sheight, int dx,
+                                  int dy, int dwidth, int dheight);
 
     /**
      * Initialize JNI field IDs
--- a/jdk/src/windows/classes/sun/awt/windows/WEmbeddedFramePeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WEmbeddedFramePeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,15 @@
         super(target);
     }
 
+    @Override
     native void create(WComponentPeer parent);
 
     // suppress printing of an embedded frame.
+    @Override
     public void print(Graphics g) {}
 
     // supress calling native setMinSize()
+    @Override
     public void updateMinimumSize() {}
 
     @Override
@@ -59,10 +62,12 @@
         ((EmbeddedFrame)target).notifyModalBlocked(blocker, false);
     }
 
+    @Override
     public void setBoundsPrivate(int x, int y, int width, int height) {
         setBounds(x, y, width, height, SET_BOUNDS | NO_EMBEDDED_CHECK);
     }
 
+    @Override
     public native Rectangle getBoundsPrivate();
 
     @Override
--- a/jdk/src/windows/classes/sun/awt/windows/WFileDialogPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WFileDialogPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,10 @@
 import java.util.ResourceBundle;
 import java.util.MissingResourceException;
 import java.util.Vector;
-import sun.awt.AppContext;
 import sun.awt.CausedFocusEvent;
 import sun.awt.AWTAccessor;
 
-public class WFileDialogPeer extends WWindowPeer implements FileDialogPeer {
+final class WFileDialogPeer extends WWindowPeer implements FileDialogPeer {
 
     static {
         initIDs();
@@ -47,11 +46,12 @@
     private WComponentPeer parent;
     private FilenameFilter fileFilter;
 
-    private Vector<WWindowPeer> blockedWindows = new Vector<WWindowPeer>();
+    private Vector<WWindowPeer> blockedWindows = new Vector<>();
 
     //Needed to fix 4152317
     private static native void setFilterString(String allFilter);
 
+    @Override
     public void setFilenameFilter(FilenameFilter filter) {
         this.fileFilter = filter;
     }
@@ -70,19 +70,23 @@
         super(target);
     }
 
+    @Override
     void create(WComponentPeer parent) {
         this.parent = parent;
     }
 
     // don't use checkCreation() from WComponentPeer to avoid hwnd check
+    @Override
     protected void checkCreation() {
     }
 
+    @Override
     void initialize() {
         setFilenameFilter(((FileDialog) target).getFilenameFilter());
     }
 
     private native void _dispose();
+    @Override
     protected void disposeImpl() {
         WToolkit.targetDisposedPeer(target, this);
         _dispose();
@@ -91,15 +95,18 @@
     private native void _show();
     private native void _hide();
 
+    @Override
     public void show() {
         new Thread(new Runnable() {
+            @Override
             public void run() {
                 _show();
             }
         }).start();
     }
 
-    public void hide() {
+    @Override
+    void hide() {
         _hide();
     }
 
@@ -169,6 +176,7 @@
         fileDialogAccessor.setFiles(fileDialog, jFiles);
 
         WToolkit.executeOnEventHandlerThread(fileDialog, new Runnable() {
+             @Override
              public void run() {
                  fileDialog.setVisible(false);
              }
@@ -185,6 +193,7 @@
         AWTAccessor.getFileDialogAccessor().setDirectory(fileDialog, null);
 
         WToolkit.executeOnEventHandlerThread(fileDialog, new Runnable() {
+             @Override
              public void run() {
                  fileDialog.setVisible(false);
              }
@@ -195,6 +204,7 @@
     static {
         String filterString = AccessController.doPrivileged(
             new PrivilegedAction<String>() {
+                @Override
                 public String run() {
                     try {
                         ResourceBundle rb = ResourceBundle.getBundle("sun.awt.windows.awtLocalization");
@@ -224,6 +234,7 @@
         }
     }
 
+    @Override
     public void blockWindows(java.util.List<Window> toBlock) {
         for (Window w : toBlock) {
             WWindowPeer wp = (WWindowPeer)AWTAccessor.getComponentAccessor().getPeer(w);
@@ -233,31 +244,47 @@
         }
     }
 
+    @Override
     public native void toFront();
+    @Override
     public native void toBack();
 
     // unused methods.  Overridden to disable this functionality as
     // it requires HWND which is not available for FileDialog
+    @Override
     public void updateAlwaysOnTopState() {}
+    @Override
     public void setDirectory(String dir) {}
+    @Override
     public void setFile(String file) {}
+    @Override
     public void setTitle(String title) {}
 
+    @Override
     public void setResizable(boolean resizable) {}
-    public void enable() {}
-    public void disable() {}
+    @Override
+    void enable() {}
+    @Override
+    void disable() {}
+    @Override
     public void reshape(int x, int y, int width, int height) {}
     public boolean handleEvent(Event e) { return false; }
+    @Override
     public void setForeground(Color c) {}
+    @Override
     public void setBackground(Color c) {}
+    @Override
     public void setFont(Font f) {}
+    @Override
     public void updateMinimumSize() {}
+    @Override
     public void updateIconImages() {}
     public boolean requestFocus(boolean temporary,
                                 boolean focusedWindowChangeAllowed) {
         return false;
     }
 
+    @Override
     public boolean requestFocus
          (Component lightweightChild, boolean temporary,
           boolean focusedWindowChangeAllowed, long time, CausedFocusEvent.Cause cause)
@@ -265,13 +292,20 @@
         return false;
     }
 
+    @Override
     void start() {}
+    @Override
     public void beginValidate() {}
+    @Override
     public void endValidate() {}
     void invalidate(int x, int y, int width, int height) {}
+    @Override
     public void addDropTarget(DropTarget dt) {}
+    @Override
     public void removeDropTarget(DropTarget dt) {}
+    @Override
     public void updateFocusableWindowState() {}
+    @Override
     public void setZOrder(ComponentPeer above) {}
 
     /**
@@ -280,8 +314,11 @@
     private static native void initIDs();
 
     // The effects are not supported for system dialogs.
+    @Override
     public void applyShape(sun.java2d.pipe.Region shape) {}
+    @Override
     public void setOpacity(float opacity) {}
+    @Override
     public void setOpaque(boolean isOpaque) {}
     public void updateWindow(java.awt.image.BufferedImage backBuffer) {}
 
--- a/jdk/src/windows/classes/sun/awt/windows/WFontConfiguration.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WFontConfiguration.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,12 +29,10 @@
 import java.util.Hashtable;
 import sun.awt.FontDescriptor;
 import sun.awt.FontConfiguration;
-import sun.font.FontManager;
 import sun.font.SunFontManager;
-import sun.java2d.SunGraphicsEnvironment;
 import java.nio.charset.*;
 
-public class WFontConfiguration extends FontConfiguration {
+public final class WFontConfiguration extends FontConfiguration {
 
     // whether compatibility fallbacks for TimesRoman and Co. are used
     private boolean useCompatibilityFallbacks;
@@ -52,6 +50,7 @@
         useCompatibilityFallbacks = "windows-1252".equals(encoding);
     }
 
+    @Override
     protected void initReorderMap() {
         if (encoding.equalsIgnoreCase("windows-31j")) {
             localeMap = new Hashtable();
@@ -81,6 +80,7 @@
 //      reorderMap.put("windows-1252", "alphabetic");
     }
 
+    @Override
     protected void setOsNameAndVersion(){
         super.setOsNameAndVersion();
         if (osName.startsWith("Windows")){
@@ -103,6 +103,7 @@
     }
 
     // overrides FontConfiguration.getFallbackFamilyName
+    @Override
     public String getFallbackFamilyName(String fontName, String defaultFallback) {
         // maintain compatibility with old font.properties files, where
         // default file had aliases for timesroman & Co, while others didn't.
@@ -115,6 +116,7 @@
         return defaultFallback;
     }
 
+    @Override
     protected String makeAWTFontName(String platformFontName, String characterSubsetName) {
         String windowsCharset = (String) subsetCharsetMap.get(characterSubsetName);
         if (windowsCharset == null) {
@@ -123,6 +125,7 @@
         return platformFontName + "," + windowsCharset;
     }
 
+    @Override
     protected String getEncoding(String awtFontName, String characterSubsetName) {
         String encoding = (String) subsetEncodingMap.get(characterSubsetName);
         if (encoding == null) {
@@ -131,15 +134,18 @@
         return encoding;
     }
 
+    @Override
     protected Charset getDefaultFontCharset(String fontName) {
         return new WDefaultFontCharset(fontName);
     }
 
+    @Override
     public String getFaceNameFromComponentFontName(String componentFontName) {
         // for Windows, the platform name is the face name
         return componentFontName;
     }
 
+    @Override
     protected String getFileNameFromComponentFontName(String componentFontName) {
         return getFileNameFromPlatformName(componentFontName);
     }
--- a/jdk/src/windows/classes/sun/awt/windows/WFontMetrics.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WFontMetrics.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 1997, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +33,7 @@
  *
  * @author Jim Graham
  */
-class WFontMetrics extends FontMetrics {
+final class WFontMetrics extends FontMetrics {
 
     static {
         initIDs();
@@ -117,6 +117,7 @@
     /**
      * Get leading
      */
+    @Override
     public int getLeading() {
         return leading;
     }
@@ -124,6 +125,7 @@
     /**
      * Get ascent.
      */
+    @Override
     public int getAscent() {
         return ascent;
     }
@@ -131,6 +133,7 @@
     /**
      * Get descent
      */
+    @Override
     public int getDescent() {
         return descent;
     }
@@ -138,6 +141,7 @@
     /**
      * Get height
      */
+    @Override
     public int getHeight() {
         return height;
     }
@@ -145,6 +149,7 @@
     /**
      * Get maxAscent
      */
+    @Override
     public int getMaxAscent() {
         return maxAscent;
     }
@@ -152,6 +157,7 @@
     /**
      * Get maxDescent
      */
+    @Override
     public int getMaxDescent() {
         return maxDescent;
     }
@@ -159,6 +165,7 @@
     /**
      * Get maxAdvance
      */
+    @Override
     public int getMaxAdvance() {
         return maxAdvance;
     }
@@ -166,21 +173,25 @@
     /**
      * Return the width of the specified string in this Font.
      */
+    @Override
     public native int stringWidth(String str);
 
     /**
      * Return the width of the specified char[] in this Font.
      */
+    @Override
     public native int charsWidth(char data[], int off, int len);
 
     /**
      * Return the width of the specified byte[] in this Font.
      */
+    @Override
     public native int bytesWidth(byte data[], int off, int len);
 
     /**
      * Get the widths of the first 256 characters in the font.
      */
+    @Override
     public int[] getWidths() {
         return widths;
     }
--- a/jdk/src/windows/classes/sun/awt/windows/WFontPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WFontPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 
 import sun.awt.PlatformFont;
 
-public class WFontPeer extends PlatformFont {
+final class WFontPeer extends PlatformFont {
 
     private String textComponentFontName;
 
@@ -38,6 +38,7 @@
         }
     }
 
+    @Override
     protected char getMissingGlyphCharacter() {
         return '\u2751';
     }
--- a/jdk/src/windows/classes/sun/awt/windows/WFramePeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WFramePeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,9 @@
     private static native void initIDs();
 
     // FramePeer implementation
+    @Override
     public native void setState(int state);
+    @Override
     public native int getState();
 
     // sync target and peer
@@ -62,6 +64,7 @@
             new GetPropertyAction(
             "sun.awt.keepWorkingSetOnMinimize")));
 
+    @Override
     public void setMaximizedBounds(Rectangle b) {
         if (b == null) {
             clearMaximizedBounds();
@@ -123,6 +126,7 @@
         return ((Frame)target).isUndecorated();
     }
 
+    @Override
     public void reshape(int x, int y, int width, int height) {
         if (((Frame)target).isUndecorated()) {
             super.reshape(x, y, width, height);
@@ -131,6 +135,7 @@
         }
     }
 
+    @Override
     public Dimension getMinimumSize() {
         Dimension d = new Dimension();
         if (!((Frame)target).isUndecorated()) {
@@ -145,6 +150,7 @@
     // Note: Because this method calls resize(), which may be overridden
     // by client code, this method must not be executed on the toolkit
     // thread.
+    @Override
     public void setMenuBar(MenuBar mb) {
         WMenuBarPeer mbPeer = (WMenuBarPeer) WToolkit.targetToPeer(mb);
         setMenuBar0(mbPeer);
@@ -170,11 +176,13 @@
     }
 
     native void createAwtFrame(WComponentPeer parent);
+    @Override
     void create(WComponentPeer parent) {
         preCreate(parent);
         createAwtFrame(parent);
     }
 
+    @Override
     void initialize() {
         super.initialize();
 
@@ -194,14 +202,17 @@
       InputMethodManager.getInstance().notifyChangeRequest((Component)target);
     }
 
+    @Override
     public void setBoundsPrivate(int x, int y, int width, int height) {
         setBounds(x, y, width, height, SET_BOUNDS);
     }
+    @Override
     public Rectangle getBoundsPrivate() {
         return getBounds();
     }
 
     // TODO: implement it in peers. WLightweightFramePeer may implement lw version.
+    @Override
     public void emulateActivation(boolean activate) {
         synthesizeWmActivate(activate);
     }
--- a/jdk/src/windows/classes/sun/awt/windows/WGlobalCursorManager.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WGlobalCursorManager.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +28,7 @@
 import java.awt.*;
 import sun.awt.GlobalCursorManager;
 
-public final class WGlobalCursorManager extends GlobalCursorManager {
+final class WGlobalCursorManager extends GlobalCursorManager {
     private static WGlobalCursorManager manager;
 
     public static GlobalCursorManager getCursorManager() {
@@ -46,12 +46,16 @@
         WGlobalCursorManager.getCursorManager().updateCursorLater(heavy);
     }
 
+    @Override
     protected native void setCursor(Component comp, Cursor cursor, boolean u);
+    @Override
     protected native void getCursorPos(Point p);
     /*
      * two native methods to call corresponding methods in Container and
      * Component
      */
+    @Override
     protected native Component findHeavyweightUnderCursor(boolean useCache);
+    @Override
     protected native Point getLocationOnScreen(Component com);
 }
--- a/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 import java.util.Map;
 import sun.awt.im.InputMethodAdapter;
 
-public class WInputMethod extends InputMethodAdapter
+final class WInputMethod extends InputMethodAdapter
 {
     /**
      * The input method context, which is used to dispatch input method
@@ -127,6 +127,7 @@
         }
     }
 
+    @Override
     protected void finalize() throws Throwable
     {
         // Release the resources used by the native input context.
@@ -137,10 +138,12 @@
         super.finalize();
     }
 
+    @Override
     public synchronized void setInputMethodContext(InputMethodContext context) {
         inputContext = context;
     }
 
+    @Override
     public final void dispose() {
         // Due to a memory management problem in Windows 98, we should retain
         // the native input context until this object is finalized. So do
@@ -152,10 +155,12 @@
      *
      * @see java.awt.im.spi.InputMethod#getControlObject
      */
+    @Override
     public Object getControlObject() {
         return null;
     }
 
+    @Override
     public boolean setLocale(Locale lang) {
         return setLocale(lang, false);
     }
@@ -178,6 +183,7 @@
         return false;
     }
 
+    @Override
     public Locale getLocale() {
         if (isActive) {
             currentLocale = getNativeLocale();
@@ -193,6 +199,7 @@
      *
      * @see java.awt.im.spi.InputMethod#setCharacterSubsets
      */
+    @Override
     public void setCharacterSubsets(Subset[] subsets) {
         if (subsets == null){
             setConversionStatus(context, cmode);
@@ -266,6 +273,7 @@
         }
     }
 
+    @Override
     public void dispatchEvent(AWTEvent e) {
         if (e instanceof ComponentEvent) {
             Component comp = ((ComponentEvent) e).getComponent();
@@ -281,6 +289,7 @@
         }
     }
 
+    @Override
     public void activate() {
         boolean isAc = haveActiveClient();
 
@@ -317,6 +326,7 @@
 
     }
 
+    @Override
     public void deactivate(boolean isTemporary)
     {
         // Sync currentLocale with the Windows keyboard layout which might be changed
@@ -336,6 +346,7 @@
      * Explicitly disable the native IME. Native IME is not disabled when
      * deactivate is called.
      */
+    @Override
     public void disableInputMethod() {
         if (lastFocussedComponentPeer != null) {
             disableNativeIME(lastFocussedComponentPeer);
@@ -348,6 +359,7 @@
      * Returns a string with information about the windows input method,
      * or null.
      */
+    @Override
     public String getNativeInputMethodInfo() {
         return getNativeIMMDescription();
     }
@@ -358,6 +370,7 @@
      * Calling stopListening to give other input method the keybaord input
      * focus.
      */
+    @Override
     protected void stopListening() {
         // Since the native input method is not disabled when deactivate is
         // called, we need to call disableInputMethod to explicitly turn off the
@@ -366,6 +379,7 @@
     }
 
     // implements sun.awt.im.InputMethodAdapter.setAWTFocussedComponent
+    @Override
     protected void setAWTFocussedComponent(Component component) {
         if (component == null) {
             return;
@@ -386,6 +400,7 @@
     }
 
     // implements java.awt.im.spi.InputMethod.hideWindows
+    @Override
     public void hideWindows() {
         if (awtFocussedComponentPeer != null) {
             /* Hide the native status window including the Windows language
@@ -401,6 +416,7 @@
     /**
      * @see java.awt.im.spi.InputMethod#removeNotify
      */
+    @Override
     public void removeNotify() {
         endCompositionNative(context, DISCARD_INPUT);
         awtFocussedComponent = null;
@@ -427,10 +443,12 @@
     }
 
     // see sun.awt.im.InputMethodAdapter.supportsBelowTheSpot
+    @Override
     protected boolean supportsBelowTheSpot() {
         return true;
     }
 
+    @Override
     public void endComposition()
     {
         //right now the native endCompositionNative() just cancel
@@ -442,6 +460,7 @@
     /**
      * @see java.awt.im.spi.InputMethod#setCompositionEnabled(boolean)
      */
+    @Override
     public void setCompositionEnabled(boolean enable) {
         setOpenStatus(context, enable);
     }
@@ -449,6 +468,7 @@
     /**
      * @see java.awt.im.spi.InputMethod#isCompositionEnabled
      */
+    @Override
     public boolean isCompositionEnabled() {
         return getOpenStatus(context);
     }
@@ -557,6 +577,7 @@
         // AWT Event thread.  Otherwise, a potential deadlock
         // could happen.
         Runnable r = new Runnable() {
+            @Override
             public void run() {
                 int x = 0;
                 int y = 0;
--- a/jdk/src/windows/classes/sun/awt/windows/WInputMethodDescriptor.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WInputMethodDescriptor.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,11 +40,12 @@
  * @since JDK1.3
  */
 
-class WInputMethodDescriptor implements InputMethodDescriptor {
+final class WInputMethodDescriptor implements InputMethodDescriptor {
 
     /**
      * @see java.awt.im.spi.InputMethodDescriptor#getAvailableLocales
      */
+    @Override
     public Locale[] getAvailableLocales() {
         // returns a copy of internal list for public API
         Locale[] locales = getAvailableLocalesInternal();
@@ -60,6 +61,7 @@
     /**
      * @see java.awt.im.spi.InputMethodDescriptor#hasDynamicLocaleList
      */
+    @Override
     public boolean hasDynamicLocaleList() {
         return true;
     }
@@ -67,6 +69,7 @@
     /**
      * @see java.awt.im.spi.InputMethodDescriptor#getInputMethodDisplayName
      */
+    @Override
     public synchronized String getInputMethodDisplayName(Locale inputLocale, Locale displayLanguage) {
         // We ignore the input locale.
         // When displaying for the default locale, rely on the localized AWT properties;
@@ -81,6 +84,7 @@
     /**
      * @see java.awt.im.spi.InputMethodDescriptor#getInputMethodIcon
      */
+    @Override
     public Image getInputMethodIcon(Locale inputLocale) {
         return null;
     }
@@ -88,6 +92,7 @@
     /**
      * @see java.awt.im.spi.InputMethodDescriptor#createInputMethod
      */
+    @Override
     public InputMethod createInputMethod() throws Exception {
         return new WInputMethod();
     }
--- a/jdk/src/windows/classes/sun/awt/windows/WKeyboardFocusManagerPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WKeyboardFocusManagerPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +31,7 @@
 import sun.awt.KeyboardFocusManagerPeerImpl;
 import sun.awt.CausedFocusEvent;
 
-class WKeyboardFocusManagerPeer extends KeyboardFocusManagerPeerImpl {
+final class WKeyboardFocusManagerPeer extends KeyboardFocusManagerPeerImpl {
     static native void setNativeFocusOwner(ComponentPeer peer);
     static native Component getNativeFocusOwner();
     static native Window getNativeFocusedWindow();
--- a/jdk/src/windows/classes/sun/awt/windows/WListPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WListPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,12 +31,14 @@
 
 final class WListPeer extends WComponentPeer implements ListPeer {
 
+    @Override
     public boolean isFocusable() {
         return true;
     }
 
     // ListPeer implementation
 
+    @Override
     public int[] getSelectedIndexes() {
         List l = (List)target;
         int len = l.countItems();
@@ -53,26 +55,31 @@
     }
 
     /* New method name for 1.1 */
+    @Override
     public void add(String item, int index) {
         addItem(item, index);
     }
 
     /* New method name for 1.1 */
+    @Override
     public void removeAll() {
         clear();
     }
 
     /* New method name for 1.1 */
+    @Override
     public void setMultipleMode (boolean b) {
         setMultipleSelections(b);
     }
 
     /* New method name for 1.1 */
+    @Override
     public Dimension getPreferredSize(int rows) {
         return preferredSize(rows);
     }
 
     /* New method name for 1.1 */
+    @Override
     public Dimension getMinimumSize(int rows) {
         return minimumSize(rows);
     }
@@ -83,13 +90,17 @@
     }
     native void addItems(String[] items, int index, int width);
 
+    @Override
     public native void delItems(int start, int end);
     public void clear() {
         List l = (List)target;
         delItems(0, l.countItems());
     }
+    @Override
     public native void select(int index);
+    @Override
     public native void deselect(int index);
+    @Override
     public native void makeVisible(int index);
     public native void setMultipleSelections(boolean v);
     public native int  getMaxWidth();
@@ -114,8 +125,10 @@
         super(target);
     }
 
+    @Override
     native void create(WComponentPeer parent);
 
+    @Override
     void initialize() {
         List li = (List)target;
 
@@ -169,6 +182,7 @@
         super.initialize();
     }
 
+    @Override
     public boolean shouldClearRectBeforePaint() {
         return false;
     }
@@ -178,7 +192,8 @@
     /*public*/ native boolean isSelected(int index);
 
     // update the fontmetrics when the font changes
-    public synchronized void _setFont(Font f)
+    @Override
+    synchronized void _setFont(Font f)
     {
         super._setFont( f );
             fm = getFontMetrics( ((List)target).getFont() );
@@ -190,6 +205,7 @@
     void handleAction(final int index, final long when, final int modifiers) {
         final List l = (List)target;
         WToolkit.executeOnEventHandlerThread(l, new Runnable() {
+            @Override
             public void run() {
                 l.select(index);
                 postEvent(new ActionEvent(target, ActionEvent.ACTION_PERFORMED,
@@ -201,6 +217,7 @@
     void handleListChanged(final int index) {
         final List l = (List)target;
         WToolkit.executeOnEventHandlerThread(l, new Runnable() {
+            @Override
             public void run() {
                 postEvent(new ItemEvent(l, ItemEvent.ITEM_STATE_CHANGED,
                                 Integer.valueOf(index),
--- a/jdk/src/windows/classes/sun/awt/windows/WMenuBarPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WMenuBarPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,16 @@
 import java.awt.*;
 import java.awt.peer.*;
 
-class WMenuBarPeer extends WMenuPeer implements MenuBarPeer {
+final class WMenuBarPeer extends WMenuPeer implements MenuBarPeer {
 
     // MenuBarPeer implementation
 
+    @Override
     public native void addMenu(Menu m);
+    @Override
     public native void delMenu(int index);
 
+    @Override
     public void addHelpMenu(Menu m) {
         addMenu(m);
     }
--- a/jdk/src/windows/classes/sun/awt/windows/WMenuPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WMenuPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,10 +31,13 @@
 
     // MenuPeer implementation
 
+    @Override
     public native void addSeparator();
+    @Override
     public void addItem(MenuItem item) {
         WMenuItemPeer itemPeer = (WMenuItemPeer) WToolkit.targetToPeer(item);
     }
+    @Override
     public native void delItem(int index);
 
     // Toolkit & peer internals
--- a/jdk/src/windows/classes/sun/awt/windows/WMouseDragGestureRecognizer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WMouseDragGestureRecognizer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,19 +25,14 @@
 
 package sun.awt.windows;
 
-import java.awt.Toolkit;
 import java.awt.Component;
-
 import java.awt.Point;
 import java.awt.dnd.DnDConstants;
+import java.awt.dnd.DragGestureListener;
 import java.awt.dnd.DragSource;
 import java.awt.dnd.MouseDragGestureRecognizer;
-import java.awt.dnd.DragGestureListener;
-
 import java.awt.event.InputEvent;
 import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import java.awt.event.MouseMotionListener;
 
 import sun.awt.dnd.SunDragSourceContextPeer;
 
@@ -54,7 +49,7 @@
  * @see java.awt.dnd.DragSource
  */
 
-class WMouseDragGestureRecognizer extends MouseDragGestureRecognizer {
+final class WMouseDragGestureRecognizer extends MouseDragGestureRecognizer {
 
     private static final long serialVersionUID = -3527844310018033570L;
 
@@ -140,6 +135,7 @@
      * Invoked when the mouse has been clicked on a component.
      */
 
+    @Override
     public void mouseClicked(MouseEvent e) {
         // do nothing
     }
@@ -148,6 +144,7 @@
      * Invoked when a mouse button has been pressed on a component.
      */
 
+    @Override
     public void mousePressed(MouseEvent e) {
         events.clear();
 
@@ -165,6 +162,7 @@
      * Invoked when a mouse button has been released on a component.
      */
 
+    @Override
     public void mouseReleased(MouseEvent e) {
         events.clear();
     }
@@ -173,6 +171,7 @@
      * Invoked when the mouse enters a component.
      */
 
+    @Override
     public void mouseEntered(MouseEvent e) {
         events.clear();
     }
@@ -181,6 +180,7 @@
      * Invoked when the mouse exits a component.
      */
 
+    @Override
     public void mouseExited(MouseEvent e) {
 
         if (!events.isEmpty()) { // gesture pending
@@ -196,6 +196,7 @@
      * Invoked when a mouse button is pressed on a component.
      */
 
+    @Override
     public void mouseDragged(MouseEvent e) {
         if (!events.isEmpty()) { // gesture pending
             int dop = mapDragOperationFromModifiers(e);
@@ -225,6 +226,7 @@
      * (with no buttons no down).
      */
 
+    @Override
     public void mouseMoved(MouseEvent e) {
         // do nothing
     }
--- a/jdk/src/windows/classes/sun/awt/windows/WPageDialog.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WPageDialog.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +34,7 @@
 import java.awt.print.PageFormat;
 import java.awt.print.Printable;
 
-public class WPageDialog extends WPrintDialog {
+final class WPageDialog extends WPrintDialog {
     static {
         initIDs();
     }
@@ -55,6 +55,7 @@
         this.painter = painter;
     }
 
+    @Override
     @SuppressWarnings("deprecation")
     public void addNotify() {
         synchronized(getTreeLock()) {
--- a/jdk/src/windows/classes/sun/awt/windows/WPageDialogPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WPageDialogPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 
 package sun.awt.windows;
 
-public class WPageDialogPeer extends WPrintDialogPeer {
+final class WPageDialogPeer extends WPrintDialogPeer {
 
     WPageDialogPeer(WPageDialog target) {
         super(target);
@@ -37,8 +37,10 @@
      */
     private native boolean _show();
 
+    @Override
     public void show() {
         new Thread(new Runnable() {
+                @Override
                 public void run() {
                     // Call pageSetup even with no printer installed, this
                     // will display Windows error dialog and return false.
--- a/jdk/src/windows/classes/sun/awt/windows/WPanelPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WPanelPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,13 @@
 import java.awt.*;
 import java.awt.peer.*;
 
-import java.util.Vector;
-
 import sun.awt.SunGraphicsCallback;
 
 class WPanelPeer extends WCanvasPeer implements PanelPeer {
 
     // ComponentPeer overrides
 
+    @Override
     public void paint(Graphics g) {
         super.paint(g);
         SunGraphicsCallback.PaintHeavyweightComponentsCallback.getInstance().
@@ -42,6 +41,7 @@
                           SunGraphicsCallback.LIGHTWEIGHTS |
                           SunGraphicsCallback.HEAVYWEIGHTS);
     }
+    @Override
     public void print(Graphics g) {
         super.print(g);
         SunGraphicsCallback.PrintHeavyweightComponentsCallback.getInstance().
@@ -52,6 +52,7 @@
 
     // ContainerPeer (via PanelPeer) implementation
 
+    @Override
     public Insets getInsets() {
         return insets_;
     }
@@ -73,6 +74,7 @@
         super(target);
     }
 
+    @Override
     void initialize() {
         super.initialize();
         insets_ = new Insets(0,0,0,0);
--- a/jdk/src/windows/classes/sun/awt/windows/WPathGraphics.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WPathGraphics.java	Wed Jul 05 19:33:51 2017 +0200
@@ -74,7 +74,7 @@
 import sun.print.PathGraphics;
 import sun.print.ProxyGraphics2D;
 
-class WPathGraphics extends PathGraphics {
+final class WPathGraphics extends PathGraphics {
 
     /**
      * For a drawing application the initial user space
@@ -896,6 +896,7 @@
      * @param   handlingTransparency if being recursively called to
      *                    print opaque region of transparent image
      */
+    @Override
     protected boolean drawImageToPlatform(Image image, AffineTransform xform,
                                           Color bgcolor,
                                           int srcX, int srcY,
@@ -1335,6 +1336,7 @@
      * Have the printing application redraw everything that falls
      * within the page bounds defined by <code>region</code>.
      */
+    @Override
     public void redrawRegion(Rectangle2D region, double scaleX, double scaleY,
                              Shape savedClip, AffineTransform savedTransform)
             throws PrinterException {
@@ -1434,6 +1436,7 @@
      * with the specified color.
      * The path is provided in device coordinates.
      */
+    @Override
     protected void deviceFill(PathIterator pathIter, Color color) {
 
         WPrinterJob wPrinterJob = (WPrinterJob) getPrinterJob();
@@ -1448,6 +1451,7 @@
      * path defined by <code>pathIter</code>
      * The path is provided in device coordinates.
      */
+    @Override
     protected void deviceClip(PathIterator pathIter) {
 
         WPrinterJob wPrinterJob = (WPrinterJob) getPrinterJob();
@@ -1459,6 +1463,7 @@
     /**
      * Draw the bounding rectangle using transformed coordinates.
      */
+     @Override
      protected void deviceFrameRect(int x, int y, int width, int height,
                                      Color color) {
 
@@ -1548,6 +1553,7 @@
       * GDI fillRect function.
       * Boundaries are determined by the given coordinates.
       */
+    @Override
     protected void deviceFillRect(int x, int y, int width, int height,
                                   Color color) {
         /*
@@ -1584,6 +1590,7 @@
      * Draw a line using a pen created using the specified color
      * and current stroke properties.
      */
+    @Override
     protected void deviceDrawLine(int xBegin, int yBegin, int xEnd, int yEnd,
                                   Color color) {
         Stroke stroke = getStroke();
--- a/jdk/src/windows/classes/sun/awt/windows/WPopupMenuPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WPopupMenuPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,12 +29,12 @@
 
 import sun.awt.AWTAccessor;
 
-public class WPopupMenuPeer extends WMenuPeer implements PopupMenuPeer {
+final class WPopupMenuPeer extends WMenuPeer implements PopupMenuPeer {
     // We can't use target.getParent() for TrayIcon popup
     // because this method should return null for the TrayIcon
     // popup regardless of that whether it has parent or not.
 
-    public WPopupMenuPeer(PopupMenu target) {
+    WPopupMenuPeer(PopupMenu target) {
         this.target = target;
         MenuContainer parent = null;
 
@@ -67,7 +67,7 @@
         }
     }
 
-    native void createMenu(WComponentPeer parent);
+    private native void createMenu(WComponentPeer parent);
 
     public void show(Event e) {
         Component origin = (Component)e.target;
@@ -106,5 +106,5 @@
         _show(e);
     }
 
-    public native void _show(Event e);
+    private native void _show(Event e);
 }
--- a/jdk/src/windows/classes/sun/awt/windows/WPrintDialog.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WPrintDialog.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +30,9 @@
 
 import java.awt.print.PrinterJob;
 
-public class WPrintDialog extends Dialog {
+import sun.awt.AWTAccessor;
+
+class WPrintDialog extends Dialog {
     static {
         initIDs();
     }
@@ -38,21 +40,23 @@
     protected PrintJob job;
     protected PrinterJob pjob;
 
-    public WPrintDialog(Frame parent, PrinterJob control) {
+    WPrintDialog(Frame parent, PrinterJob control) {
         super(parent, true);
         this.pjob = control;
         setLayout(null);
     }
 
-    public WPrintDialog(Dialog parent, PrinterJob control) {
+    WPrintDialog(Dialog parent, PrinterJob control) {
         super(parent, "", true);
         this.pjob = control;
         setLayout(null);
     }
 
-    // Use native code to circumvent access restrictions on Component.peer
-    protected native void setPeer(ComponentPeer peer);
+    final void setPeer(final ComponentPeer p){
+        AWTAccessor.getComponentAccessor().setPeer(this, p);
+    }
 
+    @Override
     @SuppressWarnings("deprecation")
     public void addNotify() {
         synchronized(getTreeLock()) {
@@ -72,11 +76,11 @@
 
     private boolean retval = false;
 
-    public void setRetVal(boolean ret) {
+    final void setRetVal(boolean ret) {
         retval = ret;
     }
 
-    public boolean getRetVal() {
+    final boolean getRetVal() {
         return retval;
     }
 
--- a/jdk/src/windows/classes/sun/awt/windows/WPrintDialogPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WPrintDialogPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,11 +30,10 @@
 import java.awt.peer.ComponentPeer;
 import java.awt.dnd.DropTarget;
 import java.util.Vector;
-import sun.awt.AppContext;
 import sun.awt.CausedFocusEvent;
 import sun.awt.AWTAccessor;
 
-public class WPrintDialogPeer extends WWindowPeer implements DialogPeer {
+class WPrintDialogPeer extends WWindowPeer implements DialogPeer {
 
     static {
         initIDs();
@@ -42,29 +41,34 @@
 
     private WComponentPeer parent;
 
-    private Vector<WWindowPeer> blockedWindows = new Vector<WWindowPeer>();
+    private Vector<WWindowPeer> blockedWindows = new Vector<>();
 
     WPrintDialogPeer(WPrintDialog target) {
         super(target);
     }
 
+    @Override
     void create(WComponentPeer parent) {
         this.parent = parent;
     }
 
     // fix for CR 6178323:
     // don't use checkCreation() from WComponentPeer to avoid hwnd check
+    @Override
     protected void checkCreation() {
     }
 
+    @Override
     protected void disposeImpl() {
         WToolkit.targetDisposedPeer(target, this);
     }
 
     private native boolean _show();
 
+    @Override
     public void show() {
         new Thread(new Runnable() {
+            @Override
             public void run() {
                 try {
                     ((WPrintDialog)target).setRetVal(_show());
@@ -102,6 +106,7 @@
         }
     }
 
+    @Override
     public void blockWindows(java.util.List<Window> toBlock) {
         for (Window w : toBlock) {
             WWindowPeer wp = (WWindowPeer)AWTAccessor.getComponentAccessor().getPeer(w);
@@ -111,28 +116,43 @@
         }
     }
 
+    @Override
     public native void toFront();
+    @Override
     public native void toBack();
 
     // unused methods.  Overridden to disable this functionality as
     // it requires HWND which is not available for FileDialog
+    @Override
     void initialize() {}
+    @Override
     public void updateAlwaysOnTopState() {}
+    @Override
     public void setResizable(boolean resizable) {}
-    public void hide() {}
-    public void enable() {}
-    public void disable() {}
+    @Override
+    void hide() {}
+    @Override
+    void enable() {}
+    @Override
+    void disable() {}
+    @Override
     public void reshape(int x, int y, int width, int height) {}
     public boolean handleEvent(Event e) { return false; }
+    @Override
     public void setForeground(Color c) {}
+    @Override
     public void setBackground(Color c) {}
+    @Override
     public void setFont(Font f) {}
+    @Override
     public void updateMinimumSize() {}
+    @Override
     public void updateIconImages() {}
     public boolean requestFocus(boolean temporary, boolean focusedWindowChangeAllowed) {
         return false;
     }
 
+    @Override
     public boolean requestFocus
          (Component lightweightChild, boolean temporary,
           boolean focusedWindowChangeAllowed, long time, CausedFocusEvent.Cause cause)
@@ -141,13 +161,20 @@
         return false;
     }
 
+    @Override
     public void updateFocusableWindowState() {}
+    @Override
     void start() {}
+    @Override
     public void beginValidate() {}
+    @Override
     public void endValidate() {}
     void invalidate(int x, int y, int width, int height) {}
+    @Override
     public void addDropTarget(DropTarget dt) {}
+    @Override
     public void removeDropTarget(DropTarget dt) {}
+    @Override
     public void setZOrder(ComponentPeer above) {}
 
     /**
@@ -156,8 +183,11 @@
     private static native void initIDs();
 
     // The effects are not supported for system dialogs.
+    @Override
     public void applyShape(sun.java2d.pipe.Region shape) {}
+    @Override
     public void setOpacity(float opacity) {}
+    @Override
     public void setOpaque(boolean isOpaque) {}
     public void updateWindow(java.awt.image.BufferedImage backBuffer) {}
 
--- a/jdk/src/windows/classes/sun/awt/windows/WPrinterJob.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WPrinterJob.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -57,26 +57,19 @@
 import java.awt.print.PrinterException;
 import javax.print.PrintService;
 
-import java.io.IOException;
 import java.io.File;
 
-import java.util.Hashtable;
-import java.util.Properties;
 import java.util.MissingResourceException;
 import java.util.ResourceBundle;
 
-import sun.awt.Win32GraphicsEnvironment;
-
 import sun.print.PeekGraphics;
 import sun.print.PeekMetrics;
 
-import java.net.URL;
 import java.net.URI;
 import java.net.URISyntaxException;
 
 import javax.print.PrintServiceLookup;
 import javax.print.attribute.PrintRequestAttributeSet;
-import javax.print.attribute.HashPrintServiceAttributeSet;
 import javax.print.attribute.HashPrintRequestAttributeSet;
 import javax.print.attribute.Attribute;
 import javax.print.attribute.standard.Sides;
@@ -84,7 +77,6 @@
 import javax.print.attribute.standard.PrintQuality;
 import javax.print.attribute.standard.PrinterResolution;
 import javax.print.attribute.standard.SheetCollate;
-import javax.print.attribute.IntegerSyntax;
 import javax.print.attribute.standard.Copies;
 import javax.print.attribute.standard.Destination;
 import javax.print.attribute.standard.OrientationRequested;
@@ -92,17 +84,13 @@
 import javax.print.attribute.standard.MediaSizeName;
 import javax.print.attribute.standard.MediaSize;
 import javax.print.attribute.standard.MediaTray;
-import javax.print.attribute.standard.PrinterName;
-import javax.print.attribute.standard.JobMediaSheetsSupported;
 import javax.print.attribute.standard.PageRanges;
-import javax.print.attribute.Size2DSyntax;
 
 import sun.awt.Win32FontManager;
 
 import sun.print.RasterPrinterJob;
 import sun.print.SunAlternateMedia;
 import sun.print.SunPageSelection;
-import sun.print.SunMinMaxPage;
 import sun.print.Win32MediaTray;
 import sun.print.Win32PrintService;
 import sun.print.Win32PrintServiceLookup;
@@ -121,7 +109,8 @@
  *
  * @author Richard Blanchard
  */
-public class WPrinterJob extends RasterPrinterJob implements DisposerTarget {
+public final class WPrinterJob extends RasterPrinterJob
+        implements DisposerTarget {
 
  /* Class Constants */
 
@@ -290,6 +279,7 @@
         private long mPrintHDevMode;
         private long mPrintHDevNames;
 
+        @Override
         public void dispose() {
             WPrinterJob.deleteDC(mPrintDC, mPrintHDevMode, mPrintHDevNames);
         }
@@ -402,6 +392,7 @@
      */
     private Object disposerReferent = new Object();
 
+    @Override
     public Object getDisposerReferent() {
         return disposerReferent;
     }
@@ -430,6 +421,7 @@
      * @see java.awt.GraphicsEnvironment#isHeadless
      * @since     JDK1.2
      */
+    @Override
     public PageFormat pageDialog(PageFormat page) throws HeadlessException {
         if (GraphicsEnvironment.isHeadless()) {
             throw new HeadlessException();
@@ -570,6 +562,7 @@
      * returns true.
      * @see java.awt.GraphicsEnvironment#isHeadless
      */
+    @Override
     public boolean printDialog() throws HeadlessException {
 
         if (GraphicsEnvironment.isHeadless()) {
@@ -603,6 +596,7 @@
      * @throws PrinterException if the specified service does not support
      * 2D printing.
      */
+    @Override
     public void setPrintService(PrintService service)
         throws PrinterException {
         super.setPrintService(service);
@@ -628,6 +622,7 @@
         }
     }
 
+    @Override
     public PrintService getPrintService() {
         if (myService == null) {
             String printerName = getNativePrintService();
@@ -681,6 +676,7 @@
      * In the event that the user changes the printer using the
       dialog, then it is up to GDI to report back all changed values.
      */
+    @Override
     protected void setAttributes(PrintRequestAttributeSet attributes)
         throws PrinterException {
 
@@ -705,7 +701,9 @@
                     setColorAttrib(attr);
                 }
                 else if (attr.getCategory() == PrinterResolution.class) {
-                    setResolutionAttrib(attr);
+                    if (myService.isAttributeValueSupported(attr, null, null)) {
+                        setResolutionAttrib(attr);
+                    }
                 }
                 else if (attr.getCategory() == PrintQuality.class) {
                     setQualityAttrib(attr);
@@ -750,6 +748,7 @@
      * Note: PageFormat.getPaper() returns a clone and getDefaultPage()
      * gets that clone so it won't overwrite the original paper.
      */
+    @Override
     public PageFormat defaultPage(PageFormat page) {
         PageFormat newPage = (PageFormat)page.clone();
         getDefaultPage(newPage);
@@ -759,6 +758,7 @@
     /**
      * validate the paper size against the current printer.
      */
+    @Override
     protected native void validatePaper(Paper origPaper, Paper newPaper );
 
     /**
@@ -774,6 +774,7 @@
      * causes the print job to be rasterized.
      */
 
+    @Override
     protected Graphics2D createPathGraphics(PeekGraphics peekGraphics,
                                             PrinterJob printerJob,
                                             Printable painter,
@@ -810,6 +811,7 @@
     }
 
 
+    @Override
     protected double getXRes() {
         if (mAttXRes != 0) {
             return mAttXRes;
@@ -818,6 +820,7 @@
         }
     }
 
+    @Override
     protected double getYRes() {
         if (mAttYRes != 0) {
             return mAttYRes;
@@ -826,26 +829,32 @@
         }
     }
 
+    @Override
     protected double getPhysicalPrintableX(Paper p) {
         return mPrintPhysX;
     }
 
+    @Override
     protected double getPhysicalPrintableY(Paper p) {
         return mPrintPhysY;
     }
 
+    @Override
     protected double getPhysicalPrintableWidth(Paper p) {
         return mPrintWidth;
     }
 
+    @Override
     protected double getPhysicalPrintableHeight(Paper p) {
         return mPrintHeight;
     }
 
+    @Override
     protected double getPhysicalPageWidth(Paper p) {
         return mPageWidth;
     }
 
+    @Override
     protected double getPhysicalPageHeight(Paper p) {
         return mPageHeight;
     }
@@ -857,6 +866,7 @@
      * collation requests - which can only originate from the print dialog.
      * REMIND: check if this can be deleted already.
      */
+    @Override
     protected boolean isCollated() {
         return userRequestedCollation;
     }
@@ -869,6 +879,7 @@
      * book need only be printed once and the copies
      * will be collated and made in the printer.
      */
+    @Override
     protected int getCollatedCopies() {
         debug_println("driverDoesMultipleCopies="+driverDoesMultipleCopies
                       +" driverDoesCollation="+driverDoesCollation);
@@ -891,6 +902,7 @@
      * iterate over the number of copies, this method always returns
      * 1.
      */
+    @Override
     protected int getNoncollatedCopies() {
         if (driverDoesMultipleCopies || super.isCollated()) {
             return 1;
@@ -1128,6 +1140,7 @@
     /**
      * Remove control characters.
      */
+    @Override
     protected String removeControlChars(String str) {
         return super.removeControlChars(str);
     }
@@ -1267,6 +1280,7 @@
     /**
      * Begin a new page.
      */
+    @Override
     protected void startPage(PageFormat format, Printable painter,
                              int index, boolean paperChanged) {
 
@@ -1283,6 +1297,7 @@
     /**
      * End a page.
      */
+    @Override
     protected void endPage(PageFormat format, Printable painter,
                            int index) {
 
@@ -1302,6 +1317,7 @@
     /**
      * Set the number of copies to be printed.
      */
+    @Override
     public void setCopies(int copies) {
         super.setCopies(copies);
         defaultCopies = false;
@@ -1315,7 +1331,7 @@
     /**
      * Set copies in device.
      */
-    public native void setNativeCopies(int copies);
+    private native void setNativeCopies(int copies);
 
     /**
      * Displays the print dialog and records the user's settings
@@ -1328,6 +1344,7 @@
     /* Make sure printer DC is intialised and that info about the printer
      * is reflected back up to Java code
      */
+    @Override
     protected native void initPrinter();
 
     /**
@@ -1343,6 +1360,7 @@
      */
     private native boolean _startDoc(String dest, String jobName)
                                      throws PrinterException;
+    @Override
     protected void startDoc() throws PrinterException {
         if (!_startDoc(mDestination, getJobName())) {
             cancel();
@@ -1353,12 +1371,14 @@
      * Call Window's EndDoc routine to end a
      * print job.
      */
+    @Override
     protected native void endDoc();
 
     /**
      * Call Window's AbortDoc routine to abort a
      * print job.
      */
+    @Override
     protected native void abortDoc();
 
     /**
@@ -1386,6 +1406,7 @@
      * page. The width and height of the band is
      * specified by the caller.
      */
+    @Override
     protected native void printBand(byte[] data, int x, int y,
                                     int width, int height);
 
@@ -2204,6 +2225,7 @@
         }
     }
 
+    @Override
     public void actionPerformed(ActionEvent event) {
         setVisible(false);
         dispose();
--- a/jdk/src/windows/classes/sun/awt/windows/WRobotPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WRobotPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +28,7 @@
 import java.awt.*;
 import java.awt.peer.RobotPeer;
 
-class WRobotPeer extends WObjectPeer implements RobotPeer
+final class WRobotPeer extends WObjectPeer implements RobotPeer
 {
     WRobotPeer() {
         create();
@@ -39,27 +39,36 @@
 
     private synchronized native void _dispose();
 
+    @Override
     protected void disposeImpl() {
         _dispose();
     }
 
     public native void create();
     public native void mouseMoveImpl(int x, int y);
+    @Override
     public void mouseMove(int x, int y) {
         mouseMoveImpl(x, y);
     }
+    @Override
     public native void mousePress(int buttons);
+    @Override
     public native void mouseRelease(int buttons);
+    @Override
     public native void mouseWheel(int wheelAmt);
 
+    @Override
     public native void keyPress( int keycode );
+    @Override
     public native void keyRelease( int keycode );
 
+    @Override
     public int getRGBPixel(int x, int y) {
          // See 7002846: that's ineffective, but works correctly with non-opaque windows
         return getRGBPixels(new Rectangle(x, y, 1, 1))[0];
     }
 
+    @Override
     public int [] getRGBPixels(Rectangle bounds) {
         int pixelArray[] = new int[bounds.width*bounds.height];
         getRGBPixels(bounds.x, bounds.y, bounds.width, bounds.height, pixelArray);
--- a/jdk/src/windows/classes/sun/awt/windows/WScrollPanePeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WScrollPanePeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +33,7 @@
 
 import sun.util.logging.PlatformLogger;
 
-class WScrollPanePeer extends WPanelPeer implements ScrollPanePeer {
+final class WScrollPanePeer extends WPanelPeer implements ScrollPanePeer {
 
     private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.windows.WScrollPanePeer");
 
@@ -47,6 +47,7 @@
     }
 
     static native void initIDs();
+    @Override
     native void create(WComponentPeer parent);
     native int getOffset(int orient);
 
@@ -56,6 +57,7 @@
         scrollbarHeight = _getHScrollbarHeight();
     }
 
+    @Override
     void initialize() {
         super.initialize();
         setInsets();
@@ -63,22 +65,27 @@
         setScrollPosition(-i.left,-i.top);
     }
 
+    @Override
     public void setUnitIncrement(Adjustable adj, int p) {
         // The unitIncrement is grabbed from the target as needed.
     }
 
+    @Override
     public Insets insets() {
         return getInsets();
     }
     private native void setInsets();
 
+    @Override
     public native synchronized void setScrollPosition(int x, int y);
 
+    @Override
     public int getHScrollbarHeight() {
         return scrollbarHeight;
     }
     private native int _getHScrollbarHeight();
 
+    @Override
     public int getVScrollbarWidth() {
         return scrollbarWidth;
     }
@@ -96,6 +103,7 @@
      * the actual windows may not have changed yet, so the size
      * information from the java-level is passed down and used.
      */
+    @Override
     public void childResized(int width, int height) {
         ScrollPane sp = (ScrollPane)target;
         Dimension vs = sp.getSize();
@@ -112,6 +120,7 @@
      * of adjustables, whether it was modified externally or from the
      * native scrollbars themselves.
      */
+    @Override
     public void setValue(Adjustable adj, int v) {
         Component c = getScrollChild();
         if (c == null) {
@@ -160,6 +169,7 @@
             super(source, runnable, 0L);
         }
 
+        @Override
         public PeerEvent coalesceEvents(PeerEvent newEvent) {
             if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                 log.finest("ScrollEvent coalesced: " + newEvent);
@@ -187,6 +197,7 @@
             this.isAdjusting = isAdjusting;
         }
 
+        @Override
         public void run() {
             if (getScrollChild() == null) {
                 return;
--- a/jdk/src/windows/classes/sun/awt/windows/WSystemTrayPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WSystemTrayPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,11 +30,12 @@
 import java.awt.Toolkit;
 import java.awt.peer.SystemTrayPeer;
 
-public class WSystemTrayPeer extends WObjectPeer implements SystemTrayPeer {
+final class WSystemTrayPeer extends WObjectPeer implements SystemTrayPeer {
     WSystemTrayPeer(SystemTray target) {
         this.target = target;
     }
 
+    @Override
     public Dimension getTrayIconSize() {
         return new Dimension(WTrayIconPeer.TRAY_ICON_WIDTH, WTrayIconPeer.TRAY_ICON_HEIGHT);
     }
@@ -43,6 +44,7 @@
         return ((WToolkit)Toolkit.getDefaultToolkit()).isTraySupported();
     }
 
+    @Override
     protected void disposeImpl() {
     }
 }
--- a/jdk/src/windows/classes/sun/awt/windows/WTextAreaPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WTextAreaPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -53,6 +53,7 @@
     public Dimension getPreferredSize(int rows, int cols) {
         return getMinimumSize(rows, cols);
     }
+
     @Override
     public Dimension getMinimumSize(int rows, int cols) {
         FontMetrics fm = getFontMetrics(((TextArea)target).getFont());
--- a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 import sun.awt.SunToolkit;
 import sun.awt.Win32GraphicsDevice;
 import sun.awt.Win32GraphicsEnvironment;
+import sun.awt.datatransfer.DataTransferer;
 import sun.java2d.d3d.D3DRenderQueue;
 import sun.java2d.opengl.OGLRenderQueue;
 
@@ -66,7 +67,7 @@
 import sun.misc.PerformanceLogger;
 import sun.util.logging.PlatformLogger;
 
-public class WToolkit extends SunToolkit implements Runnable {
+public final class WToolkit extends SunToolkit implements Runnable {
 
     private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.windows.WToolkit");
 
@@ -97,6 +98,7 @@
         if (!loaded) {
             java.security.AccessController.doPrivileged(
                 new java.security.PrivilegedAction<Void>() {
+                    @Override
                     public Void run() {
                         System.loadLibrary("awt");
                         return null;
@@ -120,6 +122,7 @@
         AccessController.doPrivileged(
             new PrivilegedAction <Void> ()
         {
+            @Override
             public Void run() {
                 String browserProp = System.getProperty("browser");
                 if (browserProp != null && browserProp.equals("sun.plugin")) {
@@ -210,9 +213,8 @@
      */
     public native void embeddedEventLoopIdleProcessing();
 
-    public static final String DATA_TRANSFERER_CLASS_NAME = "sun.awt.windows.WDataTransferer";
-
     static class ToolkitDisposer implements sun.java2d.DisposerRecord {
+        @Override
         public void dispose() {
             WToolkit.postDispose();
         }
@@ -255,8 +257,6 @@
             // swallow the exception
         }
 
-        SunToolkit.setDataTransfererClassName(DATA_TRANSFERER_CLASS_NAME);
-
         // Enabled "live resizing" by default.  It remains controlled
         // by the native system though.
         setDynamicLayout(true);
@@ -269,6 +269,7 @@
 
     private final void registerShutdownHook() {
         AccessController.doPrivileged(new PrivilegedAction<Void>() {
+            @Override
             public Void run() {
                 ThreadGroup currentTG =
                     Thread.currentThread().getThreadGroup();
@@ -278,6 +279,7 @@
                     parentTG = currentTG.getParent();
                 }
                 Thread shutdown = new Thread(currentTG, new Runnable() {
+                    @Override
                     public void run() {
                         shutdown();
                     }
@@ -289,6 +291,7 @@
         });
      }
 
+    @Override
     public void run() {
         Thread.currentThread().setPriority(Thread.NORM_PRIORITY+1);
         boolean startPump = init();
@@ -333,85 +336,98 @@
      * WARNING: startSecondaryEventLoop must only be called from the "AWT-
      * Windows" thread.
      */
-    public static native void startSecondaryEventLoop();
-    public static native void quitSecondaryEventLoop();
+    static native void startSecondaryEventLoop();
+    static native void quitSecondaryEventLoop();
 
     /*
      * Create peer objects.
      */
 
+    @Override
     public ButtonPeer createButton(Button target) {
         ButtonPeer peer = new WButtonPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public TextFieldPeer createTextField(TextField target) {
         TextFieldPeer peer = new WTextFieldPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public LabelPeer createLabel(Label target) {
         LabelPeer peer = new WLabelPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public ListPeer createList(List target) {
         ListPeer peer = new WListPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public CheckboxPeer createCheckbox(Checkbox target) {
         CheckboxPeer peer = new WCheckboxPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public ScrollbarPeer createScrollbar(Scrollbar target) {
         ScrollbarPeer peer = new WScrollbarPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public ScrollPanePeer createScrollPane(ScrollPane target) {
         ScrollPanePeer peer = new WScrollPanePeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public TextAreaPeer createTextArea(TextArea target) {
         TextAreaPeer peer = new WTextAreaPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public ChoicePeer createChoice(Choice target) {
         ChoicePeer peer = new WChoicePeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public FramePeer  createFrame(Frame target) {
         FramePeer peer = new WFramePeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public FramePeer createLightweightFrame(LightweightFrame target) {
         FramePeer peer = new WLightweightFramePeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public CanvasPeer createCanvas(Canvas target) {
         CanvasPeer peer = new WCanvasPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     @SuppressWarnings("deprecation")
     public void disableBackgroundErase(Canvas canvas) {
         WCanvasPeer peer = (WCanvasPeer)canvas.getPeer();
@@ -421,60 +437,70 @@
         peer.disableBackgroundErase();
     }
 
+    @Override
     public PanelPeer createPanel(Panel target) {
         PanelPeer peer = new WPanelPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public WindowPeer createWindow(Window target) {
         WindowPeer peer = new WWindowPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public DialogPeer createDialog(Dialog target) {
         DialogPeer peer = new WDialogPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public FileDialogPeer createFileDialog(FileDialog target) {
         FileDialogPeer peer = new WFileDialogPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public MenuBarPeer createMenuBar(MenuBar target) {
         MenuBarPeer peer = new WMenuBarPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public MenuPeer createMenu(Menu target) {
         MenuPeer peer = new WMenuPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public PopupMenuPeer createPopupMenu(PopupMenu target) {
         PopupMenuPeer peer = new WPopupMenuPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public MenuItemPeer createMenuItem(MenuItem target) {
         MenuItemPeer peer = new WMenuItemPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public CheckboxMenuItemPeer createCheckboxMenuItem(CheckboxMenuItem target) {
         CheckboxMenuItemPeer peer = new WCheckboxMenuItemPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public RobotPeer createRobot(Robot target, GraphicsDevice screen) {
         // (target is unused for now)
         // Robot's don't need to go in the peer map since
@@ -500,28 +526,38 @@
         return peer;
     }
 
+    @Override
     public TrayIconPeer createTrayIcon(TrayIcon target) {
         WTrayIconPeer peer = new WTrayIconPeer(target);
         targetCreatedPeer(target, peer);
         return peer;
     }
 
+    @Override
     public SystemTrayPeer createSystemTray(SystemTray target) {
         return new WSystemTrayPeer(target);
     }
 
+    @Override
     public boolean isTraySupported() {
         return true;
     }
 
+    @Override
+    public DataTransferer getDataTransferer() {
+        return WDataTransferer.getInstanceImpl();
+    }
+
+    @Override
     public KeyboardFocusManagerPeer getKeyboardFocusManagerPeer()
       throws HeadlessException
     {
         return WKeyboardFocusManagerPeer.getInstance();
     }
 
-    protected native void setDynamicLayoutNative(boolean b);
+    private native void setDynamicLayoutNative(boolean b);
 
+    @Override
     public void setDynamicLayout(boolean b) {
         if (b == dynamicLayoutSetting) {
             return;
@@ -531,6 +567,7 @@
         setDynamicLayoutNative(b);
     }
 
+    @Override
     protected boolean isDynamicLayoutSet() {
         return dynamicLayoutSetting;
     }
@@ -539,8 +576,9 @@
      * Called from lazilyLoadDynamicLayoutSupportedProperty because
      * Windows doesn't always send WM_SETTINGCHANGE when it should.
      */
-    protected native boolean isDynamicLayoutSupportedNative();
+    private native boolean isDynamicLayoutSupportedNative();
 
+    @Override
     public boolean isDynamicLayoutActive() {
         return (isDynamicLayoutSet() && isDynamicLayoutSupported());
     }
@@ -548,6 +586,7 @@
     /**
      * Returns <code>true</code> if this frame state is supported.
      */
+    @Override
     public boolean isFrameStateSupported(int state) {
         switch (state) {
           case Frame.NORMAL:
@@ -572,25 +611,31 @@
         return config.getColorModel();
     }
 
+    @Override
     public ColorModel getColorModel() {
         return getStaticColorModel();
     }
 
+    @Override
     public Insets getScreenInsets(GraphicsConfiguration gc)
     {
         return getScreenInsets(((Win32GraphicsDevice) gc.getDevice()).getScreen());
     }
 
+    @Override
     public int getScreenResolution() {
         Win32GraphicsEnvironment ge = (Win32GraphicsEnvironment)
             GraphicsEnvironment.getLocalGraphicsEnvironment();
         return ge.getXResolution();
     }
+    @Override
     protected native int getScreenWidth();
+    @Override
     protected native int getScreenHeight();
-    protected native Insets getScreenInsets(int screen);
+    private native Insets getScreenInsets(int screen);
 
 
+    @Override
     public FontMetrics getFontMetrics(Font font) {
         // This is an unsupported hack, but left in for a customer.
         // Do not remove.
@@ -602,6 +647,7 @@
         return super.getFontMetrics(font);
     }
 
+    @Override
     public FontPeer getFontPeer(String name, int style) {
         FontPeer retval = null;
         String lcName = name.toLowerCase();
@@ -625,6 +671,7 @@
 
     private native void nativeSync();
 
+    @Override
     public void sync() {
         // flush the GDI/DD buffers
         nativeSync();
@@ -634,11 +681,13 @@
         D3DRenderQueue.sync();
     }
 
+    @Override
     public PrintJob getPrintJob(Frame frame, String doctitle,
                                 Properties props) {
         return getPrintJob(frame, doctitle, null, null);
     }
 
+    @Override
     public PrintJob getPrintJob(Frame frame, String doctitle,
                                 JobAttributes jobAttributes,
                                 PageAttributes pageAttributes)
@@ -657,8 +706,10 @@
         return printJob;
     }
 
+    @Override
     public native void beep();
 
+    @Override
     public boolean getLockingKeyState(int key) {
         if (! (key == KeyEvent.VK_CAPS_LOCK || key == KeyEvent.VK_NUM_LOCK ||
                key == KeyEvent.VK_SCROLL_LOCK || key == KeyEvent.VK_KANA_LOCK)) {
@@ -667,8 +718,9 @@
         return getLockingKeyStateNative(key);
     }
 
-    public native boolean getLockingKeyStateNative(int key);
+    private native boolean getLockingKeyStateNative(int key);
 
+    @Override
     public void setLockingKeyState(int key, boolean on) {
         if (! (key == KeyEvent.VK_CAPS_LOCK || key == KeyEvent.VK_NUM_LOCK ||
                key == KeyEvent.VK_SCROLL_LOCK || key == KeyEvent.VK_KANA_LOCK)) {
@@ -677,8 +729,9 @@
         setLockingKeyStateNative(key, on);
     }
 
-    public native void setLockingKeyStateNative(int key, boolean on);
+    private native void setLockingKeyStateNative(int key, boolean on);
 
+    @Override
     public Clipboard getSystemClipboard() {
         SecurityManager security = System.getSecurityManager();
         if (security != null) {
@@ -692,6 +745,7 @@
         return clipboard;
     }
 
+    @Override
     protected native void loadSystemColors(int[] systemColors);
 
     public static final Object targetToPeer(Object target) {
@@ -705,6 +759,7 @@
     /**
      * Returns a new input method adapter descriptor for native input methods.
      */
+    @Override
     public InputMethodDescriptor getInputMethodAdapterDescriptor() {
         return new WInputMethodDescriptor();
     }
@@ -712,6 +767,7 @@
     /**
      * Returns a style map for the input method highlight.
      */
+    @Override
     public Map<java.awt.font.TextAttribute,?> mapInputMethodHighlight(
         InputMethodHighlight highlight)
     {
@@ -722,6 +778,7 @@
      * Returns whether enableInputMethods should be set to true for peered
      * TextComponent instances on this platform.
      */
+    @Override
     public boolean enableInputMethodsForTextComponent() {
         return true;
     }
@@ -729,6 +786,7 @@
     /**
      * Returns the default keyboard locale of the underlying operating system
      */
+    @Override
     public Locale getDefaultKeyboardLocale() {
         Locale locale = WInputMethod.getNativeLocale();
 
@@ -742,6 +800,7 @@
     /**
      * Returns a new custom cursor.
      */
+    @Override
     public Cursor createCustomCursor(Image cursor, Point hotSpot, String name)
         throws IndexOutOfBoundsException {
         return new WCustomCursor(cursor, hotSpot, name);
@@ -750,11 +809,13 @@
     /**
      * Returns the supported cursor size (Win32 only has one).
      */
+    @Override
     public Dimension getBestCursorSize(int preferredWidth, int preferredHeight) {
         return new Dimension(WCustomCursor.getCursorWidth(),
                              WCustomCursor.getCursorHeight());
     }
 
+    @Override
     public native int getMaximumCursorColors();
 
     static void paletteChanged() {
@@ -770,6 +831,7 @@
      */
     static public void displayChanged() {
         EventQueue.invokeLater(new Runnable() {
+            @Override
             public void run() {
                 ((Win32GraphicsEnvironment)GraphicsEnvironment
                 .getLocalGraphicsEnvironment())
@@ -782,10 +844,12 @@
      * create the peer for a DragSourceContext
      */
 
+    @Override
     public DragSourceContextPeer createDragSourceContextPeer(DragGestureEvent dge) throws InvalidDnDOperationException {
         return WDragSourceContextPeer.createDragSourceContextPeer(dge);
     }
 
+    @Override
     public <T extends DragGestureRecognizer> T
         createDragGestureRecognizer(Class<T> abstractRecognizerClass,
                                     DragSource ds, Component c, int srcActions,
@@ -806,6 +870,7 @@
     private static final String awtPrefix  = "awt.";
     private static final String dndPrefix  = "DnD.";
 
+    @Override
     protected Object lazilyLoadDesktopProperty(String name) {
         if (name.startsWith(prefix)) {
             String cursorName = name.substring(prefix.length(), name.length()) + postfix;
@@ -872,6 +937,7 @@
      */
     private void windowsSettingChange() {
         EventQueue.invokeLater(new Runnable() {
+            @Override
             public void run() {
                 updateProperties();
             }
@@ -894,6 +960,7 @@
         }
     }
 
+    @Override
     public synchronized void addPropertyChangeListener(String name, PropertyChangeListener pcl) {
         if (name == null) {
             // See JavaDoc for the Toolkit.addPropertyChangeListener() method
@@ -914,6 +981,7 @@
      * initialize only static props here and do not try to initialize props which depends on wprops,
      * this should be done in lazilyLoadDesktopProperty() only.
      */
+    @Override
     protected synchronized void initializeDesktopProperties() {
         desktopProperties.put("DnD.Autoscroll.initialDelay",
                               Integer.valueOf(50));
@@ -929,6 +997,7 @@
      * This returns the value for the desktop property "awt.font.desktophints"
      * This requires that the Windows properties have already been gathered.
      */
+    @Override
     protected synchronized RenderingHints getDesktopAAHints() {
         if (wprops == null) {
             return null;
@@ -937,6 +1006,7 @@
         }
     }
 
+    @Override
     public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) {
         return (modalityType == null) ||
                (modalityType == Dialog.ModalityType.MODELESS) ||
@@ -945,6 +1015,7 @@
                (modalityType == Dialog.ModalityType.TOOLKIT_MODAL);
     }
 
+    @Override
     public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType exclusionType) {
         return (exclusionType == null) ||
                (exclusionType == Dialog.ModalExclusionType.NO_EXCLUDE) ||
@@ -984,6 +1055,7 @@
         return !Win32GraphicsEnvironment.isDWMCompositionEnabled();
     }
 
+    @Override
     @SuppressWarnings("deprecation")
     public void grab(Window w) {
         if (w.getPeer() != null) {
@@ -991,6 +1063,7 @@
         }
     }
 
+    @Override
     @SuppressWarnings("deprecation")
     public void ungrab(Window w) {
         if (w.getPeer() != null) {
@@ -998,17 +1071,21 @@
         }
     }
 
+    @Override
     public native boolean syncNativeQueue(final long timeout);
+    @Override
     public boolean isDesktopSupported() {
         return true;
     }
 
+    @Override
     public DesktopPeer createDesktopPeer(Desktop target) {
         return new WDesktopPeer();
     }
 
-    public static native void setExtraMouseButtonsEnabledNative(boolean enable);
+    private static native void setExtraMouseButtonsEnabledNative(boolean enable);
 
+    @Override
     public boolean areExtraMouseButtonsEnabled() throws HeadlessException {
         return areExtraMouseButtonsEnabled;
     }
--- a/jdk/src/windows/classes/sun/awt/windows/WTrayIconPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WTrayIconPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,8 @@
 import java.awt.image.*;
 import sun.awt.SunToolkit;
 import sun.awt.image.IntegerComponentRaster;
-import sun.awt.windows.WPopupMenuPeer;
 
-public class WTrayIconPeer extends WObjectPeer implements TrayIconPeer {
+final class WTrayIconPeer extends WObjectPeer implements TrayIconPeer {
     final static int TRAY_ICON_WIDTH = 16;
     final static int TRAY_ICON_HEIGHT = 16;
     final static int TRAY_ICON_MASK_SIZE = (TRAY_ICON_WIDTH * TRAY_ICON_HEIGHT) / 8;
@@ -48,6 +47,7 @@
     Frame popupParent = new Frame("PopupMessageWindow");
     PopupMenu popup;
 
+    @Override
     protected void disposeImpl() {
         if (popupParent != null) {
             popupParent.dispose();
@@ -64,6 +64,7 @@
         updateImage();
     }
 
+    @Override
     public void updateImage() {
         Image image = ((TrayIcon)target).getImage();
         if (image != null) {
@@ -71,13 +72,16 @@
         }
     }
 
+    @Override
     public native void setToolTip(String tooltip);
 
+    @Override
     public synchronized void showPopupMenu(final int x, final int y) {
         if (isDisposed())
             return;
 
         SunToolkit.executeOnEventHandlerThread(target, new Runnable() {
+                @Override
                 public void run() {
                     PopupMenu newPopup = ((TrayIcon)target).getPopupMenu();
                     if (popup != newPopup) {
@@ -96,6 +100,7 @@
             });
     }
 
+    @Override
     public void displayMessage(String caption, String text, String messageType) {
         // The situation when both caption and text are null is processed in the shared code.
         if (caption == null) {
@@ -185,6 +190,7 @@
     native void _displayMessage(String caption, String text, String messageType);
 
     class IconObserver implements ImageObserver {
+        @Override
         public boolean imageUpdate(Image image, int flags, int x, int y, int width, int height) {
             if (image != ((TrayIcon)target).getImage() || // if the image has been changed
                 isDisposed())
--- a/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
     }
 
     // WComponentPeer overrides
+    @Override
     @SuppressWarnings("unchecked")
     protected void disposeImpl() {
         AppContext appContext = SunToolkit.targetToAppContext(target);
@@ -118,24 +119,30 @@
 
     // WindowPeer implementation
 
+    @Override
     public void toFront() {
         updateFocusableWindowState();
         _toFront();
     }
-    native void _toFront();
+    private native void _toFront();
+
+    @Override
     public native void toBack();
 
-    public native void setAlwaysOnTopNative(boolean value);
+    private native void setAlwaysOnTopNative(boolean value);
+
     public void setAlwaysOnTop(boolean value) {
         if ((value && ((Window)target).isVisible()) || !value) {
             setAlwaysOnTopNative(value);
         }
     }
 
+    @Override
     public void updateAlwaysOnTopState() {
         setAlwaysOnTop(((Window)target).isAlwaysOnTop());
     }
 
+    @Override
     public void updateFocusableWindowState() {
         setFocusableWindow(((Window)target).isFocusableWindow());
     }
@@ -150,12 +157,13 @@
         }
         _setTitle(title);
     }
-    native void _setTitle(String title);
+    private native void _setTitle(String title);
 
     public void setResizable(boolean resizable) {
         _setResizable(resizable);
     }
-    public native void _setResizable(boolean resizable);
+
+    private native void _setResizable(boolean resizable);
 
     // Toolkit & peer internals
 
@@ -163,6 +171,7 @@
         super(target);
     }
 
+    @Override
     void initialize() {
         super.initialize();
 
@@ -210,6 +219,7 @@
         windowType = ((Window)target).getType();
     }
 
+    @Override
     void create(WComponentPeer parent) {
         preCreate(parent);
         createAwtWindow(parent);
@@ -226,6 +236,7 @@
         super.show();
     }
 
+    @Override
     public void show() {
         updateFocusableWindowState();
 
@@ -289,7 +300,7 @@
         }
         return requestWindowFocus(cause == CausedFocusEvent.Cause.MOUSE_EVENT);
     }
-    public native boolean requestWindowFocus(boolean isMouseEventCause);
+    private native boolean requestWindowFocus(boolean isMouseEventCause);
 
     public boolean focusAllowedFor() {
         Window window = (Window)this.target;
@@ -305,7 +316,8 @@
         return true;
     }
 
-    public void hide() {
+    @Override
+    void hide() {
         WindowListener listener = windowListener;
         if (listener != null) {
             // We're not getting WINDOW_CLOSING from the native code when hiding
@@ -316,6 +328,7 @@
     }
 
     // WARNING: it's called on the Toolkit thread!
+    @Override
     void preprocessPostEvent(AWTEvent event) {
         if (event instanceof WindowEvent) {
             WindowListener listener = windowListener;
@@ -340,6 +353,7 @@
         windowListener = AWTEventMulticaster.remove(windowListener, l);
     }
 
+    @Override
     public void updateMinimumSize() {
         Dimension minimumSize = null;
         if (((Component)target).isMinimumSizeSet()) {
@@ -356,6 +370,7 @@
         }
     }
 
+    @Override
     public void updateIconImages() {
         java.util.List<Image> imageList = ((Window)target).getIconImages();
         if (imageList == null || imageList.size() == 0) {
@@ -393,6 +408,7 @@
         return modalBlocker != null;
     }
 
+     @Override
      @SuppressWarnings("deprecation")
     public void setModalBlocked(Dialog dialog, boolean blocked) {
         synchronized (((Component)getTarget()).getTreeLock()) // State lock should always be after awtLock
@@ -459,6 +475,7 @@
     void draggedToNewScreen() {
         SunToolkit.executeOnEventHandlerThread((Component)target,new Runnable()
         {
+            @Override
             public void run() {
                 displayChanged();
             }
@@ -519,6 +536,7 @@
      * reflects the current display depth information, which has
      * just changed).
      */
+    @Override
     public void displayChanged() {
         updateGC();
     }
@@ -527,6 +545,7 @@
      * Part of the DisplayChangedListener interface: components
      * do not need to react to this event
      */
+    @Override
     public void paletteChanged() {
     }
 
@@ -565,6 +584,7 @@
      private volatile int sysW = 0;
      private volatile int sysH = 0;
 
+     @Override
      public native void repositionSecurityWarning();
 
      @Override
@@ -620,6 +640,7 @@
     private native void setOpacity(int iOpacity);
     private float opacity = 1.0f;
 
+    @Override
     public void setOpacity(float opacity) {
         if (!((SunToolkit)((Window)target).getToolkit()).
             isWindowOpacitySupported())
@@ -663,6 +684,7 @@
 
     private native void setOpaqueImpl(boolean isOpaque);
 
+    @Override
     public void setOpaque(boolean isOpaque) {
         synchronized (getStateLock()) {
             if (this.isOpaque == isOpaque) {
@@ -720,8 +742,9 @@
         }
     }
 
-    public native void updateWindowImpl(int[] data, int width, int height);
+    native void updateWindowImpl(int[] data, int width, int height);
 
+    @Override
     public void updateWindow() {
         updateWindow(false);
     }
@@ -770,6 +793,7 @@
      * unregisters ActiveWindowListener listener.
      */
     private static class GuiDisposedListener implements PropertyChangeListener {
+        @Override
         public void propertyChange(PropertyChangeEvent e) {
             boolean isDisposed = (Boolean)e.getNewValue();
             if (isDisposed != true) {
@@ -795,6 +819,7 @@
      */
     @SuppressWarnings( value = {"deprecation", "unchecked"})
     private static class ActiveWindowListener implements PropertyChangeListener {
+        @Override
         public void propertyChange(PropertyChangeEvent e) {
             Window w = (Window)e.getNewValue();
             if (w == null) {
--- a/jdk/src/windows/classes/sun/awt/windows/WingDings.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WingDings.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,11 +29,12 @@
 import java.nio.CharBuffer;
 import java.nio.charset.*;
 
-public class WingDings extends Charset {
+final class WingDings extends Charset {
     public WingDings () {
         super("WingDings", null);
     }
 
+    @Override
     public CharsetEncoder newEncoder() {
         return new Encoder(this);
     }
@@ -41,10 +42,12 @@
     /* Seems like supporting a decoder is required, but we aren't going
      * to be publically exposing this class, so no need to waste work
      */
+    @Override
     public CharsetDecoder newDecoder() {
         throw new Error("Decoder isn't implemented for WingDings Charset");
     }
 
+    @Override
     public boolean contains(Charset cs) {
         return cs instanceof WingDings;
     }
@@ -54,6 +57,7 @@
             super(cs, 1.0f, 1.0f);
         }
 
+        @Override
         public boolean canEncode(char c) {
             if(c >= 0x2701 && c <= 0x27be){
                 if (table[c - 0x2700] != 0x00)
@@ -64,6 +68,7 @@
             return false;
         }
 
+        @Override
         protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) {
             char[] sa = src.array();
             int sp = src.arrayOffset() + src.position();
@@ -156,6 +161,7 @@
         };
 
         /* The default implementation creates a decoder and we don't have one */
+        @Override
         public boolean isLegalReplacement(byte[] repl) {
             return true;
         }
--- a/jdk/src/windows/native/sun/net/spi/DefaultProxySelector.c	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/native/sun/net/spi/DefaultProxySelector.c	Wed Jul 05 19:33:51 2017 +0200
@@ -127,12 +127,13 @@
   char regserver[MAX_STR_LEN];
   char override[MAX_STR_LEN];
   char *s, *s2;
+  char *ctx = NULL;
   int pport = 0;
   int defport = 0;
   char *phost;
 
   /**
-   * Let's opem the Registry entry. We'll check a few values in it:
+   * Let's open the Registry entry. We'll check a few values in it:
    *
    * - ProxyEnable: 0 means no proxy, 1 means use the proxy
    * - ProxyServer: a string that can take 2 forms:
@@ -177,7 +178,7 @@
            * The semicolons (;) separated entries have to be matched with the
            * the beginning of the hostname.
            */
-          s = strtok(override, "; ");
+          s = strtok_s(override, "; ", &ctx);
           urlhost = (*env)->GetStringUTFChars(env, host, &isCopy);
           if (urlhost == NULL) {
             if (!(*env)->ExceptionCheck(env))
@@ -194,7 +195,7 @@
                 (*env)->ReleaseStringUTFChars(env, host, urlhost);
               goto noproxy;
             }
-            s = strtok(NULL, "; ");
+            s = strtok_s(NULL, "; ", &ctx);
           }
           if (isCopy == JNI_TRUE)
             (*env)->ReleaseStringUTFChars(env, host, urlhost);
--- a/jdk/src/windows/native/sun/windows/MouseInfo.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/native/sun/windows/MouseInfo.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -95,7 +95,9 @@
         env->DeleteLocalRef(pointClassLocal);
     }
     xID = env->GetFieldID(pointClass, "x", "I");
+    CHECK_NULL_RETURN(xID, (jint)0);
     yID = env->GetFieldID(pointClass, "y", "I");
+    CHECK_NULL_RETURN(yID, (jint)0);
     env->SetIntField(point, xID, pt.x);
     env->SetIntField(point, yID, pt.y);
 
--- a/jdk/src/windows/native/sun/windows/awt_DataTransferer.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_DataTransferer.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -274,6 +274,9 @@
 
         jclass str_clazz = env->FindClass("java/lang/String");
         DASSERT(str_clazz != NULL);
+        if (str_clazz == NULL) {
+           throw std::bad_alloc();
+        }
         jobjectArray filenames = env->NewObjectArray(nFilenames, str_clazz,
                                                      NULL);
         if (filenames == NULL) {
@@ -827,6 +830,7 @@
     TRY;
 
     LPCTSTR cStr = JNU_GetStringPlatformChars(env, str, NULL);
+    CHECK_NULL_RETURN(cStr, 0);
     jlong value = ::RegisterClipboardFormat(cStr);
     JNU_ReleaseStringPlatformChars(env, str, cStr);
 
--- a/jdk/src/windows/native/sun/windows/awt_Insets.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_Insets.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -46,14 +46,20 @@
     TRY;
 
     AwtInsets::leftID = env->GetFieldID(cls, "left", "I");
+    DASSERT(AwtInsets::leftID != NULL);
+    CHECK_NULL(AwtInsets::leftID);
+
     AwtInsets::rightID = env->GetFieldID(cls, "right", "I");
-    AwtInsets::topID = env->GetFieldID(cls, "top", "I");
-    AwtInsets::bottomID = env->GetFieldID(cls, "bottom", "I");
+    DASSERT(AwtInsets::rightID != NULL);
+    CHECK_NULL(AwtInsets::rightID);
 
-    DASSERT(AwtInsets::leftID != NULL);
-    DASSERT(AwtInsets::rightID != NULL);
+    AwtInsets::topID = env->GetFieldID(cls, "top", "I");
     DASSERT(AwtInsets::topID != NULL);
+    CHECK_NULL(AwtInsets::topID);
+
+    AwtInsets::bottomID = env->GetFieldID(cls, "bottom", "I");
     DASSERT(AwtInsets::bottomID != NULL);
+    CHECK_NULL(AwtInsets::bottomID);
 
     CATCH_BAD_ALLOC;
 }
--- a/jdk/src/windows/native/sun/windows/awt_Label.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_Label.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -319,10 +319,12 @@
 
     /* init field ids */
     AwtLabel::textID = env->GetFieldID(cls, "text", "Ljava/lang/String;");
-    AwtLabel::alignmentID = env->GetFieldID(cls, "alignment", "I");
+    DASSERT(AwtLabel::textID != NULL);
+    CHECK_NULL(AwtLabel::textID);
 
-    DASSERT(AwtLabel::textID != NULL);
+    AwtLabel::alignmentID = env->GetFieldID(cls, "alignment", "I");
     DASSERT(AwtLabel::alignmentID != NULL);
+    CHECK_NULL(AwtLabel::alignmentID);
 
     CATCH_BAD_ALLOC;
 }
--- a/jdk/src/windows/native/sun/windows/awt_PrintDialog.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_PrintDialog.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,17 +166,6 @@
 }
 
 JNIEXPORT void JNICALL
-Java_sun_awt_windows_WPrintDialog_setPeer(JNIEnv *env, jobject target,
-                                          jobject peer)
-{
-    TRY;
-
-    env->SetObjectField(target, AwtComponent::peerID, peer);
-
-    CATCH_BAD_ALLOC;
-}
-
-JNIEXPORT void JNICALL
 Java_sun_awt_windows_WPrintDialogPeer_initIDs(JNIEnv *env, jclass cls)
 {
     TRY;
--- a/jdk/src/windows/native/sun/windows/awt_Rectangle.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_Rectangle.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -46,14 +46,20 @@
     TRY;
 
     AwtRectangle::xID = env->GetFieldID(cls, "x", "I");
+    DASSERT(AwtRectangle::xID != NULL);
+    CHECK_NULL(AwtRectangle::xID);
+
     AwtRectangle::yID = env->GetFieldID(cls, "y", "I");
-    AwtRectangle::widthID = env->GetFieldID(cls, "width", "I");
-    AwtRectangle::heightID = env->GetFieldID(cls, "height", "I");
+    DASSERT(AwtRectangle::yID != NULL);
+    CHECK_NULL(AwtRectangle::yID);
 
-    DASSERT(AwtRectangle::xID != NULL);
-    DASSERT(AwtRectangle::yID != NULL);
+    AwtRectangle::widthID = env->GetFieldID(cls, "width", "I");
     DASSERT(AwtRectangle::widthID != NULL);
+    CHECK_NULL(AwtRectangle::widthID);
+
+    AwtRectangle::heightID = env->GetFieldID(cls, "height", "I");
     DASSERT(AwtRectangle::heightID != NULL);
+    CHECK_NULL(AwtRectangle::heightID);
 
     CATCH_BAD_ALLOC;
 }
--- a/jdk/src/windows/native/sun/windows/awt_TrayIcon.cpp	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_TrayIcon.cpp	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -503,6 +503,7 @@
             env->GetMethodID(mouseEventCls, "<init>",
                              "(Ljava/awt/Component;IJIIIIIIZI)V");
         DASSERT(mouseEventConst);
+        CHECK_NULL(mouseEventConst);
     }
     if (env->EnsureLocalCapacity(2) < 0) {
         return;
@@ -556,6 +557,7 @@
             env->GetMethodID(actionEventCls, "<init>",
                              "(Ljava/lang/Object;ILjava/lang/String;JI)V");
         DASSERT(actionEventConst);
+        CHECK_NULL(actionEventConst);
     }
     if (env->EnsureLocalCapacity(2) < 0) {
         return;
@@ -736,6 +738,7 @@
     }
 
     tooltipStr = JNU_GetStringPlatformChars(env, jtooltip, (jboolean *)NULL);
+    if (env->ExceptionCheck()) goto ret;
     trayIcon->SetToolTip(tooltipStr);
     JNU_ReleaseStringPlatformChars(env, jtooltip, tooltipStr);
 ret:
@@ -855,9 +858,18 @@
     trayIcon = (AwtTrayIcon *)pData;
 
     captionStr = JNU_GetStringPlatformChars(env, jcaption, (jboolean *)NULL);
+    if (env->ExceptionCheck()) goto ret;
     textStr = JNU_GetStringPlatformChars(env, jtext, (jboolean *)NULL);
+    if (env->ExceptionCheck()) {
+        JNU_ReleaseStringPlatformChars(env, jcaption, captionStr);
+        goto ret;
+    }
     msgTypeStr = JNU_GetStringPlatformChars(env, jmsgType, (jboolean *)NULL);
-
+    if (env->ExceptionCheck()) {
+        JNU_ReleaseStringPlatformChars(env, jcaption, captionStr);
+        JNU_ReleaseStringPlatformChars(env, jtext, textStr);
+        goto ret;
+    }
     trayIcon->DisplayMessage(captionStr, textStr, msgTypeStr);
 
     JNU_ReleaseStringPlatformChars(env, jcaption, captionStr);
@@ -889,10 +901,12 @@
 
     /* init field ids */
     AwtTrayIcon::idID = env->GetFieldID(cls, "id", "I");
-    AwtTrayIcon::actionCommandID = env->GetFieldID(cls, "actionCommand", "Ljava/lang/String;");
+    DASSERT(AwtTrayIcon::idID != NULL);
+    CHECK_NULL(AwtTrayIcon::idID);
 
-    DASSERT(AwtTrayIcon::idID != NULL);
+    AwtTrayIcon::actionCommandID = env->GetFieldID(cls, "actionCommand", "Ljava/lang/String;");
     DASSERT(AwtTrayIcon::actionCommandID != NULL);
+    CHECK_NULL( AwtTrayIcon::actionCommandID);
 
     CATCH_BAD_ALLOC;
 }
@@ -981,8 +995,11 @@
     jint *intRasterDataPtr = NULL;
     HBITMAP hColor = NULL;
     try {
-        intRasterDataPtr =
-            (jint *)env->GetPrimitiveArrayCritical(intRasterData, 0);
+        intRasterDataPtr = (jint *)env->GetPrimitiveArrayCritical(intRasterData, 0);
+        if (intRasterDataPtr == NULL) {
+            ::DeleteObject(hMask);
+            return;
+        }
         hColor = AwtTrayIcon::CreateBMP(NULL, (int *)intRasterDataPtr, nSS, nW, nH);
     } catch (...) {
         if (intRasterDataPtr != NULL) {
--- a/jdk/test/ProblemList.txt	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/ProblemList.txt	Wed Jul 05 19:33:51 2017 +0200
@@ -221,15 +221,6 @@
 java/security/KeyPairGenerator/SolarisShortDSA.java             solaris-all
 sun/security/tools/keytool/standard.sh                          solaris-all
 
-# 8000439: NPG: REGRESSION : sun/security/krb5/auto/MaxRetries.java fails with timeout
-sun/security/krb5/auto/MaxRetries.java                          solaris-sparcv9
-
-# 8006690: sun/security/krb5/auto/BadKdc1.java fails intermittently
-sun/security/krb5/auto/BadKdc1.java                             solaris-sparcv9
-sun/security/krb5/auto/BadKdc2.java                             solaris-sparcv9
-sun/security/krb5/auto/BadKdc3.java                             solaris-sparcv9
-sun/security/krb5/auto/BadKdc4.java                             solaris-sparcv9
-
 ############################################################################
 
 # jdk_sound
--- a/jdk/test/com/sun/awt/SecurityWarning/CustomSecurityManager.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/com/sun/awt/SecurityWarning/CustomSecurityManager.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,10 +1,35 @@
-import sun.security.util.SecurityConstants;
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 sun.awt.AWTPermissions;
 import java.security.Permission;
 
 public class CustomSecurityManager extends SecurityManager {
     @Override
     public void checkPermission(Permission perm) {
-        if (perm.implies(SecurityConstants.AWT.TOPLEVEL_WINDOW_PERMISSION)) {
+        if (perm.implies(AWTPermissions.TOPLEVEL_WINDOW_PERMISSION)) {
             throw new SecurityException();
         }
     }
--- a/jdk/test/com/sun/crypto/provider/Cipher/DES/PerformanceTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/com/sun/crypto/provider/Cipher/DES/PerformanceTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,12 +24,9 @@
 /*
  * @test
  * @bug 0000000
- * @ignore run main/timeout=900 PerformanceTest
- * @summary PerformanceTest
+ * @summary This test checks performance of various ciphers.
  * @author Jan Luehe
- *
- * ignore since this test exists for performance
- * purpose and can be run separately if needed.
+ * @run main/manual PerformanceTest
  */
 import java.security.*;
 import java.security.spec.*;
--- a/jdk/test/com/sun/security/auth/callback/TextCallbackHandler/Default.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/com/sun/security/auth/callback/TextCallbackHandler/Default.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 @@
  * @test
  * @bug 4470717
  * @summary fix default handling and other misc
- *
- * @ignore run these by hand
+ * @run main/manual Default
  */
 
 import com.sun.security.auth.callback.TextCallbackHandler;
--- a/jdk/test/com/sun/security/auth/callback/TextCallbackHandler/Password.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/com/sun/security/auth/callback/TextCallbackHandler/Password.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
  * @test
  * @bug 6825240
  * @summary Password.readPassword() echos the input when System.Console is null
- * @ignore run these by hand
+ * @run main/manual Password
  */
 
 import com.sun.security.auth.callback.TextCallbackHandler;
--- a/jdk/test/com/sun/security/sasl/gsskerb/AuthOnly.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/com/sun/security/sasl/gsskerb/AuthOnly.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,14 @@
  * @test
  * @bug 4634892
  * @summary Ensure authentication via GSS-API/Kerberos v5 works.
- * @ignore see runwjaas.csh for instructions for how to run this test
+ * @run main/manual AuthOnly
  */
+
 /*
- * Can set logging to FINEST to view exchange.
+ * Set logging to FINEST to view exchange.
+ * See runwjaas.csh for instructions for how to run this test.
  */
+
 import javax.security.sasl.*;
 import javax.security.auth.callback.*;
 import java.security.*;
--- a/jdk/test/com/sun/security/sasl/gsskerb/ConfSecurityLayer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/com/sun/security/sasl/gsskerb/ConfSecurityLayer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,15 @@
  * @test
  * @bug 5014493
  * @summary SaslServer.wrap throws NullPointerException when security
- *    layer negotiated
- * @ignore see run-conf-wjaas.csh for instructions for how to run this test
+ *    layer negotiated.
+ * @run main/manual ConfSecurityLayer
  */
+
 /*
- * Can set logging to FINEST to view exchange.
+ * Set logging to FINEST to view exchange.
+ * See run-conf-wjaas.csh for instructions for how to run this test.
  */
+
 import javax.security.sasl.*;
 import javax.security.auth.callback.*;
 import java.security.*;
--- a/jdk/test/com/sun/security/sasl/gsskerb/NoSecurityLayer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/com/sun/security/sasl/gsskerb/NoSecurityLayer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,13 +24,16 @@
 /*
  * @test
  * @bug 4873552
- * @summary GSS-API/krb5 SASL mechanism should throw IllegalStateException for auth-only
-
- * @ignore see run-nosec-wjaas.csh for instructions for how to run this test
+ * @summary GSS-API/krb5 SASL mechanism should throw IllegalStateException
+ *     for auth-only
+ * @run main/manual NoSecurityLayer
  */
+
 /*
- * Can set logging to FINEST to view exchange.
+ * Set logging to FINEST to view exchange.
+ * See run-nosec-wjaas.csh for instructions for how to run this test.
  */
+
 import javax.security.sasl.*;
 import javax.security.auth.callback.*;
 import java.security.*;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Choice/ChoiceLocationTest/ChoiceLocationTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,96 @@
+/*
+ * 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 7159566
+  @summary The choice positioned in the top of applet when clicking the choice.
+  @author Petr Pchelko
+  @library ../../regtesthelpers
+  @build Util
+  @run main ChoiceLocationTest
+ */
+
+import java.awt.*;
+import javax.swing.*;
+import java.awt.event.InputEvent;
+import java.util.stream.Stream;
+
+import test.java.awt.regtesthelpers.Util;
+
+public class ChoiceLocationTest {
+
+    private static final int FRAME_LOCATION = 100;
+    private static final int FRAME_SIZE = 400;
+    private static final int CLICK_STEP = 5;
+
+    private static String[] choiceItems = new String[] {
+            "test item 1",
+            "test item 2",
+            "test item 3"
+    };
+
+    private static volatile Frame frame;
+    private static volatile Choice choice;
+
+    public static void main(String[] args) throws Exception {
+        try {
+            SwingUtilities.invokeAndWait(ChoiceLocationTest::initAndShowUI);
+            Robot r = new Robot();
+            r.waitForIdle();
+            r.delay(100);
+
+            Util.clickOnComp(choice, r);
+
+            choice.addItemListener(event -> {throw new RuntimeException("Failed: the choice popup is in the wrong place");});
+
+            // Test: click in several places on the top of the frame an ensure there' no choice there
+            Point locOnScreen = frame.getLocationOnScreen();
+            int x = locOnScreen.x + FRAME_SIZE / 2;
+            for (int y = locOnScreen.y + frame.getInsets().top + 10; y < locOnScreen.y + FRAME_SIZE / 3 ; y += CLICK_STEP) {
+                r.mouseMove(x, y);
+                r.waitForIdle();
+                r.mousePress(InputEvent.BUTTON1_MASK);
+                r.mouseRelease(InputEvent.BUTTON1_MASK);
+                r.waitForIdle();
+                r.delay(100);
+            }
+        } finally {
+            if (frame != null) {
+                frame.dispose();
+            }
+        }
+
+    }
+
+    private static void initAndShowUI() {
+        frame = new Frame("Test frame");
+        choice = new Choice();
+        Stream.of(choiceItems).forEach(choice::add);
+        frame.add(choice);
+        frame.setBounds(FRAME_LOCATION, FRAME_LOCATION, FRAME_SIZE, FRAME_SIZE);
+        frame.setVisible(true);
+    }
+
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Cursor/MultiResolutionCursorTest/MultiResolutionCursorTest.html	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,32 @@
+<!--
+ 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.
+-->
+
+<html>
+    <head>
+        <title>High resolution custom cursor test, bug ID 8028212</title>
+    </head>
+    <body>
+    <applet CODE="MultiResolutionCursorTest.class" WIDTH=300 HEIGHT=100></applet>
+    <p> See the dialog box (usually in upper left corner) for instructions</p>
+</body>
+</html>
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Cursor/MultiResolutionCursorTest/MultiResolutionCursorTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,266 @@
+/*
+ * 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.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Cursor;
+import java.awt.Dialog;
+import java.awt.Frame;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.Image;
+import java.awt.Label;
+import java.awt.Point;
+import java.awt.TextArea;
+import java.awt.Toolkit;
+import java.awt.image.BufferedImage;
+import java.util.LinkedList;
+import java.util.List;
+import javax.swing.JApplet;
+import sun.awt.OSInfo;
+import sun.awt.image.MultiResolutionImage;
+
+/**
+ * @test
+ * @bug 8028212
+ * @summary [macosx] Custom Cursor HiDPI support
+ * @author Alexander Scherbatiy
+ * @run applet/manual=yesno MultiResolutionCursorTest.html
+ */
+public class MultiResolutionCursorTest extends JApplet {
+    //Declare things used in the test, like buttons and labels here
+
+    static final int sizes[] = {16, 32, 128};
+    static final Color colors[] = {Color.WHITE, Color.RED, Color.GREEN, Color.BLUE};
+
+    public void init() {
+        //Create instructions for the user here, as well as set up
+        // the environment -- set the layout manager, add buttons,
+        // etc.
+        this.setLayout(new BorderLayout());
+
+        if (OSInfo.getOSType().equals(OSInfo.OSType.MACOSX)) {
+            String[] instructions = {
+                "Verify that high resolution custom cursor is used"
+                + " on HiDPI displays.",
+                "1) Run the test on Retina display or enable the Quartz Debug"
+                + " and select the screen resolution with (HiDPI) label",
+                "2) Move the cursor to the Test Frame",
+                "3) Check that cursor has red, green or blue color",
+                "If so, press PASS, else press FAIL."
+            };
+            Sysout.createDialogWithInstructions(instructions);
+
+        } else {
+            String[] instructions = {
+                "This test is not applicable to the current platform. Press PASS."
+            };
+            Sysout.createDialogWithInstructions(instructions);
+        }
+    }//End  init()
+
+    public void start() {
+        //Get things going.  Request focus, set size, et cetera
+        setSize(200, 200);
+        setVisible(true);
+        validate();
+
+        final Image image = new MultiResolutionCursor();
+
+        int center = sizes[0] / 2;
+        Cursor cursor = Toolkit.getDefaultToolkit().createCustomCursor(
+                image, new Point(center, center), "multi-resolution cursor");
+
+        Frame frame = new Frame("Test Frame");
+        frame.setSize(300, 300);
+        frame.setLocation(300, 50);
+        frame.add(new Label("Move cursor here"));
+        frame.setCursor(cursor);
+        frame.setVisible(true);
+    }// start()
+
+
+    static class MultiResolutionCursor extends BufferedImage implements MultiResolutionImage {
+
+        List<Image> highResolutionImages;
+
+        public MultiResolutionCursor() {
+            super(sizes[0], sizes[0], BufferedImage.TYPE_INT_RGB);
+
+            draw(getGraphics(), 0);
+            highResolutionImages = new LinkedList<>();
+            highResolutionImages.add(this);
+
+            for (int i = 1; i < sizes.length; i++) {
+                BufferedImage highResolutionImage =
+                        new BufferedImage(sizes[i], sizes[i], BufferedImage.TYPE_INT_RGB);
+                draw(highResolutionImage.getGraphics(), i);
+                highResolutionImages.add(highResolutionImage);
+            }
+        }
+
+        @Override
+        public Image getResolutionVariant(int width, int height) {
+
+            for (int i = 0; i < sizes.length; i++) {
+                Image image = highResolutionImages.get(i);
+                int w = image.getWidth(null);
+                int h = image.getHeight(null);
+
+                if (width <= w && height <= h) {
+                    return image;
+                }
+            }
+
+            return highResolutionImages.get(highResolutionImages.size() - 1);
+        }
+
+        void draw(Graphics graphics, int index) {
+            Graphics2D g2 = (Graphics2D) graphics;
+            Color color = colors[index];
+            g2.setColor(color);
+            g2.fillRect(0, 0, sizes[index], sizes[index]);
+        }
+
+        @Override
+        public List<Image> getResolutionVariants() {
+            return highResolutionImages;
+        }
+    }
+}// class BlockedWindowTest
+
+/* Place other classes related to the test after this line */
+/**
+ * **************************************************
+ * Standard Test Machinery DO NOT modify anything below -- it's a standard chunk
+ * of code whose purpose is to make user interaction uniform, and thereby make
+ * it simpler to read and understand someone else's test.
+ * **************************************************
+ */
+/**
+ * This is part of the standard test machinery. It creates a dialog (with the
+ * instructions), and is the interface for sending text messages to the user. To
+ * print the instructions, send an array of strings to Sysout.createDialog
+ * WithInstructions method. Put one line of instructions per array entry. To
+ * display a message for the tester to see, simply call Sysout.println with the
+ * string to be displayed. This mimics System.out.println but works within the
+ * test harness as well as standalone.
+ */
+class Sysout {
+
+    private static TestDialog dialog;
+
+    public static void createDialogWithInstructions(String[] instructions) {
+        dialog = new TestDialog(new Frame(), "Instructions");
+        dialog.printInstructions(instructions);
+        dialog.setVisible(true);
+        println("Any messages for the tester will display here.");
+    }
+
+    public static void createDialog() {
+        dialog = new TestDialog(new Frame(), "Instructions");
+        String[] defInstr = {"Instructions will appear here. ", ""};
+        dialog.printInstructions(defInstr);
+        dialog.setVisible(true);
+        println("Any messages for the tester will display here.");
+    }
+
+    public static void printInstructions(String[] instructions) {
+        dialog.printInstructions(instructions);
+    }
+
+    public static void println(String messageIn) {
+        dialog.displayMessage(messageIn);
+    }
+}// Sysout  class
+
+/**
+ * This is part of the standard test machinery. It provides a place for the test
+ * instructions to be displayed, and a place for interactive messages to the
+ * user to be displayed. To have the test instructions displayed, see Sysout. To
+ * have a message to the user be displayed, see Sysout. Do not call anything in
+ * this dialog directly.
+ */
+class TestDialog extends Dialog {
+
+    TextArea instructionsText;
+    TextArea messageText;
+    int maxStringLength = 80;
+
+    //DO NOT call this directly, go through Sysout
+    public TestDialog(Frame frame, String name) {
+        super(frame, name);
+        int scrollBoth = TextArea.SCROLLBARS_BOTH;
+        instructionsText = new TextArea("", 15, maxStringLength, scrollBoth);
+        add("North", instructionsText);
+
+        messageText = new TextArea("", 5, maxStringLength, scrollBoth);
+        add("Center", messageText);
+
+        pack();
+
+        setVisible(true);
+    }// TestDialog()
+
+    //DO NOT call this directly, go through Sysout
+    public void printInstructions(String[] instructions) {
+        //Clear out any current instructions
+        instructionsText.setText("");
+
+        //Go down array of instruction strings
+
+        String printStr, remainingStr;
+        for (int i = 0; i < instructions.length; i++) {
+            //chop up each into pieces maxSringLength long
+            remainingStr = instructions[ i];
+            while (remainingStr.length() > 0) {
+                //if longer than max then chop off first max chars to print
+                if (remainingStr.length() >= maxStringLength) {
+                    //Try to chop on a word boundary
+                    int posOfSpace = remainingStr.lastIndexOf(' ', maxStringLength - 1);
+
+                    if (posOfSpace <= 0) {
+                        posOfSpace = maxStringLength - 1;
+                    }
+
+                    printStr = remainingStr.substring(0, posOfSpace + 1);
+                    remainingStr = remainingStr.substring(posOfSpace + 1);
+                } //else just print
+                else {
+                    printStr = remainingStr;
+                    remainingStr = "";
+                }
+
+                instructionsText.append(printStr + "\n");
+
+            }// while
+
+        }// for
+
+    }//printInstructions()
+
+    //DO NOT call this directly, go through Sysout
+    public void displayMessage(String messageIn) {
+        messageText.append(messageIn + "\n");
+        System.out.println(messageIn);
+    }
+}// Te
\ No newline at end of file
--- a/jdk/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/InterprocessMessages.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/InterprocessMessages.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,5 +24,6 @@
 interface InterprocessMessages {
     final static int EXECUTION_IS_SUCCESSFULL = 0;
     final static int DATA_IS_CORRUPTED = 212;
+    final static int NO_DROP_HAPPENED = 112;
 }
 
--- a/jdk/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.html	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.html	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 <!--
- Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
  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 @@
 <html>
 <!--  
   @test
-  @bug 8005932
+  @bug 8005932 8017456
   @summary Java 7 on mac os x only provides text clipboard formats
   @author mikhail.cherkasov@oracle.com
   @library ../../regtesthelpers
--- a/jdk/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,17 +21,6 @@
  * questions.
  */
 
-/*
-  @bug 8005932
-  @summary Java 7 on mac os x only provides text clipboard formats
-  @author mikhail.cherkasov@oracle.com
-  @library ../../regtesthelpers
-  @library ../../regtesthelpers/process
-  @build Util
-  @build ProcessResults ProcessCommunicator
-  @run applet/othervm MissedHtmlAndRtfBug.html
-*/
-
 import java.awt.*;
 import java.awt.datatransfer.DataFlavor;
 import java.awt.event.*;
@@ -47,6 +36,7 @@
 import static java.lang.Thread.sleep;
 
 public class MissedHtmlAndRtfBug extends Applet {
+
     public void init() {
         setLayout(new BorderLayout());
     }//End  init()
@@ -82,9 +72,6 @@
         args.add(concatStrings(DataFlavorSearcher.RICH_TEXT_NAMES));
 
         ProcessResults processResults =
-//                ProcessCommunicator.executeChildProcess(this.getClass(), "/Users/mcherkasov/ws/clipboard/DataFlover/out/production/DataFlover" +
-//                        " -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005 ",
-//                        args.toArray(new String[0]));
                 ProcessCommunicator.executeChildProcess(this.getClass(),
                         "." + File.separator + System.getProperty("java.class.path"), args.toArray(new String[]{}));
 
@@ -117,6 +104,13 @@
             throw new RuntimeException("TEST IS FAILED: Target has received" +
                     " corrupted data.");
         }
+        if (InterprocessMessages.NO_DROP_HAPPENED ==
+                processResults.getExitValue()) {
+            processResults.printProcessErrorOutput(System.err);
+            throw new RuntimeException("Error. Drop did not happen." +
+                " Target frame is possibly covered by a window of other application." +
+                " Please, rerun the test with all windows minimized.");
+        }
         processResults.verifyStdErr(System.err);
         processResults.verifyProcessExitValue(System.err);
         processResults.printProcessStandartOutput(System.out);
@@ -184,7 +178,7 @@
         }
     }
 
-    public static void main(String[] args) {
+    public static void main(String[] args) throws InterruptedException {
         Point dragSourcePoint = new Point(InterprocessArguments.DRAG_SOURCE_POINT_X_ARGUMENT.extractInt(args),
                 InterprocessArguments.DRAG_SOURCE_POINT_Y_ARGUMENT.extractInt(args));
         Point targetFrameLocation = new Point(InterprocessArguments.TARGET_FRAME_X_POSITION_ARGUMENT.extractInt(args),
@@ -197,6 +191,8 @@
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
+        sleep(5000);
+        System.exit(InterprocessMessages.NO_DROP_HAPPENED);
     }
 
 
--- a/jdk/test/java/awt/Desktop/OpenByUNCPathNameTest/OpenByUNCPathNameTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/awt/Desktop/OpenByUNCPathNameTest/OpenByUNCPathNameTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -45,6 +45,10 @@
             System.out.println("java.awt.Desktop is not supported on this platform.");
         } else {
             Desktop desktop = Desktop.getDesktop();
+            if (!desktop.isSupported(Desktop.Action.OPEN)) {
+                System.out.println("Action.OPEN is not supported on this platform.");
+                return;
+            }
             File file = File.createTempFile("Read Me File", ".txt");
             try {
                 // Test opening of the file with Windows local file path.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/EventDispatchThread/EDTShutdownTest/EDTShutdownTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8031694
+  @summary [macosx] TwentyThousandTest test intermittently hangs
+  @author Oleg Pekhovskiy
+  @run main EDTShutdownTest
+ */
+
+import java.awt.EventQueue;
+import java.awt.Toolkit;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import sun.awt.AWTAccessor;
+
+public class EDTShutdownTest {
+
+    private static boolean passed = false;
+
+    public static void main(String[] args) {
+        // Force EDT start with InvocationEvent
+        EventQueue.invokeLater(() -> {
+            // EventQueue is empty now
+            EventQueue queue = Toolkit.getDefaultToolkit()
+                               .getSystemEventQueue();
+            Thread thread = AWTAccessor.getEventQueueAccessor()
+                            .getDispatchThread(queue);
+            try {
+                /*
+                 * Clear EventDispatchThread.doDispatch flag to break message
+                 * loop in EventDispatchThread.pumpEventsForFilter()
+                 */
+                Method stopDispatching = thread.getClass()
+                        .getDeclaredMethod("stopDispatching", null);
+                stopDispatching.setAccessible(true);
+                stopDispatching.invoke(thread, null);
+
+                /*
+                 * Post another InvocationEvent that must be handled by another
+                 * instance of EDT
+                 */
+                EventQueue.invokeLater(() -> {
+                    passed = true;
+                });
+            }
+            catch (InvocationTargetException | NoSuchMethodException
+                   | IllegalAccessException e) {
+            }
+        });
+
+        // Wait for EDT shutdown
+        EventQueue queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
+        Thread thread = AWTAccessor.getEventQueueAccessor()
+                        .getDispatchThread(queue);
+        try {
+            thread.join();
+
+            /*
+             * Wait for another EDT instance to handle the InvocationEvent
+             * and shutdown
+             */
+            thread = AWTAccessor.getEventQueueAccessor()
+                     .getDispatchThread(queue);
+            if (thread != null) {
+                thread.join();
+            }
+        }
+        catch (InterruptedException e) {
+        }
+
+        if (passed) {
+            System.out.println("Test PASSED!");
+        }
+        else {
+            throw new RuntimeException("Test FAILED!");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/FileDialog/FileDialogForPackages/FileDialogForPackages.html	Wed Jul 05 19:33:51 2017 +0200
@@ -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.
+-->
+
+<html>
+<!--
+  @test
+  @bug 8026869
+  @summary Support apple.awt.use-file-dialog-packages property.
+  @author Petr Pchelko area=awt.filedialog
+  @library ../../regtesthelpers
+  @build Sysout
+  @run applet/manual=yesno FileDialogForPackages.html
+  -->
+<head>
+    <title> FileDialogForPackages </title>
+</head>
+<body>
+
+<h1>FileDialogForPackages<br>Bug ID: 8026869</h1>
+
+<p> See the dialog box (usually in upper left corner) for instructions</p>
+
+<APPLET CODE="FileDialogForPackages.class" WIDTH=200 HEIGHT=200></APPLET>
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/FileDialog/FileDialogForPackages/FileDialogForPackages.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,84 @@
+/*
+ * 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 sun.awt.OSInfo;
+import test.java.awt.regtesthelpers.Sysout;
+
+import java.applet.Applet;
+import java.awt.Button;
+import java.awt.FileDialog;
+import java.awt.Frame;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+public class FileDialogForPackages extends Applet implements ActionListener {
+    private static final String APPLICATIONS_FOLDER = "/Applications";
+
+    private volatile Button showBtn;
+    private volatile FileDialog fd;
+
+    @Override
+    public void init() {
+        if (OSInfo.getOSType() != OSInfo.OSType.MACOSX) {
+            Sysout.createDialogWithInstructions(new String[]{
+                    "Press PASS, this test is for MacOS X only."});
+            return;
+        }
+
+        System.setProperty("apple.awt.use-file-dialog-packages", "true");
+
+        setLayout(new GridLayout(1, 1));
+
+        fd = new FileDialog(new Frame(), "Open");
+        fd.setDirectory(APPLICATIONS_FOLDER);
+
+        showBtn = new Button("Show File Dialog");
+        showBtn.addActionListener(this);
+        add(showBtn);
+        String[] instructions = {
+                "1) Click on 'Show File Dialog' button. A file dialog will come up.",
+                "2) Navigate to the Applications folder if not already there",
+                "3) Check that the application bundles can be selected and can not be navigated",
+                "4) If it's true then the test passed, otherwise it failed."};
+        Sysout.createDialogWithInstructions(instructions);
+    }
+
+    @Override
+    public void start() {
+        setSize(200, 200);
+        show();
+    }
+
+    @Override
+    public void actionPerformed(ActionEvent e) {
+        if (e.getSource() == showBtn) {
+            fd.setVisible(true);
+            String output = fd.getFile();
+            if (output != null) {
+                Sysout.println(output + " is selected");
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Frame/ExceptionOnSetExtendedStateTest/ExceptionOnSetExtendedStateTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8032078
+   @summary Frame.setExtendedState throws RuntimeException, if
+            windowState=ICONIFIED|MAXIMIZED_BOTH, on OS X
+   @author Anton Litvinov
+*/
+
+import java.awt.*;
+
+import sun.awt.SunToolkit;
+
+public class ExceptionOnSetExtendedStateTest {
+    private static final int[] frameStates = { Frame.NORMAL, Frame.ICONIFIED, Frame.MAXIMIZED_BOTH };
+    private static final SunToolkit toolkit = (SunToolkit)Toolkit.getDefaultToolkit();
+
+    private static boolean validatePlatform() {
+        String osName = System.getProperty("os.name");
+        if (osName == null) {
+            throw new RuntimeException("Name of the current OS could not be retrieved.");
+        }
+        return osName.startsWith("Mac");
+    }
+
+    private static void testStateChange(int oldState, int newState, boolean decoratedFrame) {
+        System.out.println(String.format(
+            "testStateChange: oldState='%d', newState='%d', decoratedFrame='%b'",
+            oldState, newState, decoratedFrame));
+
+        Frame frame = new Frame("ExceptionOnSetExtendedStateTest");
+        frame.setSize(200, 200);
+        frame.setUndecorated(!decoratedFrame);
+        frame.setVisible(true);
+        toolkit.realSync();
+
+        frame.setExtendedState(oldState);
+        sleep(1000);
+        frame.setExtendedState(newState);
+
+        boolean stateWasNotChanged = true;
+        int currentState = 0;
+        for (int i = 0; (i < 3) && stateWasNotChanged; i++) {
+            sleep(1000);
+            currentState = frame.getExtendedState();
+            if ((currentState == newState) ||
+                (((newState & Frame.ICONIFIED) != 0) && ((currentState & Frame.ICONIFIED) != 0))) {
+                stateWasNotChanged = false;
+            }
+        }
+        frame.dispose();
+
+        if (stateWasNotChanged) {
+            throw new RuntimeException(String.format(
+                "Frame state was not changed. currentState='%d'", currentState));
+        }
+    }
+
+    private static void sleep(int millis) {
+        try {
+            Thread.sleep(millis);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    public static void main(String[] args) {
+        if (!validatePlatform()) {
+            System.out.println("This test is only for OS X.");
+            return;
+        }
+
+        // Verify that changing states of decorated/undecorated frame to/from supported states
+        // and the state bit mask ICONIFIED | MAXIMIZED_BOTH does not raise RuntimeException.
+        for (int i = 0; i < frameStates.length; i++) {
+            testStateChange(frameStates[i], Frame.ICONIFIED | Frame.MAXIMIZED_BOTH, true);
+            testStateChange(frameStates[i], Frame.ICONIFIED | Frame.MAXIMIZED_BOTH, false);
+            testStateChange(Frame.ICONIFIED | Frame.MAXIMIZED_BOTH, frameStates[i], true);
+            testStateChange(Frame.ICONIFIED | Frame.MAXIMIZED_BOTH, frameStates[i], false);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Multiscreen/MouseEventTest/MouseEventTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8017472
+  @summary MouseEvent has wrong coordinates when using multiple monitors
+  @run main MouseEventTest
+ */
+
+import sun.awt.SunToolkit;
+
+import java.awt.*;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+
+public class MouseEventTest {
+    static volatile boolean crossed = false;
+
+    static void sleep() throws InterruptedException {
+        ((SunToolkit) Toolkit.getDefaultToolkit()).realSync();
+        Thread.sleep(500);
+    }
+
+    public static void main(String[] args) throws AWTException, InterruptedException {
+        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+        GraphicsDevice[] gds = ge.getScreenDevices();
+        if (gds.length < 2) {
+            System.out.println("It's a multiscreen test... skipping!");
+            return;
+        }
+
+        for (int i = 0; i < gds.length; ++i) {
+            GraphicsDevice gd = gds[i];
+            GraphicsConfiguration gc = gd.getDefaultConfiguration();
+            Rectangle screen = gc.getBounds();
+            Robot robot = new Robot(gd);
+            robot.setAutoDelay(100);
+
+
+            Frame frame = new Frame(gc);
+            frame.setUndecorated(true);
+            frame.setSize(200, 200);
+            frame.setLocation(screen.x + 200, screen.y + 200);
+            frame.setBackground(Color.YELLOW);
+            frame.setVisible(true);
+            sleep();
+
+            Point loc = frame.getLocationOnScreen();
+            Dimension size = frame.getSize();
+            final Point point = new Point(
+                    loc.x + size.width / 2,
+                    loc.y + size.height / 2);
+
+            crossed = false;
+
+            frame.addMouseMotionListener(new MouseAdapter() {
+                @Override
+                public void mouseMoved(MouseEvent e) {
+                    if (point.equals(e.getLocationOnScreen())) {
+                        crossed = true;
+                    }
+                }
+            });
+
+            robot.mouseMove(point.x - 1, point.y - 1);
+            robot.mouseMove(point.x, point.y);
+
+            sleep();
+            frame.dispose();
+
+            if (!crossed) {
+                throw new RuntimeException("An expected mouse motion event was not received on the screen #" + i);
+            }
+        }
+
+        System.out.println("Test PASSED!");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Multiscreen/MultiScreenInsetsTest/MultiScreenInsetsTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8020443
+  @summary Frame is not created on the specified GraphicsDevice with two
+monitors
+  @author Oleg Pekhovskiy
+  @run main MultiScreenInsetsTest
+ */
+
+import java.awt.Frame;
+import java.awt.GraphicsConfiguration;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.Insets;
+import java.awt.Rectangle;
+import java.awt.Toolkit;
+import sun.awt.OSInfo;
+
+public class MultiScreenInsetsTest {
+    private static final int SIZE = 100;
+
+    public static void main(String[] args) throws InterruptedException {
+        OSInfo.OSType type = OSInfo.getOSType();
+        if (type != OSInfo.OSType.LINUX && type != OSInfo.OSType.SOLARIS) {
+            System.out.println("This test is for Solaris and Linux only..." +
+                               "skipping!");
+            return;
+        }
+
+        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+        GraphicsDevice[] gds = ge.getScreenDevices();
+        if (gds.length < 2) {
+            System.out.println("It's a multi-screen test... skipping!");
+            return;
+        }
+
+        for (int screen = 0; screen < gds.length; ++screen) {
+            GraphicsDevice gd = gds[screen];
+            GraphicsConfiguration gc = gd.getDefaultConfiguration();
+            Rectangle bounds = gc.getBounds();
+            Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
+
+            Frame frame = new Frame(gc);
+            frame.setLocation(bounds.x + (bounds.width - SIZE) / 2,
+                              bounds.y + (bounds.height - SIZE) / 2);
+            frame.setSize(SIZE, SIZE);
+            frame.setUndecorated(true);
+            frame.setVisible(true);
+
+            // Maximize Frame to reach the struts
+            frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
+            Thread.sleep(2000);
+
+            Rectangle frameBounds = frame.getBounds();
+            frame.dispose();
+            if (bounds.x + insets.left != frameBounds.x
+                || bounds.y + insets.top != frameBounds.y
+                || bounds.width - insets.right - insets.left != frameBounds.width
+                || bounds.height - insets.bottom - insets.top != frameBounds.height) {
+                throw new RuntimeException("Test FAILED! Wrong screen #" +
+                                           screen + " insets: " + insets);
+            }
+        }
+        System.out.println("Test PASSED!");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Multiscreen/MultiScreenLocationTest/MultiScreenLocationTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8013116
+  @summary Robot moves mouse to point which differs from set in mouseMove on
+ Unity shell
+  @author Oleg Pekhovskiy
+  @library ../../regtesthelpers
+  @build Util
+  @run main MultiScreenLocationTest
+ */
+
+import java.awt.AWTException;
+import java.awt.Color;
+import java.awt.Frame;
+import java.awt.GraphicsConfiguration;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.MouseInfo;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.Robot;
+import java.awt.image.BufferedImage;
+import test.java.awt.regtesthelpers.Util;
+
+public class MultiScreenLocationTest {
+    private static final Point mouseOffset = new Point(150, 150);
+    private static final Point frameOffset = new Point(100, 100);
+    private static final Color color = Color.YELLOW;
+
+    private static String getErrorText(final String name, int screen)
+    {
+        return name + " test failed on Screen #" + screen + "!";
+    }
+
+    public static void main(String[] args) throws AWTException
+    {
+        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+        GraphicsDevice[] gds = ge.getScreenDevices();
+        if (gds.length < 2) {
+            System.out.println("It's a multiscreen test... skipping!");
+            return;
+        }
+
+        for (int i = 0; i < gds.length; ++i) {
+            GraphicsDevice gd = gds[i];
+            GraphicsConfiguration gc = gd.getDefaultConfiguration();
+            Rectangle screen = gc.getBounds();
+            Robot robot = new Robot(gd);
+
+            // check Robot.mouseMove()
+            robot.mouseMove(screen.x + mouseOffset.x, screen.y + mouseOffset.y);
+            Point mouse = MouseInfo.getPointerInfo().getLocation();
+            Point point = screen.getLocation();
+            point.translate(mouseOffset.x, mouseOffset.y);
+            if (!point.equals(mouse)) {
+                throw new RuntimeException(getErrorText("Robot.mouseMove", i));
+            }
+
+            // check Robot.getPixelColor()
+            Frame frame = new Frame(gc);
+            frame.setUndecorated(true);
+            frame.setSize(100, 100);
+            frame.setLocation(screen.x + frameOffset.x, screen.y + frameOffset.y);
+            frame.setBackground(color);
+            frame.setVisible(true);
+            robot.waitForIdle();
+            Rectangle bounds = frame.getBounds();
+            if (!Util.testBoundsColor(bounds, color, 5, 1000, robot)) {
+                throw new RuntimeException(getErrorText("Robot.getPixelColor", i));
+            }
+
+            // check Robot.createScreenCapture()
+            BufferedImage image = robot.createScreenCapture(bounds);
+            int rgb = color.getRGB();
+            if (image.getRGB(0, 0) != rgb
+                || image.getRGB(image.getWidth() - 1, 0) != rgb
+                || image.getRGB(image.getWidth() - 1, image.getHeight() - 1) != rgb
+                || image.getRGB(0, image.getHeight() - 1) != rgb) {
+                    throw new RuntimeException(
+                            getErrorText("Robot.createScreenCapture", i));
+            }
+            frame.dispose();
+        }
+
+        System.out.println("Test PASSED!");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Paint/PaintNativeOnUpdate.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.awt.AWTException;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Frame;
+import java.awt.Graphics;
+import java.awt.Label;
+import java.awt.Point;
+import java.awt.Robot;
+import java.awt.Toolkit;
+
+import sun.awt.SunToolkit;
+
+/**
+ * @test
+ * @bug 7157680
+ * @author Sergey Bylokhov
+ */
+public final class PaintNativeOnUpdate extends Label {
+
+    private boolean fullUpdate = true;
+
+    public static void main(final String[] args) throws AWTException {
+        final Frame frame = new Frame();
+        final Component label = new PaintNativeOnUpdate();
+        frame.setBackground(Color.RED);
+        frame.add(label);
+        frame.setSize(300, 300);
+        frame.setUndecorated(true);
+        frame.setLocationRelativeTo(null);
+        frame.setVisible(true);
+        sleep();
+        label.repaint();// first paint
+        sleep();
+        label.repaint();// incremental paint
+        sleep();
+
+        Robot robot = new Robot();
+        robot.setAutoDelay(50);
+        Point point = label.getLocationOnScreen();
+        Color color = robot.getPixelColor(point.x + label.getWidth() / 2,
+                                          point.y + label.getHeight() / 2);
+        if (!color.equals(Color.GREEN)) {
+            System.err.println("Expected color = " + Color.GREEN);
+            System.err.println("Actual color = " + color);
+            throw new RuntimeException();
+        }
+        frame.dispose();
+    }
+
+    @Override
+    public void update(final Graphics g) {
+        if (fullUpdate) {
+            //full paint
+            g.setColor(Color.GREEN);
+            g.fillRect(0, 0, getWidth(), getHeight());
+            fullUpdate = false;
+        } else {
+            // Do nothing
+            // incremental paint
+        }
+    }
+
+    @Override
+    public void paint(final Graphics g) {
+        // Do nothing
+    }
+
+    private static void sleep() {
+        try {
+            ((SunToolkit) (Toolkit.getDefaultToolkit())).realSync();
+            Thread.sleep(1000);
+        } catch (InterruptedException ignored) {
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/SplashScreen/FullscreenAfterSplash/FullScreenAfterSplash.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,140 @@
+/*
+* 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 sun.awt.OSInfo;
+
+import java.awt.*;
+import java.awt.Robot;
+import java.awt.event.InputEvent;
+import java.lang.InterruptedException;
+import java.lang.System;
+import java.lang.Thread;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import javax.swing.*;
+
+/*
+ * @test
+ * @bug 8024185
+ * @summary Native Mac OS X full screen does not work after showing the splash
+ * @library ../
+ * @build GenerateTestImage
+ * @run main GenerateTestImage
+ * @author Petr Pchelko area=awt.event
+ * @run main/othervm -splash:test.png FullScreenAfterSplash
+ */
+public class FullScreenAfterSplash {
+
+    private static JFrame frame;
+
+    private static volatile boolean windowEnteringFullScreen = false;
+    private static volatile boolean windowEnteredFullScreen = false;
+
+    public static void main(String[] args) throws Exception {
+
+        if (OSInfo.getOSType() != OSInfo.OSType.MACOSX) {
+            System.out.println("The test is applicable only to Mac OS X. Passed");
+            return;
+        }
+        try {
+            //Move the mouse out, because it could interfere with the test.
+            Robot r = new Robot();
+            r.mouseMove(0, 0);
+            sleep();
+
+            SwingUtilities.invokeAndWait(FullScreenAfterSplash::createAndShowGUI);
+            sleep();
+
+            Point fullScreenButtonPos = frame.getLocation();
+            fullScreenButtonPos.translate(frame.getWidth() - 10, 10);
+            r.mouseMove(fullScreenButtonPos.x, fullScreenButtonPos.y);
+
+            //Cant use waitForIdle for full screen transition.
+            int waitCount = 0;
+            while (!windowEnteringFullScreen) {
+                r.mousePress(InputEvent.BUTTON1_MASK);
+                r.mouseRelease(InputEvent.BUTTON1_MASK);
+                Thread.sleep(100);
+                if (waitCount++ > 10) {
+                    System.err.println("Can't enter full screen mode. Failed.");
+                    System.exit(1);
+                }
+            }
+
+            waitCount = 0;
+            while (!windowEnteredFullScreen) {
+                Thread.sleep(100);
+                if (waitCount++ > 10) {
+                    System.err.println("Can't enter full screen mode. Failed.");
+                    System.exit(1);
+                }
+            }
+        } finally {
+            if (frame != null) {
+                frame.dispose();
+            }
+        }
+    }
+
+    private static void createAndShowGUI() {
+        frame = new JFrame(" Fullscreen OSX Bug ");
+        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+        enableFullScreen(frame);
+        frame.setBounds(100, 100, 100, 100);
+        frame.pack();
+        frame.setVisible(true);
+    }
+
+    /*
+     *  Use reflection to make a test compilable on not Mac OS X
+     */
+    private static void enableFullScreen(Window window) {
+        try {
+            Class<?> fullScreenUtilities = Class.forName("com.apple.eawt.FullScreenUtilities");
+            Method setWindowCanFullScreen = fullScreenUtilities.getMethod("setWindowCanFullScreen", Window.class, boolean.class);
+            setWindowCanFullScreen.invoke(fullScreenUtilities, window, true);
+            Class fullScreenListener = Class.forName("com.apple.eawt.FullScreenListener");
+            Object listenerObject = Proxy.newProxyInstance(fullScreenListener.getClassLoader(), new Class[]{fullScreenListener}, (proxy, method, args) -> {
+                switch (method.getName()) {
+                    case "windowEnteringFullScreen":
+                        windowEnteringFullScreen = true;
+                        break;
+                    case "windowEnteredFullScreen":
+                        windowEnteredFullScreen = true;
+                        break;
+                }
+                return null;
+            });
+            Method addFullScreenListener = fullScreenUtilities.getMethod("addFullScreenListenerTo", Window.class, fullScreenListener);
+            addFullScreenListener.invoke(fullScreenUtilities, window, listenerObject);
+        } catch (Exception e) {
+            throw new RuntimeException("FullScreen utilities not available", e);
+        }
+    }
+
+    private static void sleep() {
+        try {
+            Thread.sleep(500);
+        } catch (InterruptedException ignored) { }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/SplashScreen/GenerateTestImage.java	Wed Jul 05 19:33:51 2017 +0200
@@ -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.
+*/
+
+import javax.imageio.ImageIO;
+import java.awt.*;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.FileOutputStream;
+
+/**
+ * A utility to generate a test image for the SplashScreen test
+ */
+public class GenerateTestImage {
+    private static final int IMAGE_SIZE = 20;
+
+    public static void main(String[] args) throws Exception {
+        String path = System.getProperty("test.classes") + File.separator + "test.png";
+
+        BufferedImage image = new BufferedImage(IMAGE_SIZE, IMAGE_SIZE, BufferedImage.TYPE_INT_ARGB);
+        Graphics2D graphics2D = image.createGraphics();
+        graphics2D.setColor(Color.red);
+        graphics2D.fillOval(0, 0, IMAGE_SIZE, IMAGE_SIZE);
+        graphics2D.dispose();;
+
+        try(FileOutputStream fos = new FileOutputStream(path)) {
+            ImageIO.write(image, "png", fos);
+        }
+    }
+}
--- a/jdk/test/java/awt/TextArea/SelectionVisible/SelectionVisible.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/awt/TextArea/SelectionVisible/SelectionVisible.java	Wed Jul 05 19:33:51 2017 +0200
@@ -31,32 +31,32 @@
 
 public final class SelectionVisible extends Applet {
 
-    TextArea tf;
+    private TextArea ta;
 
     @Override
     public void init() {
-        tf = new TextArea(3, 20);
-        tf.setText("0123456789");
-        tf.select(0, 6);
+        ta = new TextArea(4, 20);
+        ta.setText("01234\n56789");
+        ta.select(3, 9);
 
-        final TextArea ta = new TextArea("INSTRUCTIONS:\n"
-                                                 + "The text 012345 should be selected in the TextArea.\n"
+        final TextArea instruction = new TextArea("INSTRUCTIONS:\n"
+                                                 + "The text 34567 should be selected in the TextArea.\n"
                                                  + "If this is what you observe, then the test passes.\n"
                                                  + "Otherwise, the test fails.", 40, 5,
                                          TextArea.SCROLLBARS_NONE);
-        ta.setEditable(false);
-        ta.setPreferredSize(new Dimension(300, 70));
+        instruction.setEditable(false);
+        instruction.setPreferredSize(new Dimension(300, 70));
         final Panel panel = new Panel();
         panel.setLayout(new FlowLayout());
-        panel.add(tf);
+        panel.add(ta);
         setLayout(new BorderLayout());
-        add(ta, BorderLayout.CENTER);
+        add(instruction, BorderLayout.CENTER);
         add(panel, BorderLayout.PAGE_END);
     }
 
     @Override
     public void start() {
         setVisible(true);
-        tf.requestFocus();
+        ta.requestFocus();
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/TrayIcon/AddPopupAfterShowTest/AddPopupAfterShowTest.html	Wed Jul 05 19:33:51 2017 +0200
@@ -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.
+-->
+
+<html>
+<!--
+  @test
+  @bug 8007220
+  @summary The popup menu is not added to the tray icon after it was added to tray
+  @author Petr Pchelko
+  @library ../../regtesthelpers
+  @build Sysout
+  @run applet/manual=yesno AddPopupAfterShowTest.html
+  -->
+<head>
+    <title> AddPopupAfterShowTest </title>
+</head>
+<body>
+
+<h1>AddPopupAfterShowTest<br>Bug ID: 8007220</h1>
+
+<p> See the dialog box (usually in upper left corner) for instructions</p>
+
+<APPLET CODE="AddPopupAfterShowTest.class" WIDTH=200 HEIGHT=200></APPLET>
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/TrayIcon/AddPopupAfterShowTest/AddPopupAfterShowTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,106 @@
+/*
+ * 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 test.java.awt.regtesthelpers.Sysout;
+
+import java.applet.Applet;
+import java.awt.*;
+import java.awt.image.BufferedImage;
+
+public class AddPopupAfterShowTest extends Applet {
+    @Override
+    public void init() {
+        if (!SystemTray.isSupported()) {
+            Sysout.createDialogWithInstructions(new String[]{
+                    "Press PASS, the System Tray is not supported"});
+            return;
+        }
+
+
+        String[] instructions = {
+                "1) The red circle icon was added to the system tray.",
+                "2) Check that a popup menu is opened when the icon is clicked.",
+                "3) If true the test is passed, otherwise failed."};
+        Sysout.createDialogWithInstructions(instructions);
+    }
+
+    @Override
+    public void start() {
+        setSize(200, 200);
+        show();
+
+        createSystemTrayIcon();
+    }
+
+    private static void createSystemTrayIcon() {
+        final TrayIcon trayIcon = new TrayIcon(createTrayIconImage());
+        trayIcon.setImageAutoSize(true);
+
+        try {
+            // Add tray icon to system tray *before* adding popup menu to demonstrate buggy behaviour
+            SystemTray.getSystemTray().add(trayIcon);
+            trayIcon.setPopupMenu(createTrayIconPopupMenu());
+        } catch (final AWTException awte) {
+            awte.printStackTrace();
+        }
+    }
+
+    private static Image createTrayIconImage() {
+        /**
+         * Create a small image of a red circle to use as the icon for the tray icon
+         */
+        int trayIconImageSize = 32;
+        final BufferedImage trayImage = new BufferedImage(trayIconImageSize, trayIconImageSize, BufferedImage.TYPE_INT_ARGB);
+        final Graphics2D trayImageGraphics = (Graphics2D) trayImage.getGraphics();
+
+        trayImageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+
+        trayImageGraphics.setColor(new Color(255, 255, 255, 0));
+        trayImageGraphics.fillRect(0, 0, trayImage.getWidth(), trayImage.getHeight());
+
+        trayImageGraphics.setColor(Color.red);
+
+        int trayIconImageInset = 4;
+        trayImageGraphics.fillOval(trayIconImageInset,
+                trayIconImageInset,
+                trayImage.getWidth() - 2 * trayIconImageInset,
+                trayImage.getHeight() - 2 * trayIconImageInset);
+
+        trayImageGraphics.setColor(Color.darkGray);
+
+        trayImageGraphics.drawOval(trayIconImageInset,
+                trayIconImageInset,
+                trayImage.getWidth() - 2 * trayIconImageInset,
+                trayImage.getHeight() - 2 * trayIconImageInset);
+
+        return trayImage;
+    }
+
+    private static PopupMenu createTrayIconPopupMenu() {
+        final PopupMenu trayIconPopupMenu = new PopupMenu();
+        final MenuItem popupMenuItem = new MenuItem("TEST PASSED!");
+        trayIconPopupMenu.add(popupMenuItem);
+        return trayIconPopupMenu;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/TrayIcon/PopupMenuLeakTest/PopupMenuLeakTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,149 @@
+/*
+ * 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 8007220
+  @summary Reference to the popup leaks after the TrayIcon is removed
+  @author Petr Pchelko
+  @run main/othervm -Xmx50m PopupMenuLeakTest
+ */
+
+import java.awt.*;
+import javax.swing.SwingUtilities;
+import sun.awt.SunToolkit;
+
+import java.awt.image.BufferedImage;
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+
+public class PopupMenuLeakTest {
+
+    static final AtomicReference<WeakReference<TrayIcon>> iconWeakReference = new AtomicReference<>();
+    static final AtomicReference<WeakReference<PopupMenu>> popupWeakReference = new AtomicReference<>();
+
+    public static void main(String[] args) throws Exception {
+        SwingUtilities.invokeAndWait(PopupMenuLeakTest::createSystemTrayIcon);
+        sleep();
+        // To make the test automatic we explicitly call addNotify on a popup to create the peer
+        SwingUtilities.invokeAndWait(PopupMenuLeakTest::addNotifyPopup);
+        sleep();
+        SwingUtilities.invokeAndWait(PopupMenuLeakTest::removeIcon);
+        sleep();
+        assertCollected(popupWeakReference.get(), "Failed, reference to popup not collected");
+        assertCollected(iconWeakReference.get(), "Failed, reference to tray icon not collected");
+    }
+
+    private static void addNotifyPopup() {
+        PopupMenu menu = popupWeakReference.get().get();
+        if (menu == null) {
+            throw new RuntimeException("Failed: popup collected too early");
+        }
+        menu.addNotify();
+    }
+
+    private static void removeIcon() {
+        TrayIcon icon = iconWeakReference.get().get();
+        if (icon == null) {
+            throw new RuntimeException("Failed: TrayIcon collected too early");
+        }
+        SystemTray.getSystemTray().remove(icon);
+    }
+
+    private static void assertCollected(WeakReference<?> reference, String message) {
+        java.util.List<byte[]> bytes = new ArrayList<>();
+        for (int i = 0; i < 5; i ++) {
+            try {
+                while (true) {
+                    bytes.add(new byte[1024]);
+                }
+            } catch (OutOfMemoryError err) {
+                bytes = new ArrayList<>();
+            }
+        }
+        if (reference.get() != null) {
+            throw new RuntimeException(message);
+        }
+    }
+
+    private static void createSystemTrayIcon() {
+        final TrayIcon trayIcon = new TrayIcon(createTrayIconImage());
+        trayIcon.setImageAutoSize(true);
+
+        try {
+            // Add tray icon to system tray *before* adding popup menu to demonstrate buggy behaviour
+            trayIcon.setPopupMenu(createTrayIconPopupMenu());
+            SystemTray.getSystemTray().add(trayIcon);
+            iconWeakReference.set(new WeakReference<>(trayIcon));
+            popupWeakReference.set(new WeakReference<>(trayIcon.getPopupMenu()));
+        } catch (final AWTException awte) {
+            awte.printStackTrace();
+        }
+    }
+
+    private static Image createTrayIconImage() {
+        /**
+         * Create a small image of a red circle to use as the icon for the tray icon
+         */
+        int trayIconImageSize = 32;
+        final BufferedImage trayImage = new BufferedImage(trayIconImageSize, trayIconImageSize, BufferedImage.TYPE_INT_ARGB);
+        final Graphics2D trayImageGraphics = (Graphics2D) trayImage.getGraphics();
+
+        trayImageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+
+        trayImageGraphics.setColor(new Color(255, 255, 255, 0));
+        trayImageGraphics.fillRect(0, 0, trayImage.getWidth(), trayImage.getHeight());
+
+        trayImageGraphics.setColor(Color.red);
+
+        int trayIconImageInset = 4;
+        trayImageGraphics.fillOval(trayIconImageInset,
+                trayIconImageInset,
+                trayImage.getWidth() - 2 * trayIconImageInset,
+                trayImage.getHeight() - 2 * trayIconImageInset);
+
+        trayImageGraphics.setColor(Color.darkGray);
+
+        trayImageGraphics.drawOval(trayIconImageInset,
+                trayIconImageInset,
+                trayImage.getWidth() - 2 * trayIconImageInset,
+                trayImage.getHeight() - 2 * trayIconImageInset);
+
+        return trayImage;
+    }
+
+    private static PopupMenu createTrayIconPopupMenu() {
+        final PopupMenu trayIconPopupMenu = new PopupMenu();
+        final MenuItem popupMenuItem = new MenuItem("TEST!");
+        trayIconPopupMenu.add(popupMenuItem);
+        return trayIconPopupMenu;
+    }
+
+    private static void sleep() {
+        ((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
+        try {
+            Thread.sleep(100);
+        } catch (InterruptedException ignored) { }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Window/AlwaysOnTop/TestAlwaysOnTopBeforeShow.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,472 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 6236247
+@summary Test that setting of always-on-top flags before showing window works
+@author dom@sparc.spb.su: area=awt.toplevel
+@run main TestAlwaysOnTopBeforeShow
+*/
+
+/**
+ * TestAlwaysOnTopBeforeShow.java
+ *
+ * summary:  Test that always-on-top works in the following situations:
+ * - when set on a window before showing
+ * - when set on a child dialog
+ * - that it doesn't generate focus event when set on an invisible window
+ */
+
+import java.awt.*;
+import java.awt.event.*;
+import java.util.concurrent.atomic.AtomicBoolean;
+import sun.awt.SunToolkit;
+
+
+//*** global search and replace TestAlwaysOnTopBeforeShow with name of the test ***
+
+public class TestAlwaysOnTopBeforeShow
+{
+
+    //*** test-writer defined static variables go here ***
+
+    private static AtomicBoolean focused = new AtomicBoolean();
+    private static AtomicBoolean pressed = new AtomicBoolean();
+    private static volatile Object pressedTarget;
+    private static void init()
+    {
+        //*** Create instructions for the user here ***
+
+        Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
+                public void eventDispatched(AWTEvent e) {
+                    if (e.getID() == MouseEvent.MOUSE_PRESSED) {
+                        synchronized(pressed) {
+                            pressed.set(true);
+                            pressedTarget = e.getSource();
+                            pressed.notifyAll();
+                        }
+                    }
+                }
+            }, AWTEvent.MOUSE_EVENT_MASK);
+
+        Frame f = new Frame("always-on-top");
+        f.setBounds(0, 0, 200, 200);
+        f.addFocusListener(new FocusAdapter() {
+                public void focusGained(FocusEvent e) {
+                    synchronized(focused) {
+                        focused.set(true);
+                        focused.notifyAll();
+                    }
+                }
+            });
+
+        f.setAlwaysOnTop(true);
+
+        waitForIdle(1000);
+        if (focused.get()) {
+            throw new RuntimeException("Always-on-top generated focus event");
+        }
+
+        f.setVisible(true);
+
+        waitFocused(f, focused);
+        focused.set(false);
+
+        Frame f2 = new Frame("auxilary");
+        f2.setBounds(100, 0, 200, 100);
+        f2.setVisible(true);
+        f2.toFront();
+        waitForIdle(1000);
+
+        Point location = f.getLocationOnScreen();
+        Dimension size = f.getSize();
+        checkOnTop(f, f2, location.x + size.width / 2, location.y + size.height / 2);
+
+        Dialog d = new Dialog(f, "Always-on-top");
+        d.pack();
+        d.setBounds(0, 0, 100, 100);
+
+        waitForIdle(1000);
+        checkOnTop(f, f2, location.x + size.width / 2, location.y + size.height / 2);
+        waitForIdle(1000);
+
+        focused.set(false);
+        f.setVisible(false);
+        f.setAlwaysOnTop(false);
+        waitForIdle(1000);
+        if (focused.get()) {
+            throw new RuntimeException("Always-on-top generated focus event");
+        }
+
+        TestAlwaysOnTopBeforeShow.pass();
+
+    }//End  init()
+
+    private static void waitForIdle(int mls) {
+        ((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
+        try {
+            Thread.sleep(mls);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }
+    }
+
+    static void waitFocused(Window w, AtomicBoolean b) {
+        try {
+            synchronized(b) {
+                if (w.isFocusOwner()) {
+                    return;
+                }
+                b.wait(3000);
+            }
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+        if (!w.isFocusOwner()) {
+            throw new RuntimeException("Can't make " + w + " focus owner");
+        }
+    }
+
+    static void checkOnTop(Window ontop, Window under, int x, int y) {
+        under.toFront();
+        try {
+            Robot robot = new Robot();
+            robot.mouseMove(x, y);
+            robot.mousePress(InputEvent.BUTTON1_MASK);
+            robot.mouseRelease(InputEvent.BUTTON1_MASK);
+            synchronized(pressed) {
+                if (pressed.get()) {
+                    if (pressedTarget != ontop) {
+                        throw new RuntimeException("Pressed at wrong location: " + pressedTarget);
+                    }
+                } else {
+                    pressed.wait(5000);
+                }
+            }
+            if (!pressed.get() || pressedTarget != ontop) {
+                throw new RuntimeException("Pressed at wrong location: " + pressedTarget);
+            }
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /*****************************************************
+     * Standard Test Machinery Section
+     * DO NOT modify anything in this section -- it's a
+     * standard chunk of code which has all of the
+     * synchronisation necessary for the test harness.
+     * By keeping it the same in all tests, it is easier
+     * to read and understand someone else's test, as
+     * well as insuring that all tests behave correctly
+     * with the test harness.
+     * There is a section following this for test-
+     * classes
+     ******************************************************/
+    private static boolean theTestPassed = false;
+    private static boolean testGeneratedInterrupt = false;
+    private static String failureMessage = "";
+
+    private static Thread mainThread = null;
+
+    private static int sleepTime = 300000;
+
+    // Not sure about what happens if multiple of this test are
+    //  instantiated in the same VM.  Being static (and using
+    //  static vars), it aint gonna work.  Not worrying about
+    //  it for now.
+    public static void main( String args[] ) throws InterruptedException
+    {
+        mainThread = Thread.currentThread();
+        try
+        {
+            init();
+        }
+        catch( TestPassedException e )
+        {
+            //The test passed, so just return from main and harness will
+            // interepret this return as a pass
+            return;
+        }
+        //At this point, neither test pass nor test fail has been
+        // called -- either would have thrown an exception and ended the
+        // test, so we know we have multiple threads.
+
+        //Test involves other threads, so sleep and wait for them to
+        // called pass() or fail()
+        try
+        {
+            Thread.sleep( sleepTime );
+            //Timed out, so fail the test
+            throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" );
+        }
+        catch (InterruptedException e)
+        {
+            //The test harness may have interrupted the test.  If so, rethrow the exception
+            // so that the harness gets it and deals with it.
+            if( ! testGeneratedInterrupt ) throw e;
+
+            //reset flag in case hit this code more than once for some reason (just safety)
+            testGeneratedInterrupt = false;
+
+            if ( theTestPassed == false )
+            {
+                throw new RuntimeException( failureMessage );
+            }
+        }
+
+    }//main
+
+    public static synchronized void setTimeoutTo( int seconds )
+    {
+        sleepTime = seconds * 1000;
+    }
+
+    public static synchronized void pass()
+    {
+        Sysout.println( "The test passed." );
+        Sysout.println( "The test is over, hit  Ctl-C to stop Java VM" );
+        //first check if this is executing in main thread
+        if ( mainThread == Thread.currentThread() )
+        {
+            //Still in the main thread, so set the flag just for kicks,
+            // and throw a test passed exception which will be caught
+            // and end the test.
+            theTestPassed = true;
+            throw new TestPassedException();
+        }
+        theTestPassed = true;
+        testGeneratedInterrupt = true;
+        mainThread.interrupt();
+    }//pass()
+
+    public static synchronized void fail()
+    {
+        //test writer didn't specify why test failed, so give generic
+        fail( "it just plain failed! :-)" );
+    }
+
+    public static synchronized void fail( String whyFailed )
+    {
+        Sysout.println( "The test failed: " + whyFailed );
+        Sysout.println( "The test is over, hit  Ctl-C to stop Java VM" );
+        //check if this called from main thread
+        if ( mainThread == Thread.currentThread() )
+        {
+            //If main thread, fail now 'cause not sleeping
+            throw new RuntimeException( whyFailed );
+        }
+        theTestPassed = false;
+        testGeneratedInterrupt = true;
+        failureMessage = whyFailed;
+        mainThread.interrupt();
+    }//fail()
+
+}// class TestAlwaysOnTopBeforeShow
+
+//This exception is used to exit from any level of call nesting
+// when it's determined that the test has passed, and immediately
+// end the test.
+class TestPassedException extends RuntimeException
+{
+}
+
+//*********** End Standard Test Machinery Section **********
+
+
+//************ Begin classes defined for the test ****************
+
+// if want to make listeners, here is the recommended place for them, then instantiate
+//  them in init()
+
+/* Example of a class which may be written as part of a test
+class NewClass implements anInterface
+ {
+   static int newVar = 0;
+
+   public void eventDispatched(AWTEvent e)
+    {
+      //Counting events to see if we get enough
+      eventCount++;
+
+      if( eventCount == 20 )
+       {
+         //got enough events, so pass
+
+         TestAlwaysOnTopBeforeShow.pass();
+       }
+      else if( tries == 20 )
+       {
+         //tried too many times without getting enough events so fail
+
+         TestAlwaysOnTopBeforeShow.fail();
+       }
+
+    }// eventDispatched()
+
+ }// NewClass class
+
+*/
+
+
+//************** End classes defined for the test *******************
+
+
+
+
+/****************************************************
+ Standard Test Machinery
+ DO NOT modify anything below -- it's a standard
+  chunk of code whose purpose is to make user
+  interaction uniform, and thereby make it simpler
+  to read and understand someone else's test.
+ ****************************************************/
+
+/**
+ This is part of the standard test machinery.
+ It creates a dialog (with the instructions), and is the interface
+  for sending text messages to the user.
+ To print the instructions, send an array of strings to Sysout.createDialog
+  WithInstructions method.  Put one line of instructions per array entry.
+ To display a message for the tester to see, simply call Sysout.println
+  with the string to be displayed.
+ This mimics System.out.println but works within the test harness as well
+  as standalone.
+ */
+
+class Sysout
+{
+    private static TestDialog dialog;
+
+    public static void createDialogWithInstructions( String[] instructions )
+    {
+        dialog = new TestDialog( new Frame(), "Instructions" );
+        dialog.printInstructions( instructions );
+        dialog.setVisible(true);
+        println( "Any messages for the tester will display here." );
+    }
+
+    public static void createDialog( )
+    {
+        dialog = new TestDialog( new Frame(), "Instructions" );
+        String[] defInstr = { "Instructions will appear here. ", "" } ;
+        dialog.printInstructions( defInstr );
+        dialog.setVisible(true);
+        println( "Any messages for the tester will display here." );
+    }
+
+
+    public static void printInstructions( String[] instructions )
+    {
+        dialog.printInstructions( instructions );
+    }
+
+
+    public static void println( String messageIn )
+    {
+        System.out.println(messageIn);
+    }
+
+}// Sysout  class
+
+/**
+  This is part of the standard test machinery.  It provides a place for the
+   test instructions to be displayed, and a place for interactive messages
+   to the user to be displayed.
+  To have the test instructions displayed, see Sysout.
+  To have a message to the user be displayed, see Sysout.
+  Do not call anything in this dialog directly.
+  */
+class TestDialog extends Dialog
+{
+
+    TextArea instructionsText;
+    TextArea messageText;
+    int maxStringLength = 80;
+
+    //DO NOT call this directly, go through Sysout
+    public TestDialog( Frame frame, String name )
+    {
+        super( frame, name );
+        int scrollBoth = TextArea.SCROLLBARS_BOTH;
+        instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
+        add( "North", instructionsText );
+
+        messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
+        add("Center", messageText);
+
+        pack();
+
+        setVisible(true);
+    }// TestDialog()
+
+    //DO NOT call this directly, go through Sysout
+    public void printInstructions( String[] instructions )
+    {
+        //Clear out any current instructions
+        instructionsText.setText( "" );
+
+        //Go down array of instruction strings
+
+        String printStr, remainingStr;
+        for( int i=0; i < instructions.length; i++ )
+        {
+            //chop up each into pieces maxSringLength long
+            remainingStr = instructions[ i ];
+            while( remainingStr.length() > 0 )
+            {
+                //if longer than max then chop off first max chars to print
+                if( remainingStr.length() >= maxStringLength )
+                {
+                    //Try to chop on a word boundary
+                    int posOfSpace = remainingStr.
+                        lastIndexOf( ' ', maxStringLength - 1 );
+
+                    if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
+
+                    printStr = remainingStr.substring( 0, posOfSpace + 1 );
+                    remainingStr = remainingStr.substring( posOfSpace + 1 );
+                }
+                //else just print
+                else
+                {
+                    printStr = remainingStr;
+                    remainingStr = "";
+                }
+
+                instructionsText.append( printStr + "\n" );
+
+            }// while
+
+        }// for
+
+    }//printInstructions()
+
+    //DO NOT call this directly, go through Sysout
+    public void displayMessage( String messageIn )
+    {
+        messageText.append( messageIn + "\n" );
+        System.out.println(messageIn);
+    }
+
+}// TestDialog  class
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Window/BackgroundIsNotUpdated/BackgroundIsNotUpdated.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,84 @@
+/*
+ * 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.awt.AWTException;
+import java.awt.Color;
+import java.awt.Frame;
+import java.awt.Graphics;
+import java.awt.Point;
+import java.awt.Robot;
+import java.awt.Toolkit;
+import java.awt.Window;
+
+import sun.awt.SunToolkit;
+
+/**
+ * @test
+ * @bug 8001472
+ * @summary Background of the window should not depend from the paint()/update()
+ * @author Sergey Bylokhov
+ */
+public final class BackgroundIsNotUpdated extends Window {
+
+    public BackgroundIsNotUpdated(final Frame owner) {
+        super(owner);
+    }
+
+    @Override
+    public void paint(final Graphics ignored) {
+        // Intentionally left blank
+    }
+
+    @Override
+    public void update(final Graphics ignored) {
+        // Intentionally left blank
+    }
+
+    public static void main(final String[] args) throws AWTException {
+        final Window window = new BackgroundIsNotUpdated(null);
+        window.setSize(300, 300);
+        window.setLocationRelativeTo(null);
+        window.setVisible(true);
+        sleep();
+        window.setBackground(Color.GREEN);
+        sleep();
+        final Robot robot = new Robot();
+        robot.setAutoDelay(200);
+        Point point = window.getLocationOnScreen();
+        Color color = robot.getPixelColor(point.x + window.getWidth() / 2,
+                                          point.y + window.getHeight() / 2);
+        window.dispose();
+        if (!color.equals(Color.GREEN)) {
+            throw new RuntimeException(
+                    "Expected: " + Color.GREEN + " , Actual: " + color);
+        }
+    }
+
+    private static void sleep() {
+        try {
+            ((SunToolkit) Toolkit.getDefaultToolkit()).realSync();
+            Thread.sleep(1000);
+        } catch (InterruptedException ignored) {
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/dnd/AcceptDropMultipleTimes/AcceptDropMultipleTimes.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,103 @@
+/*
+ * 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 8029979
+ * @summary Checks if acceptDrop() can be called several times
+ * @library ../../regtesthelpers
+ * @build Util
+ * @compile AcceptDropMultipleTimes.java
+ * @run main/othervm AcceptDropMultipleTimes
+ * @author anthony.petrov@oracle.com
+ */
+
+import test.java.awt.regtesthelpers.Util;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.datatransfer.*;
+import java.awt.dnd.*;
+import java.awt.event.InputEvent;
+
+public class AcceptDropMultipleTimes {
+
+    private static final int FRAME_SIZE = 100;
+    private static final int FRAME_LOCATION = 100;
+
+    private static volatile Frame f;
+
+    private static void initAndShowUI() {
+        f = new Frame("Test frame");
+        f.setBounds(FRAME_LOCATION, FRAME_LOCATION, FRAME_SIZE, FRAME_SIZE);
+
+        final DraggablePanel dragSource = new DraggablePanel();
+        dragSource.setBackground(Color.yellow);
+        DropTarget dt = new DropTarget(dragSource, new DropTargetAdapter() {
+            @Override public void drop(DropTargetDropEvent dtde) {
+                // The first call always succeeds
+                dtde.acceptDrop(DnDConstants.ACTION_COPY);
+
+                // The second call should succeed if the fix works
+                dtde.acceptDrop(DnDConstants.ACTION_MOVE);
+
+                dtde.dropComplete(true);
+            }
+        });
+        dragSource.setDropTarget(dt);
+        f.add(dragSource);
+
+        f.setVisible(true);
+    }
+
+    public static void main(String[] args) throws Throwable {
+        try {
+
+            SwingUtilities.invokeAndWait(() -> initAndShowUI());
+
+            Robot r = new Robot();
+            Util.waitForIdle(r);
+            Util.drag(r,
+                    new Point(FRAME_LOCATION + FRAME_SIZE / 3, FRAME_LOCATION + FRAME_SIZE / 3),
+                    new Point(FRAME_LOCATION + FRAME_SIZE / 3 * 2, FRAME_LOCATION + FRAME_SIZE / 3 * 2),
+                    InputEvent.BUTTON1_MASK);
+            Util.waitForIdle(r);
+        } finally {
+            if (f != null) {
+                f.dispose();
+            }
+        }
+    }
+
+    private static class DraggablePanel extends Panel implements DragGestureListener {
+
+        public DraggablePanel() {
+            (new DragSource()).createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, this);
+        }
+
+        @Override
+        public void dragGestureRecognized(DragGestureEvent dge) {
+            dge.startDrag(Cursor.getDefaultCursor(), new StringSelection("test"));
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/dnd/BadSerializaionTest/BadSerializationTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8030050
+ * @summary Validate fields on DnD class deserialization
+ * @author petr.pchelko@oracle.com
+ */
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
+import java.util.stream.Stream;
+
+public class BadSerializationTest {
+
+    private static final String[] badSerialized = new String[] {
+            "badAction",
+            "noEvents",
+            "nullComponent",
+            "nullDragSource",
+            "nullOrigin"
+    };
+
+    private static final String goodSerialized = "good";
+
+    public static void main(String[] args) throws Exception {
+        String testSrc = System.getProperty("test.src") + File.separator;
+        testReadObject(testSrc + goodSerialized, false);
+        Stream.of(badSerialized).forEach(file -> testReadObject(testSrc + file, true));
+    }
+
+    private static void testReadObject(String filename, boolean expectException) {
+        Exception exceptionCaught = null;
+        try (FileInputStream fileInputStream = new FileInputStream(filename);
+             ObjectInputStream ois = new ObjectInputStream(fileInputStream)) {
+            ois.readObject();
+        } catch (InvalidObjectException e) {
+            exceptionCaught = e;
+        } catch (IOException e) {
+            throw new RuntimeException("FAILED: IOException", e);
+        } catch (ClassNotFoundException e) {
+            throw new RuntimeException("FAILED: ClassNotFoundException", e);
+        }
+        if (exceptionCaught != null && !expectException) {
+            throw new RuntimeException("FAILED: UnexpectedException", exceptionCaught);
+        }
+        if (exceptionCaught == null && expectException) {
+            throw new RuntimeException("FAILED: Invalid object was created with no exception");
+        }
+    }
+}
Binary file jdk/test/java/awt/dnd/BadSerializaionTest/badAction has changed
Binary file jdk/test/java/awt/dnd/BadSerializaionTest/good has changed
Binary file jdk/test/java/awt/dnd/BadSerializaionTest/noEvents has changed
Binary file jdk/test/java/awt/dnd/BadSerializaionTest/nullComponent has changed
Binary file jdk/test/java/awt/dnd/BadSerializaionTest/nullDragSource has changed
Binary file jdk/test/java/awt/dnd/BadSerializaionTest/nullOrigin has changed
--- a/jdk/test/java/awt/dnd/Button2DragTest/Button2DragTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/awt/dnd/Button2DragTest/Button2DragTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -112,6 +112,7 @@
         Util.drag(robot, startPoint, endPoint, InputEvent.BUTTON2_MASK);
 
         Util.waitForIdle(robot);
+        robot.delay(500);
 
         if (dropSuccess) {
             System.err.println("test passed");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/dnd/URIListToFileListBetweenJVMsTest/InterprocessMessages.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+
+public interface InterprocessMessages {
+    final static int EXECUTION_IS_SUCCESSFULL = 0;
+    final static int WRONG_FILES_NUMBER_ON_TARGET = 212;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/dnd/URIListToFileListBetweenJVMsTest/SourceFileListFrame.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,100 @@
+/*
+ * 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 test.java.awt.regtesthelpers.Util;
+
+import java.awt.*;
+import java.awt.dnd.DnDConstants;
+import java.awt.dnd.DragGestureEvent;
+import java.awt.dnd.DragGestureListener;
+import java.awt.dnd.DragSource;
+import java.io.File;
+import java.net.URI;
+import java.util.Arrays;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+
+class SourceFileListFrame extends Frame implements DragGestureListener {
+
+    private final static int SOURCE_POINT_SHIFT = 3;
+
+    private List list = new List(URIListToFileListBetweenJVMsTest.VISIBLE_RAWS_IN_LIST);
+    private File[] files;
+
+    SourceFileListFrame() {
+        super("Source File List Frame");
+        extractFilesFromTheWorkingDirectory();
+        initList();
+        initGUI();
+        new DragSource().createDefaultDragGestureRecognizer(list,
+                DnDConstants.ACTION_COPY,this);
+    }
+
+    private void extractFilesFromTheWorkingDirectory() {
+        files = new File(System.getProperty("java.home", "")).listFiles();
+    }
+
+    private void initList() {
+        for (File currFile:files) {
+            list.add(currFile.getName());
+        }
+    }
+
+    private void initGUI() {
+        this.addWindowListener(Util.getClosingWindowAdapter());
+        this.setLocation(300,250);
+        this.add(new Panel().add(list));
+        this.pack();
+        this.setVisible(true);
+    }
+
+    int getNextLocationX() {
+        return getX()+getWidth();
+    }
+
+    int getNextLocationY() {
+        return getY();
+    }
+
+    int getDragSourcePointX() {
+        return (int)list.getLocationOnScreen().getX()+(list.getWidth()/2);
+    }
+
+   int getDragSourcePointY() {
+        return (int)list.getLocationOnScreen().getY()+ SOURCE_POINT_SHIFT;
+    }
+
+    int getSourceFilesNumber() {
+        return files.length;
+    }
+
+    public void dragGestureRecognized(DragGestureEvent dge) {
+        java.util.List<URI> uriList = Stream.of(list.getItems())
+                                                .map(File::new)
+                                                .map(File::toURI)
+                                                .collect(Collectors.toList());
+
+        dge.startDrag(null, new URIListTransferable(uriList));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/dnd/URIListToFileListBetweenJVMsTest/TargetFileListFrame.java	Wed Jul 05 19:33:51 2017 +0200
@@ -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.
+ */
+
+import java.awt.*;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.awt.dnd.*;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.io.File;
+import java.io.IOException;
+
+class TargetFileListFrame extends Frame implements DropTargetListener {
+
+    private List list = new List(URIListToFileListBetweenJVMsTest.VISIBLE_RAWS_IN_LIST);
+    private int expectationTransferredFilesNumber;
+
+    TargetFileListFrame(Point location, int expectationTransferredFilesNumber) {
+        this.expectationTransferredFilesNumber = expectationTransferredFilesNumber;
+        initGUI(location);
+        setDropTarget(new DropTarget(list, DnDConstants.ACTION_COPY, this));
+    }
+
+    private void initGUI(Point location) {
+        this.setLocation(location);
+        this.addWindowListener(new WindowAdapter() {
+            public void windowClosing(WindowEvent e) {
+                TargetFileListFrame.this.dispose();
+            }
+        });
+        this.add(new Panel().add(list));
+        this.pack();
+        this.setVisible(true);
+    }
+
+    public void dragEnter(DropTargetDragEvent dtde) {
+        if (dtde.getCurrentDataFlavorsAsList().contains(DataFlavor.javaFileListFlavor)) {
+            dtde.acceptDrag(DnDConstants.ACTION_COPY);
+        }
+    }
+
+    public void dragOver(DropTargetDragEvent dtde) {
+        if (dtde.getCurrentDataFlavorsAsList().contains(DataFlavor.javaFileListFlavor)) {
+            dtde.acceptDrag(DnDConstants.ACTION_COPY);
+        }
+    }
+
+    public void dropActionChanged(DropTargetDragEvent dtde) {
+        if (dtde.getCurrentDataFlavorsAsList().contains(DataFlavor.javaFileListFlavor)) {
+            dtde.acceptDrag(DnDConstants.ACTION_COPY);
+        }
+    }
+
+    public void dragExit(DropTargetEvent dte) {}
+
+    public void drop(DropTargetDropEvent dtde) {
+        list.removeAll();
+        dtde.acceptDrop(DnDConstants.ACTION_COPY);
+        java.util.List<File> fileList = extractListOfFiles(dtde);
+        for (File file:fileList) {
+            list.add(file.getName());
+        }
+
+        if (fileList.size() != expectationTransferredFilesNumber)
+        {
+            System.err.println("ERROR: Expected file number:"
+                    + expectationTransferredFilesNumber
+                    + "; Received file number: "
+                    + fileList.size());
+            TargetFileListFrame.this.dispose();
+            System.exit(InterprocessMessages.WRONG_FILES_NUMBER_ON_TARGET);
+        }
+
+        TargetFileListFrame.this.dispose();
+
+    }
+
+    private java.util.List<File> extractListOfFiles(DropTargetDropEvent dtde) {
+        java.util.List<File> fileList = null;
+        try {
+            fileList = (java.util.List<File>)dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
+        } catch (UnsupportedFlavorException | IOException e) {
+            e.printStackTrace();
+        }
+        return fileList;
+    }
+
+    Point getDropTargetPoint() {
+       return new Point((int)list.getLocationOnScreen().getX()+(list.getWidth()/2),
+                        (int)list.getLocationOnScreen().getY()+(list.getHeight()/2));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/dnd/URIListToFileListBetweenJVMsTest/URIListToFileListBetweenJVMsTest.html	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,48 @@
+<!--
+ 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.
+-->
+
+<html>
+<!--  
+  @test
+  @bug 8029565
+  @summary Conversion of a URI list to File list fails
+  @author Petr Pchelko <petr.pchelko@oracle.com>
+  @library ../../regtesthelpers
+  @library ../../regtesthelpers/process
+  @build Util
+  @build ProcessResults ProcessCommunicator
+  @run applet/othervm URIListToFileListBetweenJVMsTest.html
+
+-->
+<head>
+<title> DnD of File-List across JVM </title>
+</head>
+<body>
+
+<h1>URIListToFileListBetweenJVMsTest<br>Bug ID: 5079469</h1>
+
+<p> This is an AUTOMATIC test, simply wait for completion </p>
+
+<APPLET CODE="URIListToFileListBetweenJVMsTest.class" WIDTH=200 HEIGHT=200></APPLET>
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/dnd/URIListToFileListBetweenJVMsTest/URIListToFileListBetweenJVMsTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,139 @@
+/*
+ * 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 8029565
+  @summary Conversion of a URI list to File list fails
+  @author Petr Pchelko <petr.pchelko@oracle.com>
+  @library ../../regtesthelpers
+  @library ../../regtesthelpers/process
+  @build Util
+  @build ProcessResults ProcessCommunicator
+  @run applet/othervm URIListToFileListBetweenJVMsTest.html
+ */
+
+/**
+ * URIListToFileListBetweenJVMsTest.java
+ *
+ * summary: DnD of File-List across JVM adds two empty items to the list
+ */
+
+import test.java.awt.regtesthelpers.Util;
+import test.java.awt.regtesthelpers.process.ProcessCommunicator;
+import test.java.awt.regtesthelpers.process.ProcessResults;
+
+import java.applet.Applet;
+import java.awt.*;
+import java.awt.event.InputEvent;
+
+import static java.lang.Thread.sleep;
+
+public class URIListToFileListBetweenJVMsTest extends Applet {
+
+    // information related to the test in common
+    static int VISIBLE_RAWS_IN_LIST=15;
+
+    public void init() {
+        setLayout(new BorderLayout());
+    }
+
+    public void start() {
+
+        SourceFileListFrame sourceFrame = new SourceFileListFrame();
+
+        Util.waitForIdle(null);
+
+        String [] args = new String [] {
+                String.valueOf(sourceFrame.getNextLocationX()),
+                String.valueOf(sourceFrame.getNextLocationY()),
+                String.valueOf(sourceFrame.getDragSourcePointX()),
+                String.valueOf(sourceFrame.getDragSourcePointY()),
+                String.valueOf(sourceFrame.getSourceFilesNumber())
+        };
+
+        ProcessResults processResults = ProcessCommunicator.executeChildProcess(this.getClass(), args);
+
+        verifyTestResults(processResults);
+
+    }
+
+    private static void verifyTestResults(ProcessResults processResults) {
+        if ( InterprocessMessages.WRONG_FILES_NUMBER_ON_TARGET == processResults.getExitValue()) {
+            processResults.printProcessErrorOutput(System.err);
+            throw new RuntimeException("TEST IS FAILED: Target has recieved wrong number of files.");
+        }
+        processResults.verifyStdErr(System.err);
+        processResults.verifyProcessExitValue(System.err);
+        processResults.printProcessStandartOutput(System.out);
+    }
+
+    //We cannot make an instance of the applet without the default constructor
+    public URIListToFileListBetweenJVMsTest() {
+        super();
+    }
+
+    //We need in this constructor to pass frame position between JVMs
+    public URIListToFileListBetweenJVMsTest(Point targetFrameLocation,
+                                            Point dragSourcePoint,
+                                            int transferredFilesNumber) throws InterruptedException
+    {
+        TargetFileListFrame targetFrame = new TargetFileListFrame(targetFrameLocation, transferredFilesNumber);
+
+        Util.waitForIdle(null);
+
+        final Robot robot = Util.createRobot();
+
+        robot.mouseMove((int)dragSourcePoint.getX(),(int)dragSourcePoint.getY());
+        sleep(100);
+        robot.mousePress(InputEvent.BUTTON1_MASK);
+        sleep(100);
+        robot.mouseRelease(InputEvent.BUTTON1_MASK);
+        sleep(100);
+
+        Util.drag(robot, dragSourcePoint, targetFrame.getDropTargetPoint(), InputEvent.BUTTON1_MASK);
+
+    }
+
+    enum InterprocessArguments {
+        TARGET_FRAME_X_POSITION_ARGUMENT,
+        TARGET_FRAME_Y_POSITION_ARGUMENT,
+        DRAG_SOURCE_POINT_X_ARGUMENT,
+        DRAG_SOURCE_POINT_Y_ARGUMENT,
+        FILES_IN_THE_LIST_NUMBER_ARGUMENT;
+
+        int extract (String [] args) {
+            return Integer.parseInt(args[this.ordinal()]);
+        }
+    }
+
+    public static void main (String [] args) throws Exception {
+        Point dragSourcePoint = new Point(InterprocessArguments.DRAG_SOURCE_POINT_X_ARGUMENT.extract(args),
+                InterprocessArguments.DRAG_SOURCE_POINT_Y_ARGUMENT.extract(args));
+        Point targetFrameLocation = new Point(InterprocessArguments.TARGET_FRAME_X_POSITION_ARGUMENT.extract(args),
+                InterprocessArguments.TARGET_FRAME_Y_POSITION_ARGUMENT.extract(args));
+        int transferredFilesNumber = InterprocessArguments.FILES_IN_THE_LIST_NUMBER_ARGUMENT.extract(args);
+
+        new URIListToFileListBetweenJVMsTest(targetFrameLocation, dragSourcePoint, transferredFilesNumber);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/dnd/URIListToFileListBetweenJVMsTest/URIListTransferable.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,64 @@
+/*
+ * 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.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.io.IOException;
+import java.net.URI;
+import java.util.List;
+
+class URIListTransferable implements Transferable {
+
+    private final DataFlavor supportedFlavor;
+
+    private List<URI> list;
+
+    public URIListTransferable(List<URI> list) {
+        try {
+            this.supportedFlavor = new DataFlavor("text/uri-list;class=java.lang.String");
+        } catch (ClassNotFoundException e) {
+            throw new RuntimeException("FAILED: could not create a DataFlavor");
+        }
+        this.list = list;
+    }
+
+    public DataFlavor[] getTransferDataFlavors() {
+        return new DataFlavor[] { supportedFlavor };
+    }
+
+    public boolean isDataFlavorSupported(DataFlavor flavor) {
+        return supportedFlavor.equals(flavor);
+    }
+
+    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
+        if (supportedFlavor.equals(flavor)) {
+            return list.stream()
+                    .map(URI::toASCIIString)
+                    .collect(StringBuilder::new,
+                             (builder, uri)-> { builder.append(uri).append("\r\n"); },
+                             StringBuilder::append).toString();
+        }
+        throw new UnsupportedFlavorException(flavor);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/dnd/URLDragTest/URLDragTest.html	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,45 @@
+<!--
+ Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ 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.
+-->
+
+<html>
+<!--  
+  @test
+  @bug 8031964
+  @summary Dragging images from the browser does not work
+  @author Petr Pchelko : area=dnd
+  @library ../../regtesthelpers
+  @build Sysout
+  @run applet/manual=yesno URLDragTest.html
+-->
+<head>
+<title> DnD of URL across JVM </title>
+</head>
+<body>
+
+<h1>URLDragTest<br>Bug ID: 8031964</h1>
+
+<p> This is an AUTOMATIC test, simply wait for completion </p>
+
+<APPLET CODE="URLDragTest.class" WIDTH=200 HEIGHT=200></APPLET>
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/dnd/URLDragTest/URLDragTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8031964
+  @summary Dragging images from the browser does not work
+  @author Petr Pchelko : area=dnd
+  @library ../../regtesthelpers
+  @build Sysout
+  @run applet/manual=yesno URLDragTest.html
+*/
+
+import test.java.awt.regtesthelpers.Sysout;
+
+import java.applet.Applet;
+import java.awt.*;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.dnd.DnDConstants;
+import java.awt.dnd.DropTarget;
+import java.awt.dnd.DropTargetAdapter;
+import java.awt.dnd.DropTargetDragEvent;
+import java.awt.dnd.DropTargetDropEvent;
+
+public class URLDragTest extends Applet {
+
+
+    @Override
+    public void init() {
+        setBackground(Color.red);
+        setDropTarget(new DropTarget(this,
+                DnDConstants.ACTION_COPY,
+                new DropTargetAdapter() {
+                    @Override
+                    public void dragEnter(DropTargetDragEvent dtde) {
+                        dtde.acceptDrag(DnDConstants.ACTION_COPY);
+                    }
+
+                    @Override
+                    public void dragOver(DropTargetDragEvent dtde) {
+                        dtde.acceptDrag(DnDConstants.ACTION_COPY);
+                    }
+
+                    @Override
+                    public void drop(DropTargetDropEvent dtde) {
+                        dtde.acceptDrop(DnDConstants.ACTION_COPY);
+                        dtde.getCurrentDataFlavorsAsList()
+                                .stream()
+                                .map(DataFlavor::toString)
+                                .forEach(Sysout::println);
+                    }
+                }));
+
+        String[] instructions = {
+                "1) Open the browser.",
+                "2) Drag any image from the browser page to the red square",
+                "3) When the image is dropped you should se the list of available DataFlavors",
+                "4) If you see application/x-java-url and text/uri-list flavors - test PASSED",
+                "5) Otherwise the test is FAILED"};
+        Sysout.createDialogWithInstructions(instructions);
+    }
+
+    @Override
+    public void start() {
+        setSize(200, 200);
+        setVisible(true);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/image/MultiResolutionImageTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,620 @@
+/*
+ * 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.awt.Color;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.Image;
+import java.awt.Toolkit;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.lang.reflect.Method;
+import java.net.URL;
+import javax.imageio.ImageIO;
+import sun.awt.OSInfo;
+import sun.awt.SunHints;
+import java.awt.MediaTracker;
+import java.awt.geom.AffineTransform;
+import java.awt.image.ImageObserver;
+import java.util.Arrays;
+import java.util.List;
+import javax.swing.JPanel;
+import sun.awt.SunToolkit;
+import sun.awt.image.MultiResolutionImage;
+
+/**
+ * @test
+ * @bug 8011059
+ * @author Alexander Scherbatiy
+ * @summary [macosx] Make JDK demos look perfect on retina displays
+ * @run main MultiResolutionImageTest CUSTOM
+ * @run main MultiResolutionImageTest TOOLKIT_PREPARE
+ * @run main MultiResolutionImageTest TOOLKIT_LOAD
+ * @run main MultiResolutionImageTest TOOLKIT
+ */
+public class MultiResolutionImageTest {
+
+    private static final int IMAGE_WIDTH = 300;
+    private static final int IMAGE_HEIGHT = 200;
+    private static final Color COLOR_1X = Color.GREEN;
+    private static final Color COLOR_2X = Color.BLUE;
+    private static final String IMAGE_NAME_1X = "image.png";
+    private static final String IMAGE_NAME_2X = "image@2x.png";
+
+    public static void main(String[] args) throws Exception {
+
+        System.out.println("args: " + args.length);
+
+        if (args.length == 0) {
+            throw new RuntimeException("Not found a test");
+        }
+
+        String test = args[0];
+
+        System.out.println("TEST: " + test);
+        System.out.println("CHECK OS: " + checkOS());
+
+        if ("CUSTOM".equals(test)) {
+            testCustomMultiResolutionImage();
+        } else if (checkOS()) {
+            switch (test) {
+                case "CUSTOM":
+                    break;
+                case "TOOLKIT_PREPARE":
+                    testToolkitMultiResolutionImagePrepare();
+                    break;
+                case "TOOLKIT_LOAD":
+                    testToolkitMultiResolutionImageLoad();
+                    break;
+                case "TOOLKIT":
+                    testToolkitMultiResolutionImage();
+                    testImageNameTo2xParsing();
+                    break;
+                default:
+                    throw new RuntimeException("Unknown test: " + test);
+            }
+        }
+    }
+
+    static boolean checkOS() {
+        return OSInfo.getOSType() == OSInfo.OSType.MACOSX;
+    }
+
+    public static void testCustomMultiResolutionImage() {
+        testCustomMultiResolutionImage(false);
+        testCustomMultiResolutionImage(true);
+    }
+
+    public static void testCustomMultiResolutionImage(boolean enableImageScaling) {
+
+        Image image = new MultiResolutionBufferedImage();
+
+        // Same image size
+        BufferedImage bufferedImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT,
+                BufferedImage.TYPE_INT_RGB);
+        Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
+        setImageScalingHint(g2d, enableImageScaling);
+        g2d.drawImage(image, 0, 0, null);
+        checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 4, 3 * IMAGE_HEIGHT / 4), false);
+
+        // Twice image size
+        bufferedImage = new BufferedImage(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT,
+                BufferedImage.TYPE_INT_RGB);
+        g2d = (Graphics2D) bufferedImage.getGraphics();
+        setImageScalingHint(g2d, enableImageScaling);
+        g2d.drawImage(image, 0, 0, 2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, null);
+        checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 2, 3 * IMAGE_HEIGHT / 2), enableImageScaling);
+
+        // Scale 2x
+        bufferedImage = new BufferedImage(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
+        g2d = (Graphics2D) bufferedImage.getGraphics();
+        setImageScalingHint(g2d, enableImageScaling);
+        g2d.scale(2, 2);
+        g2d.drawImage(image, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, null);
+        checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 2, 3 * IMAGE_HEIGHT / 2), enableImageScaling);
+
+        // Rotate
+        bufferedImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT,
+                BufferedImage.TYPE_INT_RGB);
+        g2d = (Graphics2D) bufferedImage.getGraphics();
+        setImageScalingHint(g2d, enableImageScaling);
+        g2d.drawImage(image, 0, 0, null);
+        g2d.rotate(Math.PI / 4);
+        checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 4, 3 * IMAGE_HEIGHT / 4), false);
+
+        // Scale 2x and Rotate
+        bufferedImage = new BufferedImage(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
+        g2d = (Graphics2D) bufferedImage.getGraphics();
+        setImageScalingHint(g2d, enableImageScaling);
+        g2d.scale(-2, 2);
+        g2d.rotate(-Math.PI / 10);
+        g2d.drawImage(image, -IMAGE_WIDTH, 0, IMAGE_WIDTH, IMAGE_HEIGHT, null);
+        checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 2, 3 * IMAGE_HEIGHT / 2), enableImageScaling);
+
+        // General Transform
+        bufferedImage = new BufferedImage(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
+        g2d = (Graphics2D) bufferedImage.getGraphics();
+        setImageScalingHint(g2d, enableImageScaling);
+        float delta = 0.05f;
+        float cos = 1 - delta * delta / 2;
+        float sin = 1 + delta;
+        AffineTransform transform = new AffineTransform(2 * cos, 0.1, 0.3, -2 * sin, 10, -5);
+        g2d.setTransform(transform);
+        g2d.drawImage(image, 0, -IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_HEIGHT, null);
+        checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 2, 3 * IMAGE_HEIGHT / 2), enableImageScaling);
+
+        int D = 10;
+        // From Source to small Destination region
+        bufferedImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
+        g2d = (Graphics2D) bufferedImage.getGraphics();
+        setImageScalingHint(g2d, enableImageScaling);
+        g2d.drawImage(image, IMAGE_WIDTH / 2, IMAGE_HEIGHT / 2, IMAGE_WIDTH - D, IMAGE_HEIGHT - D,
+                D, D, IMAGE_WIDTH - D, IMAGE_HEIGHT - D, null);
+        checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 4, 3 * IMAGE_HEIGHT / 4), false);
+
+        // From Source to large Destination region
+        bufferedImage = new BufferedImage(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
+        g2d = (Graphics2D) bufferedImage.getGraphics();
+        setImageScalingHint(g2d, enableImageScaling);
+        g2d.drawImage(image, D, D, 2 * IMAGE_WIDTH - D, 2 * IMAGE_HEIGHT - D,
+                IMAGE_WIDTH / 2, IMAGE_HEIGHT / 2, IMAGE_WIDTH - D, IMAGE_HEIGHT - D, null);
+        checkColor(bufferedImage.getRGB(3 * IMAGE_WIDTH / 2, 3 * IMAGE_HEIGHT / 2), enableImageScaling);
+    }
+
+    static class MultiResolutionBufferedImage extends BufferedImage
+            implements MultiResolutionImage {
+
+        Image highResolutionImage;
+
+        public MultiResolutionBufferedImage() {
+            super(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
+            highResolutionImage = new BufferedImage(
+                    2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
+            draw(getGraphics(), 1);
+            draw(highResolutionImage.getGraphics(), 2);
+        }
+
+        void draw(Graphics graphics, float resolution) {
+            Graphics2D g2 = (Graphics2D) graphics;
+            g2.scale(resolution, resolution);
+            g2.setColor((resolution == 1) ? COLOR_1X : COLOR_2X);
+            g2.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
+        }
+
+        @Override
+        public Image getResolutionVariant(int width, int height) {
+            return ((width <= getWidth() && height <= getHeight()))
+                    ? this : highResolutionImage;
+        }
+
+        @Override
+        public List<Image> getResolutionVariants() {
+            return Arrays.asList(this, highResolutionImage);
+        }
+    }
+
+    static void testToolkitMultiResolutionImagePrepare() throws Exception {
+
+        generateImages();
+
+        File imageFile = new File(IMAGE_NAME_1X);
+        String fileName = imageFile.getAbsolutePath();
+
+        Image image = Toolkit.getDefaultToolkit().getImage(fileName);
+
+        SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
+        toolkit.prepareImage(image, IMAGE_WIDTH, IMAGE_HEIGHT, new LoadImageObserver(image));
+
+        testToolkitMultiResolutionImageLoad(image);
+    }
+
+    static void testToolkitMultiResolutionImageLoad() throws Exception {
+
+        generateImages();
+
+        File imageFile = new File(IMAGE_NAME_1X);
+        String fileName = imageFile.getAbsolutePath();
+        Image image = Toolkit.getDefaultToolkit().getImage(fileName);
+        testToolkitMultiResolutionImageLoad(image);
+    }
+
+    static void testToolkitMultiResolutionImageLoad(Image image) throws Exception {
+
+        MediaTracker tracker = new MediaTracker(new JPanel());
+        tracker.addImage(image, 0);
+        tracker.waitForID(0);
+        if (tracker.isErrorAny()) {
+            throw new RuntimeException("Error during image loading");
+        }
+        tracker.removeImage(image, 0);
+
+        testImageLoaded(image);
+
+        int w = image.getWidth(null);
+        int h = image.getHeight(null);
+
+        Image resolutionVariant = ((MultiResolutionImage) image)
+                .getResolutionVariant(2 * w, 2 * h);
+
+        if (image == resolutionVariant) {
+            throw new RuntimeException("Resolution variant is not loaded");
+        }
+
+        testImageLoaded(resolutionVariant);
+    }
+
+    static void testImageLoaded(Image image) {
+
+        SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
+
+        int flags = toolkit.checkImage(image, IMAGE_WIDTH, IMAGE_WIDTH, new SilentImageObserver());
+        if ((flags & (ImageObserver.FRAMEBITS | ImageObserver.ALLBITS)) == 0) {
+            throw new RuntimeException("Image is not loaded!");
+        }
+    }
+
+    static class SilentImageObserver implements ImageObserver {
+
+        @Override
+        public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
+            throw new RuntimeException("Observer should not be called!");
+        }
+    }
+
+    static class LoadImageObserver implements ImageObserver {
+
+        Image image;
+
+        public LoadImageObserver(Image image) {
+            this.image = image;
+        }
+
+        @Override
+        public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
+
+            if (image != img) {
+                throw new RuntimeException("Original image is not passed to the observer");
+            }
+
+            if ((infoflags & ImageObserver.WIDTH) != 0) {
+                if (width != IMAGE_WIDTH) {
+                    throw new RuntimeException("Original width is not passed to the observer");
+                }
+            }
+
+            if ((infoflags & ImageObserver.HEIGHT) != 0) {
+                if (height != IMAGE_HEIGHT) {
+                    throw new RuntimeException("Original height is not passed to the observer");
+                }
+            }
+
+            return (infoflags & ALLBITS) == 0;
+        }
+
+    }
+
+    static void testToolkitMultiResolutionImage() throws Exception {
+
+        generateImages();
+
+        File imageFile = new File(IMAGE_NAME_1X);
+        String fileName = imageFile.getAbsolutePath();
+        URL url = imageFile.toURI().toURL();
+        testToolkitMultiResolutionImageChache(fileName, url);
+
+        Image image = Toolkit.getDefaultToolkit().getImage(fileName);
+        testToolkitImageObserver(image);
+        testToolkitMultiResolutionImage(image, false);
+        testToolkitMultiResolutionImage(image, true);
+
+        image = Toolkit.getDefaultToolkit().getImage(url);
+        testToolkitImageObserver(image);
+        testToolkitMultiResolutionImage(image, false);
+        testToolkitMultiResolutionImage(image, true);
+    }
+
+    static void testToolkitMultiResolutionImageChache(String fileName, URL url) {
+
+        Image img1 = Toolkit.getDefaultToolkit().getImage(fileName);
+        if (!(img1 instanceof MultiResolutionImage)) {
+            throw new RuntimeException("Not a MultiResolutionImage");
+        }
+
+        Image img2 = Toolkit.getDefaultToolkit().getImage(fileName);
+        if (img1 != img2) {
+            throw new RuntimeException("Image is not cached");
+        }
+
+        img1 = Toolkit.getDefaultToolkit().getImage(url);
+        if (!(img1 instanceof MultiResolutionImage)) {
+            throw new RuntimeException("Not a MultiResolutionImage");
+        }
+
+        img2 = Toolkit.getDefaultToolkit().getImage(url);
+        if (img1 != img2) {
+            throw new RuntimeException("Image is not cached");
+        }
+    }
+
+    static void testToolkitMultiResolutionImage(Image image, boolean enableImageScaling)
+            throws Exception {
+
+        MediaTracker tracker = new MediaTracker(new JPanel());
+        tracker.addImage(image, 0);
+        tracker.waitForID(0);
+        if (tracker.isErrorAny()) {
+            throw new RuntimeException("Error during image loading");
+        }
+
+        final BufferedImage bufferedImage1x = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT,
+                BufferedImage.TYPE_INT_RGB);
+        Graphics2D g1x = (Graphics2D) bufferedImage1x.getGraphics();
+        setImageScalingHint(g1x, false);
+        g1x.drawImage(image, 0, 0, null);
+        checkColor(bufferedImage1x.getRGB(3 * IMAGE_WIDTH / 4, 3 * IMAGE_HEIGHT / 4), false);
+
+        Image resolutionVariant = ((MultiResolutionImage) image).
+                getResolutionVariant(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT);
+
+        if (resolutionVariant == null) {
+            throw new RuntimeException("Resolution variant is null");
+        }
+
+        MediaTracker tracker2x = new MediaTracker(new JPanel());
+        tracker2x.addImage(resolutionVariant, 0);
+        tracker2x.waitForID(0);
+        if (tracker2x.isErrorAny()) {
+            throw new RuntimeException("Error during scalable image loading");
+        }
+
+        final BufferedImage bufferedImage2x = new BufferedImage(2 * IMAGE_WIDTH,
+                2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
+        Graphics2D g2x = (Graphics2D) bufferedImage2x.getGraphics();
+        setImageScalingHint(g2x, enableImageScaling);
+        g2x.drawImage(image, 0, 0, 2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, null);
+        checkColor(bufferedImage2x.getRGB(3 * IMAGE_WIDTH / 2, 3 * IMAGE_HEIGHT / 2), enableImageScaling);
+
+        if (!(image instanceof MultiResolutionImage)) {
+            throw new RuntimeException("Not a MultiResolutionImage");
+        }
+
+        MultiResolutionImage multiResolutionImage = (MultiResolutionImage) image;
+
+        Image image1x = multiResolutionImage.getResolutionVariant(IMAGE_WIDTH, IMAGE_HEIGHT);
+        Image image2x = multiResolutionImage.getResolutionVariant(2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT);
+
+        if (image1x.getWidth(null) * 2 != image2x.getWidth(null)
+                || image1x.getHeight(null) * 2 != image2x.getHeight(null)) {
+            throw new RuntimeException("Wrong resolution variant size");
+        }
+    }
+
+    static void testToolkitImageObserver(final Image image) {
+
+        ImageObserver observer = new ImageObserver() {
+
+            @Override
+            public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
+
+                if (img != image) {
+                    throw new RuntimeException("Wrong image in observer");
+                }
+
+                if ((infoflags & (ImageObserver.ERROR | ImageObserver.ABORT)) != 0) {
+                    throw new RuntimeException("Error during image loading");
+                }
+
+                return (infoflags & ImageObserver.ALLBITS) == 0;
+
+            }
+        };
+
+        final BufferedImage bufferedImage2x = new BufferedImage(2 * IMAGE_WIDTH,
+                2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
+        Graphics2D g2x = (Graphics2D) bufferedImage2x.getGraphics();
+        setImageScalingHint(g2x, true);
+
+        g2x.drawImage(image, 0, 0, 2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, observer);
+
+    }
+
+    static void setImageScalingHint(Graphics2D g2d, boolean enableImageScaling) {
+        g2d.setRenderingHint(SunHints.KEY_RESOLUTION_VARIANT, enableImageScaling
+                ? SunHints.VALUE_RESOLUTION_VARIANT_ON
+                : SunHints.VALUE_RESOLUTION_VARIANT_OFF);
+    }
+
+    static void checkColor(int rgb, boolean isImageScaled) {
+
+        if (!isImageScaled && COLOR_1X.getRGB() != rgb) {
+            throw new RuntimeException("Wrong 1x color: " + new Color(rgb));
+        }
+
+        if (isImageScaled && COLOR_2X.getRGB() != rgb) {
+            throw new RuntimeException("Wrong 2x color" + new Color(rgb));
+        }
+    }
+
+    static void generateImages() throws Exception {
+        if (!new File(IMAGE_NAME_1X).exists()) {
+            generateImage(1);
+        }
+
+        if (!new File(IMAGE_NAME_2X).exists()) {
+            generateImage(2);
+        }
+    }
+
+    static void generateImage(int scale) throws Exception {
+        BufferedImage image = new BufferedImage(scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT,
+                BufferedImage.TYPE_INT_RGB);
+        Graphics g = image.getGraphics();
+        g.setColor(scale == 1 ? COLOR_1X : COLOR_2X);
+        g.fillRect(0, 0, scale * IMAGE_WIDTH, scale * IMAGE_HEIGHT);
+        File file = new File(scale == 1 ? IMAGE_NAME_1X : IMAGE_NAME_2X);
+        ImageIO.write(image, "png", file);
+    }
+
+    static void testImageNameTo2xParsing() throws Exception {
+
+        for (String[] testNames : TEST_FILE_NAMES) {
+            String testName = testNames[0];
+            String goldenName = testNames[1];
+            String resultName = getTestScaledImageName(testName);
+
+            if (!isValidPath(testName) && resultName == null) {
+                continue;
+            }
+
+            if (goldenName.equals(resultName)) {
+                continue;
+            }
+
+            throw new RuntimeException("Test name " + testName
+                    + ", result name: " + resultName);
+        }
+
+        for (URL[] testURLs : TEST_URLS) {
+            URL testURL = testURLs[0];
+            URL goldenURL = testURLs[1];
+            URL resultURL = getTestScaledImageURL(testURL);
+
+            if (!isValidPath(testURL.getPath()) && resultURL == null) {
+                continue;
+            }
+
+            if (goldenURL.equals(resultURL)) {
+                continue;
+            }
+
+            throw new RuntimeException("Test url: " + testURL
+                    + ", result url: " + resultURL);
+        }
+
+    }
+
+    static URL getTestScaledImageURL(URL url) throws Exception {
+        Method method = getScalableImageMethod("getScaledImageURL", URL.class);
+        return (URL) method.invoke(null, url);
+    }
+
+    static String getTestScaledImageName(String name) throws Exception {
+        Method method = getScalableImageMethod("getScaledImageName", String.class);
+        return (String) method.invoke(null, name);
+    }
+
+    private static boolean isValidPath(String path) {
+        return !path.isEmpty() && !path.endsWith("/") && !path.endsWith(".")
+                && !path.contains("@2x");
+    }
+
+    private static Method getScalableImageMethod(String name,
+            Class... parameterTypes) throws Exception {
+        Toolkit toolkit = Toolkit.getDefaultToolkit();
+        Method method = toolkit.getClass().getDeclaredMethod(name, parameterTypes);
+        method.setAccessible(true);
+        return method;
+    }
+    private static final String[][] TEST_FILE_NAMES;
+    private static final URL[][] TEST_URLS;
+
+    static {
+        TEST_FILE_NAMES = new String[][]{
+            {"", null},
+            {".", null},
+            {"..", null},
+            {"/", null},
+            {"/.", null},
+            {"dir/", null},
+            {"dir/.", null},
+            {"aaa@2x.png", null},
+            {"/dir/aaa@2x.png", null},
+            {"image", "image@2x"},
+            {"image.ext", "image@2x.ext"},
+            {"image.aaa.ext", "image.aaa@2x.ext"},
+            {"dir/image", "dir/image@2x"},
+            {"dir/image.ext", "dir/image@2x.ext"},
+            {"dir/image.aaa.ext", "dir/image.aaa@2x.ext"},
+            {"dir/aaa.bbb/image", "dir/aaa.bbb/image@2x"},
+            {"dir/aaa.bbb/image.ext", "dir/aaa.bbb/image@2x.ext"},
+            {"dir/aaa.bbb/image.ccc.ext", "dir/aaa.bbb/image.ccc@2x.ext"},
+            {"/dir/image", "/dir/image@2x"},
+            {"/dir/image.ext", "/dir/image@2x.ext"},
+            {"/dir/image.aaa.ext", "/dir/image.aaa@2x.ext"},
+            {"/dir/aaa.bbb/image", "/dir/aaa.bbb/image@2x"},
+            {"/dir/aaa.bbb/image.ext", "/dir/aaa.bbb/image@2x.ext"},
+            {"/dir/aaa.bbb/image.ccc.ext", "/dir/aaa.bbb/image.ccc@2x.ext"}
+        };
+        try {
+            TEST_URLS = new URL[][]{
+                // file
+                {new URL("file:/aaa"), new URL("file:/aaa@2x")},
+                {new URL("file:/aaa.ext"), new URL("file:/aaa@2x.ext")},
+                {new URL("file:/aaa.bbb.ext"), new URL("file:/aaa.bbb@2x.ext")},
+                {new URL("file:/ccc/aaa.bbb.ext"),
+                    new URL("file:/ccc/aaa.bbb@2x.ext")},
+                {new URL("file:/ccc.ddd/aaa.bbb.ext"),
+                    new URL("file:/ccc.ddd/aaa.bbb@2x.ext")},
+                {new URL("file:///~/image"), new URL("file:///~/image@2x")},
+                {new URL("file:///~/image.ext"),
+                    new URL("file:///~/image@2x.ext")},
+                // http
+                {new URL("http://www.test.com"), null},
+                {new URL("http://www.test.com/"), null},
+                {new URL("http://www.test.com///"), null},
+                {new URL("http://www.test.com/image"),
+                    new URL("http://www.test.com/image@2x")},
+                {new URL("http://www.test.com/image.ext"),
+                    new URL("http://www.test.com/image@2x.ext")},
+                {new URL("http://www.test.com/dir/image"),
+                    new URL("http://www.test.com/dir/image@2x")},
+                {new URL("http://www.test.com:80/dir/image.aaa.ext"),
+                    new URL("http://www.test.com:80/dir/image.aaa@2x.ext")},
+                {new URL("http://www.test.com:8080/dir/image.aaa.ext"),
+                    new URL("http://www.test.com:8080/dir/image.aaa@2x.ext")},
+                // jar
+                {new URL("jar:file:/dir/Java2D.jar!/image"),
+                    new URL("jar:file:/dir/Java2D.jar!/image@2x")},
+                {new URL("jar:file:/dir/Java2D.jar!/image.aaa.ext"),
+                    new URL("jar:file:/dir/Java2D.jar!/image.aaa@2x.ext")},
+                {new URL("jar:file:/dir/Java2D.jar!/images/image"),
+                    new URL("jar:file:/dir/Java2D.jar!/images/image@2x")},
+                {new URL("jar:file:/dir/Java2D.jar!/images/image.ext"),
+                    new URL("jar:file:/dir/Java2D.jar!/images/image@2x.ext")},
+                {new URL("jar:file:/aaa.bbb/Java2D.jar!/images/image.ext"),
+                    new URL("jar:file:/aaa.bbb/Java2D.jar!/images/image@2x.ext")},
+                {new URL("jar:file:/dir/Java2D.jar!/aaa.bbb/image.ext"),
+                    new URL("jar:file:/dir/Java2D.jar!/aaa.bbb/image@2x.ext")},};
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    static class PreloadedImageObserver implements ImageObserver {
+
+        @Override
+        public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
+            throw new RuntimeException("Image should be already preloaded");
+        }
+    }
+}
--- a/jdk/test/java/awt/regtesthelpers/Util.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/awt/regtesthelpers/Util.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,6 +51,7 @@
 import java.awt.IllegalComponentStateException;
 import java.awt.AWTException;
 import java.awt.AWTEvent;
+import java.awt.Color;
 
 import java.awt.event.InputEvent;
 import java.awt.event.WindowAdapter;
@@ -184,6 +185,57 @@
         }
     }
 
+    /**
+     * Tests whether screen pixel has the expected color performing several
+     * attempts. This method is useful for asynchronous window manager where
+     * it's impossible to determine when drawing actually takes place.
+     *
+     * @param x X position of pixel
+     * @param y Y position of pixel
+     * @param color expected color
+     * @param attempts number of attempts to undertake
+     * @param delay delay before each attempt
+     * @param robot a robot to use for retrieving pixel color
+     * @return true if pixel color matches the color expected, otherwise false
+     */
+    public static boolean testPixelColor(int x, int y, final Color color, int attempts, int delay, final Robot robot) {
+        while (attempts-- > 0) {
+            robot.delay(delay);
+            Color screen = robot.getPixelColor(x, y);
+            if (screen.equals(color)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Tests whether the area within boundaries has the expected color
+     * performing several attempts. This method is useful for asynchronous
+     * window manager where it's impossible to determine when drawing actually
+     * takes place.
+     *
+     * @param bounds position of area
+     * @param color expected color
+     * @param attempts number of attempts to undertake
+     * @param delay delay before each attempt
+     * @param robot a robot to use for retrieving pixel color
+     * @return true if area color matches the color expected, otherwise false
+     */
+    public static boolean testBoundsColor(final Rectangle bounds, final Color color, int attempts, int delay, final Robot robot) {
+        int right = bounds.x + bounds.width - 1;
+        int bottom = bounds.y + bounds.height - 1;
+        while (attempts-- > 0) {
+            if (testPixelColor(bounds.x, bounds.y, color, 1, delay, robot)
+                && testPixelColor(right, bounds.y, color, 1, 0, robot)
+                && testPixelColor(right, bottom, color, 1, 0, robot)
+                && testPixelColor(bounds.x, bottom, color, 1, 0, robot)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     public static void waitForIdle(final Robot robot) {
         // we do not use robot for now, use SunToolkit.realSync() instead
         ((sun.awt.SunToolkit)Toolkit.getDefaultToolkit()).realSync();
--- a/jdk/test/java/beans/Introspector/Test4168833.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/beans/Introspector/Test4168833.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,10 +23,11 @@
 
 /*
  * @test
- * @bug 4168833
+ * @bug 4168833 8034085
  * @summary Tests that Introspector does not create IndexedPropertyDescriptor
  *          from non-indexed PropertyDescriptor
  * @author Mark Davidson
+ * @author Sergey Malenkov
  */
 
 import java.awt.Color;
@@ -42,10 +43,6 @@
  */
 public class Test4168833 {
     public static void main(String[] args) throws Exception {
-        IndexedPropertyDescriptor ipd = BeanUtils.getIndexedPropertyDescriptor(Base.class, "prop");
-        if (!ipd.getIndexedPropertyType().equals(Dimension.class)) {
-            error(ipd, "Base.prop property should a Dimension");
-        }
         // When the Sub class is introspected,
         // the property type should be color.
         // The complete "classic" set of properties
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/beans/Introspector/Test8034085.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,236 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.awt.Window;
+import java.beans.IndexedPropertyDescriptor;
+import java.beans.PropertyDescriptor;
+
+/*
+ * @test
+ * @bug 8034085
+ * @summary Tests that Introspector ignores indexed getter and setter for incorrect types
+ * @author Sergey Malenkov
+ */
+
+public class Test8034085 {
+    public static final StringBuilder ERROR = new StringBuilder();
+
+    public static void main(String[] args) {
+        test(Window.class, false, true, false, false);
+
+        test(Bean0000.class, false, false, false, false);
+        test(Bean0001.class, false, false, false, true);
+        test(Bean0010.class, false, false, true, false);
+        test(Bean0011.class, false, false, true, true);
+        test(Bean0100.class, false, true, false, false);
+        test(Bean0101.class, false, true, false, false);
+        test(Bean0110.class, false, true, false, false);
+        test(Bean0111.class, false, true, false, false);
+        test(Bean1000.class, true, false, false, false);
+        test(Bean1001.class, true, false, false, false);
+        test(Bean1010.class, true, false, false, false);
+        test(Bean1011.class, true, false, false, false);
+        test(Bean1100.class, true, true, false, false);
+        test(Bean1101.class, true, true, false, false);
+        test(Bean1110.class, true, true, false, false);
+        test(Bean1111.class, true, true, false, false);
+
+        if (0 < ERROR.length()) {
+            throw new Error(ERROR.toString());
+        }
+    }
+
+    private static void test(Class<?> type, boolean read, boolean write, boolean readIndexed, boolean writeIndexed) {
+        PropertyDescriptor pd = BeanUtils.findPropertyDescriptor(type, "size");
+        if (pd != null) {
+            test(type, "read", read, null != pd.getReadMethod());
+            test(type, "write", write, null != pd.getWriteMethod());
+            if (pd instanceof IndexedPropertyDescriptor) {
+                IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
+                test(type, "indexed read", readIndexed, null != ipd.getIndexedReadMethod());
+                test(type, "indexed write", writeIndexed, null != ipd.getIndexedWriteMethod());
+            } else if (readIndexed || writeIndexed) {
+                error(type, "indexed property does not exist");
+            }
+        } else if (read || write || readIndexed || writeIndexed) {
+            error(type, "property does not exist");
+        }
+    }
+
+    private static void test(Class<?> type, String name, boolean expected, boolean actual) {
+        if (expected && !actual) {
+            error(type, name + " method does not exist");
+        } else if (!expected && actual) {
+            error(type, name + " method is not expected");
+        }
+    }
+
+    private static void error(Class<?> type, String message) {
+        ERROR.append("\n\t\t").append(type.getSimpleName()).append(".size: ").append(message);
+    }
+
+    public static class Bean0000 {
+    }
+
+    public static class Bean0001 {
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean0010 {
+        public int getSize(int index) {
+            return 0;
+        }
+    }
+
+    public static class Bean0011 {
+        public int getSize(int index) {
+            return 0;
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean0100 {
+        public void setSize(int value) {
+        }
+    }
+
+    public static class Bean0101 {
+        public void setSize(int value) {
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean0110 {
+        public void setSize(int value) {
+        }
+
+        public int getSize(int index) {
+            return 0;
+        }
+    }
+
+    public static class Bean0111 {
+        public void setSize(int value) {
+        }
+
+        public int getSize(int index) {
+            return 0;
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean1000 {
+        public int getSize() {
+            return 0;
+        }
+    }
+
+    public static class Bean1001 {
+        public int getSize() {
+            return 0;
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean1010 {
+        public int getSize() {
+            return 0;
+        }
+
+        public int getSize(int index) {
+            return 0;
+        }
+    }
+
+    public static class Bean1011 {
+        public int getSize() {
+            return 0;
+        }
+
+        public int getSize(int index) {
+            return 0;
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean1100 {
+        public int getSize() {
+            return 0;
+        }
+
+        public void setSize(int value) {
+        }
+    }
+
+    public static class Bean1101 {
+        public int getSize() {
+            return 0;
+        }
+
+        public void setSize(int value) {
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean1110 {
+        public int getSize() {
+            return 0;
+        }
+
+        public void setSize(int value) {
+        }
+
+        public int getSize(int index) {
+            return 0;
+        }
+    }
+
+    public static class Bean1111 {
+        public int getSize() {
+            return 0;
+        }
+
+        public void setSize(int value) {
+        }
+
+        public int getSize(int index) {
+            return 0;
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/beans/Introspector/Test8034164.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.beans.IndexedPropertyDescriptor;
+import java.beans.PropertyDescriptor;
+
+/*
+ * @test
+ * @bug 8034164
+ * @summary Tests that Introspector does not ignore indexed getter and setter for correct types
+ * @author Sergey Malenkov
+ */
+
+public class Test8034164 {
+    public static final StringBuilder ERROR = new StringBuilder();
+
+    public static void main(String[] args) {
+        test(Bean0000.class, false, false, false, false);
+        test(Bean0001.class, false, false, false, true);
+        test(Bean0010.class, false, false, true, false);
+        test(Bean0011.class, false, false, true, true);
+        test(Bean0100.class, false, true, false, false);
+        test(Bean0101.class, false, true, false, true);
+        test(Bean0110.class, false, true, true, false);
+        test(Bean0111.class, false, true, true, true);
+        test(Bean1000.class, true, false, false, false);
+        test(Bean1001.class, true, false, false, true);
+        test(Bean1010.class, true, false, true, false);
+        test(Bean1011.class, true, false, true, true);
+        test(Bean1100.class, true, true, false, false);
+        test(Bean1101.class, true, true, false, true);
+        test(Bean1110.class, true, true, true, false);
+        test(Bean1111.class, true, true, true, true);
+
+        if (0 < ERROR.length()) {
+            throw new Error(ERROR.toString());
+        }
+    }
+
+    private static void test(Class<?> type, boolean read, boolean write, boolean readIndexed, boolean writeIndexed) {
+        PropertyDescriptor pd = BeanUtils.findPropertyDescriptor(type, "size");
+        if (pd != null) {
+            test(type, "read", read, null != pd.getReadMethod());
+            test(type, "write", write, null != pd.getWriteMethod());
+            if (pd instanceof IndexedPropertyDescriptor) {
+                IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
+                test(type, "indexed read", readIndexed, null != ipd.getIndexedReadMethod());
+                test(type, "indexed write", writeIndexed, null != ipd.getIndexedWriteMethod());
+            } else if (readIndexed || writeIndexed) {
+                error(type, "indexed property does not exist");
+            }
+        } else if (read || write || readIndexed || writeIndexed) {
+            error(type, "property does not exist");
+        }
+    }
+
+    private static void test(Class<?> type, String name, boolean expected, boolean actual) {
+        if (expected && !actual) {
+            error(type, name + " method does not exist");
+        } else if (!expected && actual) {
+            error(type, name + " method is not expected");
+        }
+    }
+
+    private static void error(Class<?> type, String message) {
+        ERROR.append("\n\t\t").append(type.getSimpleName()).append(".size: ").append(message);
+    }
+
+    public static class Bean0000 {
+    }
+
+    public static class Bean0001 {
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean0010 {
+        public int getSize(int index) {
+            return 0;
+        }
+    }
+
+    public static class Bean0011 {
+        public int getSize(int index) {
+            return 0;
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean0100 {
+        public void setSize(int[] value) {
+        }
+    }
+
+    public static class Bean0101 {
+        public void setSize(int[] value) {
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean0110 {
+        public void setSize(int[] value) {
+        }
+
+        public int getSize(int index) {
+            return 0;
+        }
+    }
+
+    public static class Bean0111 {
+        public void setSize(int[] value) {
+        }
+
+        public int getSize(int index) {
+            return 0;
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean1000 {
+        public int[] getSize() {
+            return null;
+        }
+    }
+
+    public static class Bean1001 {
+        public int[] getSize() {
+            return null;
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean1010 {
+        public int[] getSize() {
+            return null;
+        }
+
+        public int getSize(int index) {
+            return 0;
+        }
+    }
+
+    public static class Bean1011 {
+        public int[] getSize() {
+            return null;
+        }
+
+        public int getSize(int index) {
+            return 0;
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean1100 {
+        public int[] getSize() {
+            return null;
+        }
+
+        public void setSize(int[] value) {
+        }
+    }
+
+    public static class Bean1101 {
+        public int[] getSize() {
+            return null;
+        }
+
+        public void setSize(int[] value) {
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+
+    public static class Bean1110 {
+        public int[] getSize() {
+            return null;
+        }
+
+        public void setSize(int[] value) {
+        }
+
+        public int getSize(int index) {
+            return 0;
+        }
+    }
+
+    public static class Bean1111 {
+        public int[] getSize() {
+            return null;
+        }
+
+        public void setSize(int[] value) {
+        }
+
+        public int getSize(int index) {
+            return 0;
+        }
+
+        public void setSize(int index, int value) {
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/io/SequenceInputStream/LotsOfStreams.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 7011804
+ * @summary SequenceInputStream#read() was implemented recursivly,
+ *          which may cause stack overflow
+ */
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.SequenceInputStream;
+import java.util.Enumeration;
+
+public class LotsOfStreams {
+
+    static final int MAX_SUBSTREAMS = 32000;
+
+    public static void main(String[] argv) throws Exception {
+        try (InputStream stream =
+                new SequenceInputStream(new LOSEnumeration())) {
+            stream.read();
+        }
+        try (InputStream stream =
+                new SequenceInputStream(new LOSEnumeration())) {
+            byte[] b = new byte[1];
+            stream.read(b, 0, 1);
+        }
+    }
+
+    static class LOSEnumeration
+            implements Enumeration<InputStream> {
+
+        private static InputStream inputStream =
+                new ByteArrayInputStream(new byte[0]);
+        private int left = MAX_SUBSTREAMS;
+
+        public boolean hasMoreElements() {
+            return (left > 0);
+        }
+        public InputStream nextElement() {
+            left--;
+            return inputStream;
+        }
+    }
+}
--- a/jdk/test/java/lang/ClassLoader/Assert.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/lang/ClassLoader/Assert.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,8 @@
 /*
  * @test
  * @bug 4290640 4785473
- * @run shell/timeout=300 Assert.sh
+ * @build package1.Class1 package2.Class2 package1.package3.Class3 Assert
+ * @run main/othervm Assert
  * @summary Test the assertion facility
  * @author Mike McCloskey
  */
--- a/jdk/test/java/lang/ClassLoader/Assert.sh	Tue Mar 25 12:31:49 2014 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,83 +0,0 @@
-#
-# 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
-# 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.
-#
-
-#
-
-OS=`uname -s`
-case "$OS" in
-  SunOS | Linux | Darwin )
-    FS="/"
-    CHMOD="${FS}bin${FS}chmod"
-    ;;
-  Windows* | CYGWIN* )
-    CHMOD="chmod"
-    ;;
-  * )
-    echo "Unrecognized system!"
-    exit 1;
-    ;;
-esac
-
-if [ "${TESTSRC}" = "" ]
-then
-  echo "TESTSRC not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTSRC=${TESTSRC}"
-if [ "${TESTJAVA}" = "" ]
-then
-  echo "TESTJAVA not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTJAVA=${TESTJAVA}"
-if [ "${COMPILEJAVA}" = "" ]; then
-  COMPILEJAVA="${TESTJAVA}"
-fi
-echo "COMPILEJAVA=${COMPILEJAVA}"
-if [ "${TESTCLASSES}" = "" ]
-then
-  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTCLASSES=${TESTCLASSES}"
-echo "CLASSPATH=${CLASSPATH}"
-
-cp ${TESTSRC}/Assert.java .
-cp -R ${TESTSRC}/package1 .
-cp -R ${TESTSRC}/package2 .
-${CHMOD} -R u+w *
-
-${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} Assert.java 
-
-${TESTJAVA}/bin/java ${TESTVMOPTS} Assert
-
-result=$?
-if [ $result -eq 0 ]
-then
-  echo "Passed"
-else
-  echo "Failed"
-fi
-exit $result
-
-
--- a/jdk/test/java/lang/ProcessBuilder/CloseRace.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/lang/ProcessBuilder/CloseRace.java	Wed Jul 05 19:33:51 2017 +0200
@@ -33,6 +33,8 @@
 import java.io.*;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
 
 public class CloseRace {
     private static final String BIG_FILE = "bigfile";
@@ -43,6 +45,9 @@
     private static final int testDurationSeconds
         = Integer.getInteger("test.duration", 600);
 
+    private static final CountDownLatch threadsStarted
+        = new CountDownLatch(2);
+
     static boolean fdInUse(int i) {
         return new File("/proc/self/fd/" + i).exists();
     }
@@ -61,6 +66,18 @@
         return count;
     }
 
+    static void dumpAllStacks() {
+        System.err.println("Start of dump");
+        final Map<Thread, StackTraceElement[]> allStackTraces
+                = Thread.getAllStackTraces();
+        for (Thread thread : allStackTraces.keySet()) {
+            System.err.println("Thread " + thread.getName());
+            for (StackTraceElement element : allStackTraces.get(thread))
+                System.err.println("\t" + element);
+        }
+        System.err.println("End of dump");
+    }
+
     public static void main(String args[]) throws Exception {
         if (!(new File("/proc/self/fd").isDirectory()))
             return;
@@ -84,26 +101,41 @@
         for (Thread thread : threads)
             thread.start();
 
+        threadsStarted.await();
         Thread.sleep(testDurationSeconds * 1000);
 
         for (Thread thread : threads)
             thread.interrupt();
-        for (Thread thread : threads)
-            thread.join();
+        for (Thread thread : threads) {
+            thread.join(10_000);
+            if (thread.isAlive()) {
+                dumpAllStacks();
+                throw new Error("At least one child thread ("
+                        + thread.getName()
+                        + ") failed to finish gracefully");
+            }
+        }
     }
 
     static class OpenLoop implements Runnable {
         public void run() {
+            threadsStarted.countDown();
             while (!Thread.interrupted()) {
                 try {
                     // wait for ExecLoop to finish creating process
-                    do {} while (count(procFDsInUse()) != 3);
+                    do {
+                        if (Thread.interrupted())
+                            return;
+                    } while (count(procFDsInUse()) != 3);
                     List<InputStream> iss = new ArrayList<>(4);
 
                     // eat up three "holes" (closed ends of pipe fd pairs)
                     for (int i = 0; i < 3; i++)
                         iss.add(new FileInputStream(BIG_FILE));
-                    do {} while (count(procFDsInUse()) == procFDs.length);
+                    do {
+                        if (Thread.interrupted())
+                            return;
+                    } while (count(procFDsInUse()) == procFDs.length);
                     // hopefully this will racily occupy empty fd slot
                     iss.add(new FileInputStream(BIG_FILE));
                     Thread.sleep(1); // Widen race window
@@ -120,11 +152,15 @@
 
     static class ExecLoop implements Runnable {
         public void run() {
+            threadsStarted.countDown();
             ProcessBuilder builder = new ProcessBuilder("/bin/true");
             while (!Thread.interrupted()) {
                 try {
                     // wait for OpenLoop to finish
-                    do {} while (count(procFDsInUse()) > 0);
+                    do {
+                        if (Thread.interrupted())
+                            return;
+                    } while (count(procFDsInUse()) > 0);
                     Process process = builder.start();
                     InputStream is = process.getInputStream();
                     process.waitFor();
--- a/jdk/test/java/lang/invoke/MethodHandles/TestCatchException.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/lang/invoke/MethodHandles/TestCatchException.java	Wed Jul 05 19:33:51 2017 +0200
@@ -72,19 +72,55 @@
         assertEquals(x, 17);
     }
 
+    final static Object masterParam = new Object();
+    final static Object[] masterTail = new Object[] { "str" };
+    static Exception masterEx = new Exception();
 
     public static Object m1(Object o1, Object o2, Object o3, Object o4, Object o5,
                             Object o6, Object o7, Object o8, Object... tail) {
+        assertEquals(masterParam, o1);
+        assertEquals(masterParam, o2);
+        assertEquals(masterParam, o3);
+        assertEquals(masterParam, o4);
+        assertEquals(masterParam, o5);
+        assertEquals(masterParam, o6);
+        assertEquals(masterParam, o7);
+        assertEquals(masterParam, o8);
+        assertEquals(masterTail, tail);
         return tail;
     }
 
     public static Object m2(Exception e, Object o1, Object o2, Object o3, Object o4,
                             Object o5, Object o6, Object o7, Object o8, Object... tail) {
+        assertEquals(masterEx, e);
+        assertEquals(masterParam, o1);
+        assertEquals(masterParam, o2);
+        assertEquals(masterParam, o3);
+        assertEquals(masterParam, o4);
+        assertEquals(masterParam, o5);
+        assertEquals(masterParam, o6);
+        assertEquals(masterParam, o7);
+        assertEquals(masterParam, o8);
+        assertEquals(masterTail, tail);
         return tail;
     }
 
+    public static Object throwEx(Object o1, Object o2, Object o3, Object o4, Object o5,
+                                 Object o6, Object o7, Object o8, Object... tail) throws Exception {
+        assertEquals(masterParam, o1);
+        assertEquals(masterParam, o2);
+        assertEquals(masterParam, o3);
+        assertEquals(masterParam, o4);
+        assertEquals(masterParam, o5);
+        assertEquals(masterParam, o6);
+        assertEquals(masterParam, o7);
+        assertEquals(masterParam, o8);
+        assertEquals(masterTail, tail);
+        throw masterEx;
+    }
+
     @Test
-    public void testVarargsCollector() throws Throwable {
+    public void testVarargsCollectorNoThrow() throws Throwable {
         MethodType t1 = MethodType.methodType(Object.class, Object.class, Object.class, Object.class, Object.class,
                 Object.class, Object.class, Object.class, Object.class, Object[].class);
 
@@ -92,17 +128,34 @@
 
         MethodHandle target = LOOKUP.findStatic(TestCatchException.class, "m1", t1)
                                     .asVarargsCollector(Object[].class);
-
-        MethodHandle catcher = LOOKUP.findStatic(TestCatchException.class, "m2", t2);
-
+        MethodHandle catcher = LOOKUP.findStatic(TestCatchException.class, "m2", t2)
+                                     .asVarargsCollector(Object[].class);
         MethodHandle gwc = MethodHandles.catchException(target, Exception.class, catcher);
 
-        Object o = new Object();
-        Object[] obj1 = new Object[] { "str" };
+        Object o = masterParam;
+        Object[] obj1 = masterTail;
+
+        Object r2 = gwc.invokeExact(o, o, o, o, o, o, o, o, obj1);
+        assertEquals(r2, obj1);
+    }
+
+    @Test
+    public void testVarargsCollectorThrow() throws Throwable {
+        MethodType t1 = MethodType.methodType(Object.class, Object.class, Object.class, Object.class, Object.class,
+                Object.class, Object.class, Object.class, Object.class, Object[].class);
 
-        Object r1 = target.invokeExact(o, o, o, o, o, o, o, o, obj1);
+        MethodType t2 = t1.insertParameterTypes(0, Exception.class);
+
+        MethodHandle target = LOOKUP.findStatic(TestCatchException.class, "throwEx", t1)
+                                    .asVarargsCollector(Object[].class);
+        MethodHandle catcher = LOOKUP.findStatic(TestCatchException.class, "m2", t2)
+                                     .asVarargsCollector(Object[].class);
+        MethodHandle gwc = MethodHandles.catchException(target, Exception.class, catcher);
+
+        Object o = masterParam;
+        Object[] obj1 = masterTail;
+
         Object r2 = gwc.invokeExact(o, o, o, o, o, o, o, o, obj1);
-        assertEquals(r1, obj1);
         assertEquals(r2, obj1);
     }
 
@@ -110,7 +163,8 @@
         TestCatchException test = new TestCatchException();
         test.testNoThrowPath();
         test.testThrowPath();
-        test.testVarargsCollector();
+        test.testVarargsCollectorNoThrow();
+        test.testVarargsCollectorThrow();
         System.out.println("TEST PASSED");
     }
 }
--- a/jdk/test/java/lang/management/ThreadMXBean/Locks.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/lang/management/ThreadMXBean/Locks.java	Wed Jul 05 19:33:51 2017 +0200
@@ -166,6 +166,9 @@
     private static CheckerThread checker;
     static class WaitingThread extends Thread {
         private final Phaser p;
+
+        volatile boolean waiting = false;
+
         public WaitingThread(Phaser p) {
             super("WaitingThread");
             this.p = p;
@@ -175,7 +178,9 @@
                 System.out.println("WaitingThread about to wait on objC");
                 try {
                     // Signal checker thread, about to wait on objC.
+                    waiting = false;
                     p.arriveAndAwaitAdvance(); // Phase 1 (waiting)
+                    waiting = true;
                     objC.wait();
                 } catch (InterruptedException e) {
                     e.printStackTrace();
@@ -194,7 +199,9 @@
             synchronized(objC) {
                 try {
                     // signal checker thread, about to wait on objC
+                    waiting = false;
                     p.arriveAndAwaitAdvance(); // Phase 3 (waiting)
+                    waiting = true;
                     objC.wait();
                 } catch (InterruptedException e) {
                     e.printStackTrace();
@@ -203,25 +210,35 @@
             }
             System.out.println("WaitingThread about to exit waiting on objC 2");
         }
-    }
-    static class CheckerThread extends Thread {
-        private final Phaser p;
-        public CheckerThread(Phaser p) {
-            super("CheckerThread");
-            this.p = p;
+
+        public void waitForWaiting() {
+            p.arriveAndAwaitAdvance();
+            while (!waiting) {
+                goSleep(10);
+            }
+            waitForState(State.WAITING);
+        }
+
+        public void waitForBlocked() {
+            p.arriveAndAwaitAdvance();
+            waitForState(State.BLOCKED);
         }
 
         private void waitForState(Thread.State state) {
-            p.arriveAndAwaitAdvance();
             while (!waiter.isInterrupted() && waiter.getState() != state) {
-                goSleep(10);
+                Thread.yield();
             }
         }
+    }
+    static class CheckerThread extends Thread {
+        public CheckerThread() {
+            super("CheckerThread");
+        }
 
         public void run() {
             synchronized (ready) {
                 // wait until WaitingThread about to wait for objC
-                waitForState(Thread.State.WAITING); // Phase 1 (waiting)
+                waiter.waitForWaiting(); // Phase 1 (waiting)
                 checkBlockedObject(waiter, objC, null, Thread.State.WAITING);
 
                 synchronized (objC) {
@@ -230,13 +247,13 @@
 
                 // wait for waiter thread to about to enter
                 // synchronized object ready.
-                waitForState(Thread.State.BLOCKED); // Phase 2 (waiting)
+                waiter.waitForBlocked(); // Phase 2 (waiting)
                 checkBlockedObject(waiter, ready, this, Thread.State.BLOCKED);
             }
 
             // wait for signal from waiting thread that it is about
             // wait for objC.
-            waitForState(Thread.State.WAITING); // Phase 3 (waiting)
+            waiter.waitForWaiting(); // Phase 3 (waiting)
             synchronized(objC) {
                 checkBlockedObject(waiter, objC, Thread.currentThread(), Thread.State.WAITING);
                 objC.notify();
@@ -284,7 +301,7 @@
         waiter = new WaitingThread(p);
         waiter.start();
 
-        checker = new CheckerThread(p);
+        checker = new CheckerThread();
         checker.start();
 
         try {
--- a/jdk/test/java/security/Policy/Root/Root.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/security/Policy/Root/Root.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,13 @@
  *
  * @bug 4619757
  * @summary User Policy Setting is not recognized on Netscape 6
- *              when invoked as root
- * @ignore - must run test as root
- *
- * place Root.policy in the root home directory (/), as /.java.policy
- * run this test as root:
- *      java Root
+ *          when invoked as root.
+ * @run main/manual Root
+ */
+
+/*
+ * Place Root.policy in the root home directory (/),
+ * as /.java.policy and run as test as root user.
  */
 
 import java.security.*;
--- a/jdk/test/java/security/cert/X509Certificate/X509BadCertificate.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/security/cert/X509Certificate/X509BadCertificate.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +23,7 @@
 
 /**
  * @test
- * @bug 8028431
+ * @bug 8028431 8028591
  * @summary Make sure that proper CertificateException is thrown
  *          when loading bad x509 certificate
  * @author Artem Smotrakov
@@ -39,6 +39,7 @@
 
     public static void main(String[] args) throws Exception {
         test("bad-cert-1.pem");
+        test("bad-cert-2.pem");
     }
 
     /**
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/security/cert/X509Certificate/bad-cert-2.pem	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,21 @@
+-----BEGIN CERTIFICATE-----
+MIIDZzCCAk+gAwIBAgIJAJYB3qu9C2kiMA0GCSqGSIb3DQEBBQUAMEoxDTALBgNV
+BAMMBFRlc3QxDTALBgNVBAsMBEphdmExDzANBgNVBAoMBk9yYWNsZTEMMAoGA1UE
+BwwDU1BCMQswCQYDVQQGEwJSVTAeFw0xMzEyMjMwNzA4MDhaFw0yMzEyMjEwNzA4
+MDhaMEoxDTALBgNVBAMMBFRlc3QxDTALBgNVBAsMBEphdmExDzANBgNVBAoMBk9y
+YWNsZTEMMAoGA1UEBwwDU1BCMQswCQYDVQQGEwJSVTCCASIwDQYJKoZIhvcNAQEB
+BQADgGEPADCCAQoCggEBAOqiCN4gFxehl547Q7/VNGbGApr+wszLdanHPucAH6Wf
+LtcRhKNUSqtBAQxEpFrTpMNEqm2GElAjiPa6m48qIjLVSvOb/9w3G/yXB8zyZbIm
+/Nfp2sT4OEaa1JSEZSpolhS4FfqYzjGQp5cn4Xn4zKjDgiceHgfLls5x2dRydQZO
+Yf91qSIioZxVHUtlo8yztkieiSaqPWt3nJ4PIwhFbsu1HVmWaYZD+nBYCKgVHqrS
+cueO98Ca4Doz73O27X1dVbQBdLS0JI7qVAG8LD388iPL8qbsOkgWPzmEQ+kLRKO4
+g7RpuwlXuwaMSh95NWaxlu4Ob6GRJQmpconYoe13+7ECAwEAAaNQME4wHQYDVR0O
+BBYEFIG8TPobXcbNbDi+zKudd9whpxoNMB8GA1UdIwQYMBaAFIG8TPobXcbNbDi+
+zKudd9whpxoNMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAAynN+e7
+h+ufT5SBKN/gBuJAnF1mKIPESiipuv5KoYUGZOY8ShgYLcwY+qnbuHYFUlvq6Zns
+K4/e+x/16h32vD7dEPkNvukbvER4YJQQiN6osDfXpTPzixYftWdmtX0u8xQfwb/g
+R8DS7bazz99jVXk+jTK4yWBY+gMwEat+LyNQ5cyq8Qhi1oBKUbGRbiOts19B97fn
+Rv8TsyXN3INLGYhdVxZoD7E5tyG1ydSFmOMadulAC2epBXDHOXZnz2UWauJc0XW5
+1L/YQVri47VkdHS3tisBzELEJdLmdMDb+5tAU+lItXmTXe2/PB53WIvsEIb4t+eQ
+wY0hCj9lVJlajTQ=
+-----END CERTIFICATE-----
--- a/jdk/test/java/util/Collection/CollectionDefaults.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/util/Collection/CollectionDefaults.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,6 +21,7 @@
  * questions.
  */
 
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
@@ -44,8 +45,8 @@
 import java.util.TreeSet;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentSkipListMap;
+import java.util.function.Function;
 import java.util.function.Predicate;
-import java.util.function.Supplier;
 
 /**
  * @test
@@ -59,26 +60,25 @@
     public static final Predicate<Integer> pEven = x -> 0 == x % 2;
     public static final Predicate<Integer> pOdd = x -> 1 == x % 2;
 
-    @SuppressWarnings("unchecked")
-    private static final Supplier<?>[] TEST_CLASSES = {
-        // Collection
-        ExtendsAbstractCollection<Integer>::new,
+    private static final List<Function<Collection<Integer>, Collection<Integer>>> TEST_SUPPLIERS = Arrays.asList(
+            // Collection
+            ExtendsAbstractCollection<Integer>::new,
 
-        // Lists
-        java.util.ArrayList<Integer>::new,
-        java.util.LinkedList<Integer>::new,
-        java.util.Vector<Integer>::new,
-        java.util.concurrent.CopyOnWriteArrayList<Integer>::new,
-        ExtendsAbstractList<Integer>::new,
+            // Lists
+            java.util.ArrayList<Integer>::new,
+            java.util.LinkedList<Integer>::new,
+            java.util.Vector<Integer>::new,
+            java.util.concurrent.CopyOnWriteArrayList<Integer>::new,
+            ExtendsAbstractList<Integer>::new,
 
-        // Sets
-        java.util.HashSet<Integer>::new,
-        java.util.LinkedHashSet<Integer>::new,
-        java.util.TreeSet<Integer>::new,
-        java.util.concurrent.ConcurrentSkipListSet<Integer>::new,
-        java.util.concurrent.CopyOnWriteArraySet<Integer>::new,
-        ExtendsAbstractSet<Integer>::new
-    };
+            // Sets
+            java.util.HashSet<Integer>::new,
+            java.util.LinkedHashSet<Integer>::new,
+            java.util.TreeSet<Integer>::new,
+            java.util.concurrent.ConcurrentSkipListSet<Integer>::new,
+            java.util.concurrent.CopyOnWriteArraySet<Integer>::new,
+            ExtendsAbstractSet<Integer>::new
+       );
 
     private static final int SIZE = 100;
 
@@ -94,7 +94,7 @@
         cases.add(new Object[] { new ExtendsAbstractSet<>() });
 
         cases.add(new Object[] { Collections.newSetFromMap(new HashMap<>()) });
-        cases.add(new Object[] { Collections.newSetFromMap(new LinkedHashMap()) });
+        cases.add(new Object[] { Collections.newSetFromMap(new LinkedHashMap<>()) });
         cases.add(new Object[] { Collections.newSetFromMap(new TreeMap<>()) });
         cases.add(new Object[] { Collections.newSetFromMap(new ConcurrentHashMap<>()) });
         cases.add(new Object[] { Collections.newSetFromMap(new ConcurrentSkipListMap<>()) });
@@ -107,24 +107,23 @@
     }
 
     @Test(dataProvider = "setProvider")
-    public void testProvidedWithNull(final Set<Integer> set) throws Exception {
+    public void testProvidedWithNull(final Set<Integer> set) {
         try {
             set.forEach(null);
             fail("expected NPE not thrown");
-        } catch (NullPointerException expected) {
-                ; // expected
-            }
+        } catch (NullPointerException expected) { // expected
+        }
         try {
             set.removeIf(null);
             fail("expected NPE not thrown");
-        } catch (NullPointerException expected) {
-               ; // expected
+        } catch (NullPointerException expected) { // expected
         }
     }
 
     @Test
-    public void testForEach() throws Exception {
-        final CollectionSupplier<Collection<Integer>> supplier = new CollectionSupplier((Supplier<Collection<Integer>>[]) TEST_CLASSES, SIZE);
+    public void testForEach() {
+        @SuppressWarnings("unchecked")
+        final CollectionSupplier<Collection<Integer>> supplier = new CollectionSupplier(TEST_SUPPLIERS, SIZE);
 
         for (final CollectionSupplier.TestCase<Collection<Integer>> test : supplier.get()) {
             final Collection<Integer> original = test.expected;
@@ -133,8 +132,7 @@
             try {
                 set.forEach(null);
                 fail("expected NPE not thrown");
-            } catch (NullPointerException expected) {
-                ; // expected
+            } catch (NullPointerException expected) { // expected
             }
             if (set instanceof Set && !((set instanceof SortedSet) || (set instanceof LinkedHashSet))) {
                 CollectionAsserts.assertContentsUnordered(set, original, test.toString());
@@ -155,8 +153,9 @@
     }
 
     @Test
-    public void testRemoveIf() throws Exception {
-        final CollectionSupplier<Collection<Integer>> supplier = new CollectionSupplier((Supplier<Collection<Integer>>[]) TEST_CLASSES, SIZE);
+    public void testRemoveIf() {
+        @SuppressWarnings("unchecked")
+        final CollectionSupplier<Collection<Integer>> supplier = new CollectionSupplier(TEST_SUPPLIERS, SIZE);
         for (final CollectionSupplier.TestCase<Collection<Integer>> test : supplier.get()) {
             final Collection<Integer> original = test.expected;
             final Collection<Integer> set = test.collection;
@@ -164,8 +163,7 @@
             try {
                 set.removeIf(null);
                 fail("expected NPE not thrown");
-            } catch (NullPointerException expected) {
-                ; // expected
+            } catch (NullPointerException expected) { // expected
             }
             if (set instanceof Set && !((set instanceof SortedSet) || (set instanceof LinkedHashSet))) {
                 CollectionAsserts.assertContentsUnordered(set, original, test.toString());
--- a/jdk/test/java/util/Collection/testlibrary/CollectionSupplier.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/util/Collection/testlibrary/CollectionSupplier.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 import java.lang.Integer;
 import java.lang.Iterable;
 import java.lang.Override;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.LinkedList;
 import java.util.List;
@@ -36,6 +37,7 @@
 
 import java.util.Collection;
 import java.util.Collections;
+import java.util.function.Function;
 import java.util.function.Supplier;
 
 /**
@@ -44,20 +46,24 @@
  */
 public final class CollectionSupplier<C extends Collection<Integer>> implements Supplier<Iterable<CollectionSupplier.TestCase<C>>> {
 
-    private final Supplier<C>[] classes;
+    private final List<Function<Collection<Integer>, C>> suppliers;
     private final int size;
 
     /**
      * A Collection test case.
      */
     public static final class TestCase<C extends Collection<Integer>> {
-
         /**
          * The name of the test case.
          */
         public final String name;
 
         /**
+         * The supplier of a collection
+         */
+        public Function<Collection<Integer>, C> supplier;
+
+        /**
          * Unmodifiable reference collection, useful for comparisons.
          */
         public final List<Integer> expected;
@@ -71,11 +77,11 @@
          * Create a Collection test case.
          *
          * @param name name of the test case
-         * @param expected reference collection
          * @param collection the modifiable test collection
          */
-        public TestCase(String name, C collection) {
+        public TestCase(String name, Function<Collection<Integer>, C> supplier, C collection) {
             this.name = name;
+            this.supplier = supplier;
             this.expected = Collections.unmodifiableList(
                 Arrays.asList(collection.toArray(new Integer[0])));
             this.collection = collection;
@@ -107,54 +113,52 @@
     }
 
     /**
-     * Create a {@code Supplier} that creates instances of specified collection
-     * classes of specified length.
+     * Create a {@code CollectionSupplier} that creates instances of specified
+     * collection suppliers of the specified size.
      *
-     * @param classNames class names that implement {@code Collection}
+     * @param suppliers the suppliers names that supply {@code Collection}
+     *        instances
      * @param size the desired size of each collection
      */
-    public CollectionSupplier(Supplier<C>[] classes, int size) {
-        this.classes = Arrays.copyOf(classes, classes.length);
+    public CollectionSupplier(List<Function<Collection<Integer>, C>> suppliers, int size) {
+        this.suppliers = suppliers;
         this.size = size;
     }
 
     @Override
     public Iterable<TestCase<C>> get() {
         final Collection<TestCase<C>> cases = new LinkedList<>();
-        for (final Supplier<C> type : classes) {
+        for (final Function<Collection<Integer>, C> supplier : suppliers)
             try {
-                final Collection<Integer> empty = type.get();
-                cases.add(new TestCase("empty", empty));
+                cases.add(new TestCase<>("empty", supplier, supplier.apply(Collections.emptyList())));
 
-                final Collection<Integer> single = type.get();
-                single.add(42);
-                cases.add(new TestCase("single", single));
+                cases.add(new TestCase<>("single", supplier, supplier.apply(Arrays.asList(42))));
 
-                final Collection<Integer> regular = type.get();
+                final Collection<Integer> regular = new ArrayList<>();
                 for (int i = 0; i < size; i++) {
                     regular.add(i);
                 }
-                cases.add(new TestCase("regular", regular));
+                cases.add(new TestCase<>("regular", supplier, supplier.apply(regular)));
 
-                final Collection<Integer> reverse = type.get();
+                final Collection<Integer> reverse = new ArrayList<>();
                 for (int i = size; i >= 0; i--) {
                     reverse.add(i);
                 }
-                cases.add(new TestCase("reverse", reverse));
+                cases.add(new TestCase<>("reverse", supplier, supplier.apply(reverse)));
 
-                final Collection<Integer> odds = type.get();
+                final Collection<Integer> odds = new ArrayList<>();
                 for (int i = 0; i < size; i++) {
                     odds.add((i * 2) + 1);
                 }
-                cases.add(new TestCase("odds", odds));
+                cases.add(new TestCase<>("odds", supplier, supplier.apply(odds)));
 
-                final Collection<Integer> evens = type.get();
+                final Collection<Integer> evens = new ArrayList<>();
                 for (int i = 0; i < size; i++) {
                     evens.add(i * 2);
                 }
-                cases.add(new TestCase("evens", evens));
+                cases.add(new TestCase<>("evens", supplier, supplier.apply(evens)));
 
-                final Collection<Integer> fibonacci = type.get();
+                final Collection<Integer> fibonacci = new ArrayList<>();
                 int prev2 = 0;
                 int prev1 = 1;
                 for (int i = 0; i < size; i++) {
@@ -166,58 +170,62 @@
                     prev2 = prev1;
                     prev1 = n;
                 }
-                cases.add(new TestCase("fibonacci", fibonacci));
+                cases.add(new TestCase<>("fibonacci", supplier, supplier.apply(fibonacci)));
+
 
-            // variants where the size of the backing storage != reported size
+                boolean isStructurallyModifiable = false;
+                try {
+                    C t = supplier.apply(Collections.emptyList());
+                    t.add(1);
+                    isStructurallyModifiable = true;
+                } catch (UnsupportedOperationException e) { }
+
+                if (!isStructurallyModifiable)
+                    continue;
+
+
+                // variants where the size of the backing storage != reported size
                 // created by removing half of the elements
-                final Collection<Integer> emptyWithSlack = type.get();
+                final C emptyWithSlack = supplier.apply(Collections.emptyList());
                 emptyWithSlack.add(42);
                 assertTrue(emptyWithSlack.remove(42));
-                cases.add(new TestCase("emptyWithSlack", emptyWithSlack));
+                cases.add(new TestCase<>("emptyWithSlack", supplier, emptyWithSlack));
 
-                final Collection<Integer> singleWithSlack = type.get();
+                final C singleWithSlack = supplier.apply(Collections.emptyList());
                 singleWithSlack.add(42);
                 singleWithSlack.add(43);
                 assertTrue(singleWithSlack.remove(43));
-                cases.add(new TestCase("singleWithSlack", singleWithSlack));
+                cases.add(new TestCase<>("singleWithSlack", supplier, singleWithSlack));
 
-                final Collection<Integer> regularWithSlack = type.get();
+                final C regularWithSlack = supplier.apply(Collections.emptyList());
                 for (int i = 0; i < (2 * size); i++) {
                     regularWithSlack.add(i);
                 }
-                assertTrue(regularWithSlack.removeIf((x) -> {
-                    return x >= size;
-                }));
-                cases.add(new TestCase("regularWithSlack", regularWithSlack));
+                assertTrue(regularWithSlack.removeIf(x -> x < size));
+                cases.add(new TestCase<>("regularWithSlack", supplier, regularWithSlack));
 
-                final Collection<Integer> reverseWithSlack = type.get();
+                final C reverseWithSlack = supplier.apply(Collections.emptyList());
                 for (int i = 2 * size; i >= 0; i--) {
                     reverseWithSlack.add(i);
                 }
-                assertTrue(reverseWithSlack.removeIf((x) -> {
-                    return x < size;
-                }));
-                cases.add(new TestCase("reverseWithSlack", reverseWithSlack));
+                assertTrue(reverseWithSlack.removeIf(x -> x < size));
+                cases.add(new TestCase<>("reverseWithSlack", supplier, reverseWithSlack));
 
-                final Collection<Integer> oddsWithSlack = type.get();
+                final C oddsWithSlack = supplier.apply(Collections.emptyList());
                 for (int i = 0; i < 2 * size; i++) {
                     oddsWithSlack.add((i * 2) + 1);
                 }
-                assertTrue(oddsWithSlack.removeIf((x) -> {
-                    return x >= size;
-                }));
-                cases.add(new TestCase("oddsWithSlack", oddsWithSlack));
+                assertTrue(oddsWithSlack.removeIf(x -> x >= size));
+                cases.add(new TestCase<>("oddsWithSlack", supplier, oddsWithSlack));
 
-                final Collection<Integer> evensWithSlack = type.get();
+                final C evensWithSlack = supplier.apply(Collections.emptyList());
                 for (int i = 0; i < 2 * size; i++) {
                     evensWithSlack.add(i * 2);
                 }
-                assertTrue(evensWithSlack.removeIf((x) -> {
-                    return x >= size;
-                }));
-                cases.add(new TestCase("evensWithSlack", evensWithSlack));
+                assertTrue(evensWithSlack.removeIf(x -> x >= size));
+                cases.add(new TestCase<>("evensWithSlack", supplier, evensWithSlack));
 
-                final Collection<Integer> fibonacciWithSlack = type.get();
+                final C fibonacciWithSlack = supplier.apply(Collections.emptyList());
                 prev2 = 0;
                 prev1 = 1;
                 for (int i = 0; i < size; i++) {
@@ -229,15 +237,12 @@
                     prev2 = prev1;
                     prev1 = n;
                 }
-                assertTrue(fibonacciWithSlack.removeIf((x) -> {
-                    return x < 20;
-                }));
-                cases.add(new TestCase("fibonacciWithSlack",
-                    fibonacciWithSlack));
-            } catch (Exception failed) {
+                assertTrue(fibonacciWithSlack.removeIf(x -> x < 20));
+                cases.add(new TestCase<>("fibonacciWithSlack", supplier, fibonacciWithSlack));
+            }
+            catch (Exception failed) {
                 throw new TestException(failed);
             }
-        }
 
         return cases;
     }
--- a/jdk/test/java/util/List/ListDefaults.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/java/util/List/ListDefaults.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.List;
@@ -43,31 +44,45 @@
 
 import java.lang.reflect.Constructor;
 import java.util.ConcurrentModificationException;
+import java.util.function.Consumer;
+import java.util.function.Function;
 import java.util.function.Predicate;
 import java.util.function.Supplier;
 
 /**
  * @test
  * @summary Unit tests for extension methods on List
- * @bug 8023367
+ * @bug 8023367 8037106
  * @library ../Collection/testlibrary
  * @build CollectionAsserts CollectionSupplier ExtendsAbstractList
  * @run testng ListDefaults
  */
 public class ListDefaults {
 
-    private static final Supplier<?>[] LIST_CLASSES = {
-        java.util.ArrayList::new,
-        java.util.LinkedList::new,
-        java.util.Vector::new,
-        java.util.concurrent.CopyOnWriteArrayList::new,
-        ExtendsAbstractList::new
-     };
+    // Suppliers of lists that can support structural modifications
+    private static final List<Function<Collection, List>> LIST_STRUCT_MOD_SUPPLIERS = Arrays.asList(
+            java.util.ArrayList::new,
+            java.util.LinkedList::new,
+            java.util.Vector::new,
+            java.util.concurrent.CopyOnWriteArrayList::new,
+            ExtendsAbstractList::new
+    );
 
-    private static final Supplier<?>[] LIST_CME_CLASSES = {
-        java.util.ArrayList::new,
-        java.util.Vector::new
-     };
+    // Suppliers of lists that can support in place modifications
+    private static final List<Function<Collection, List>> LIST_SUPPLIERS = Arrays.asList(
+            java.util.ArrayList::new,
+            java.util.LinkedList::new,
+            java.util.Vector::new,
+            java.util.concurrent.CopyOnWriteArrayList::new,
+            ExtendsAbstractList::new,
+            c -> Arrays.asList(c.toArray())
+    );
+
+    // Suppliers of lists supporting CMEs
+    private static final List<Function<Collection, List>> LIST_CME_SUPPLIERS = Arrays.asList(
+            java.util.ArrayList::new,
+            java.util.Vector::new
+    );
 
     private static final Predicate<Integer> pEven = x -> 0 == x % 2;
     private static final Predicate<Integer> pOdd = x -> 1 == x % 2;
@@ -83,17 +98,13 @@
     private static final int SUBLIST_TO = SIZE - 5;
     private static final int SUBLIST_SIZE = SUBLIST_TO - SUBLIST_FROM;
 
-    private static interface Callback {
-        void call(List<Integer> list);
-    }
-
     // call the callback for each recursive subList
-    private void trimmedSubList(final List<Integer> list, final Callback callback) {
+    private void trimmedSubList(final List<Integer> list, final Consumer<List<Integer>> callback) {
         int size = list.size();
         if (size > 1) {
             // trim 1 element from both ends
             final List<Integer> subList = list.subList(1, size - 1);
-            callback.call(subList);
+            callback.accept(subList);
             trimmedSubList(subList, callback);
         }
     }
@@ -107,17 +118,21 @@
         cases.add(new Object[] { new Vector<>() });
         cases.add(new Object[] { new Stack<>() });
         cases.add(new Object[] { new CopyOnWriteArrayList<>() });
+        cases.add(new Object[] { Arrays.asList() });
 
-        cases.add(new Object[] { new ArrayList(){{add(42);}} });
-        cases.add(new Object[] { new LinkedList(){{add(42);}} });
-        cases.add(new Object[] { new Vector(){{add(42);}} });
-        cases.add(new Object[] { new Stack(){{add(42);}} });
-        cases.add(new Object[] { new CopyOnWriteArrayList(){{add(42);}} });
+        List<Integer> l = Arrays.asList(42);
+        cases.add(new Object[] { new ArrayList<>(l) });
+        cases.add(new Object[] { new LinkedList<>(l) });
+        cases.add(new Object[] { new Vector<>(l) });
+        Stack<Integer> s = new Stack<>(); s.addAll(l);
+        cases.add(new Object[]{s});
+        cases.add(new Object[] { new CopyOnWriteArrayList<>(l) });
+        cases.add(new Object[] { l });
         return cases.toArray(new Object[0][cases.size()]);
     }
 
     @Test(dataProvider = "listProvider")
-    public void testProvidedWithNull(final List<Integer> list) throws Exception {
+    public void testProvidedWithNull(final List<Integer> list) {
         try {
             list.forEach(null);
             fail("expected NPE not thrown");
@@ -138,11 +153,12 @@
     }
 
     @Test
-    public void testForEach() throws Exception {
-        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier((Supplier<List<Integer>>[])LIST_CLASSES, SIZE);
+    public void testForEach() {
+        @SuppressWarnings("unchecked")
+        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_SUPPLIERS, SIZE);
         for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
-            final List<Integer> original = ((List<Integer>) test.expected);
-            final List<Integer> list = ((List<Integer>) test.collection);
+            final List<Integer> original = test.expected;
+            final List<Integer> list = test.collection;
 
             try {
                 list.forEach(null);
@@ -165,23 +181,21 @@
                 }
             }
 
-            trimmedSubList(list, new Callback() {
-                @Override
-                public void call(final List<Integer> list) {
-                    final List<Integer> actual = new LinkedList<>();
-                    list.forEach(actual::add);
-                    CollectionAsserts.assertContents(actual, list);
-                }
-            });
+            trimmedSubList(list, l -> {
+                    final List<Integer> a = new LinkedList<>();
+                    l.forEach(a::add);
+                    CollectionAsserts.assertContents(a, l);
+                });
         }
     }
 
     @Test
-    public void testRemoveIf() throws Exception {
-        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier((Supplier<List<Integer>>[])LIST_CLASSES, SIZE);
+    public void testRemoveIf() {
+        @SuppressWarnings("unchecked")
+        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_STRUCT_MOD_SUPPLIERS, SIZE);
         for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
-            final List<Integer> original = ((List<Integer>) test.expected);
-            final List<Integer> list = ((List<Integer>) test.collection);
+            final List<Integer> original = test.expected;
+            final List<Integer> list = test.collection;
 
             try {
                 list.removeIf(null);
@@ -195,9 +209,9 @@
             }
         }
 
-        for (final CollectionSupplier.TestCase test : supplier.get()) {
-            final List<Integer> original = ((List<Integer>) test.expected);
-            final List<Integer> list = ((List<Integer>) test.collection);
+        for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
+            final List<Integer> original = test.expected;
+            final List<Integer> list = test.collection;
             list.removeIf(pOdd);
             for (int i : list) {
                 assertTrue((i % 2) == 0);
@@ -211,9 +225,9 @@
             assertTrue(list.isEmpty());
         }
 
-        for (final CollectionSupplier.TestCase test : supplier.get()) {
-            final List<Integer> original = ((List<Integer>) test.expected);
-            final List<Integer> list = ((List<Integer>) test.collection);
+        for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
+            final List<Integer> original = test.expected;
+            final List<Integer> list = test.collection;
             final List<Integer> listCopy = new ArrayList<>(list);
             if (original.size() > SUBLIST_SIZE) {
                 final List<Integer> subList = list.subList(SUBLIST_FROM, SUBLIST_TO);
@@ -237,22 +251,19 @@
             }
         }
 
-        for (final CollectionSupplier.TestCase test : supplier.get()) {
-            final List<Integer> list = ((List<Integer>) test.collection);
-            trimmedSubList(list, new Callback() {
-                @Override
-                public void call(final List<Integer> list) {
-                    final List<Integer> copy = new ArrayList<>(list);
-                    list.removeIf(pOdd);
-                    for (int i : list) {
-                        assertTrue((i % 2) == 0);
-                    }
-                    for (int i : copy) {
-                        if (i % 2 == 0) {
-                            assertTrue(list.contains(i));
-                        } else {
-                            assertFalse(list.contains(i));
-                        }
+        for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
+            final List<Integer> list = test.collection;
+            trimmedSubList(list, l -> {
+                final List<Integer> copy = new ArrayList<>(l);
+                l.removeIf(pOdd);
+                for (int i : l) {
+                    assertTrue((i % 2) == 0);
+                }
+                for (int i : copy) {
+                    if (i % 2 == 0) {
+                        assertTrue(l.contains(i));
+                    } else {
+                        assertFalse(l.contains(i));
                     }
                 }
             });
@@ -267,12 +278,13 @@
     }
 
     @Test
-    public void testReplaceAll() throws Exception {
+    public void testReplaceAll() {
         final int scale = 3;
-        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier((Supplier<List<Integer>>[])LIST_CLASSES, SIZE);
+        @SuppressWarnings("unchecked")
+        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_SUPPLIERS, SIZE);
         for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
-            final List<Integer> original = ((List<Integer>) test.expected);
-            final List<Integer> list = ((List<Integer>) test.collection);
+            final List<Integer> original = test.expected;
+            final List<Integer> list = test.collection;
 
             try {
                 list.replaceAll(null);
@@ -281,7 +293,7 @@
             CollectionAsserts.assertContents(list, original);
 
             list.replaceAll(x -> scale * x);
-            for (int i=0; i < original.size(); i++) {
+            for (int i = 0; i < original.size(); i++) {
                 assertTrue(list.get(i) == (scale * original.get(i)), "mismatch at index " + i);
             }
 
@@ -306,28 +318,26 @@
             }
         }
 
-        for (final CollectionSupplier.TestCase test : supplier.get()) {
-            final List<Integer> list = ((List<Integer>) test.collection);
-            trimmedSubList(list, new Callback() {
-                @Override
-                public void call(final List<Integer> list) {
-                    final List<Integer> copy = new ArrayList<>(list);
-                    final int offset = 5;
-                    list.replaceAll(x -> offset + x);
-                    for (int i=0; i < copy.size(); i++) {
-                        assertTrue(list.get(i) == (offset + copy.get(i)), "mismatch at index " + i);
-                    }
+        for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
+            final List<Integer> list = test.collection;
+            trimmedSubList(list, l -> {
+                final List<Integer> copy = new ArrayList<>(l);
+                final int offset = 5;
+                l.replaceAll(x -> offset + x);
+                for (int i = 0; i < copy.size(); i++) {
+                    assertTrue(l.get(i) == (offset + copy.get(i)), "mismatch at index " + i);
                 }
             });
         }
     }
 
     @Test
-    public void testSort() throws Exception {
-        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier((Supplier<List<Integer>>[])LIST_CLASSES, SIZE);
+    public void testSort() {
+        @SuppressWarnings("unchecked")
+        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_SUPPLIERS, SIZE);
         for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
-            final List<Integer> original = ((List<Integer>) test.expected);
-            final List<Integer> list = ((List<Integer>) test.collection);
+            final List<Integer> original = test.expected;
+            final List<Integer> list = test.collection;
             CollectionSupplier.shuffle(list);
             list.sort(Integer::compare);
             CollectionAsserts.assertSorted(list, Integer::compare);
@@ -338,23 +348,23 @@
 
             CollectionSupplier.shuffle(list);
             list.sort(null);
-            CollectionAsserts.assertSorted(list, Comparator.<Integer>naturalOrder());
+            CollectionAsserts.assertSorted(list, Comparator.naturalOrder());
             if (test.name.startsWith("reverse")) {
                 Collections.reverse(list);
             }
             CollectionAsserts.assertContents(list, original);
 
             CollectionSupplier.shuffle(list);
-            list.sort(Comparator.<Integer>naturalOrder());
-            CollectionAsserts.assertSorted(list, Comparator.<Integer>naturalOrder());
+            list.sort(Comparator.naturalOrder());
+            CollectionAsserts.assertSorted(list, Comparator.naturalOrder());
             if (test.name.startsWith("reverse")) {
                 Collections.reverse(list);
             }
             CollectionAsserts.assertContents(list, original);
 
             CollectionSupplier.shuffle(list);
-            list.sort(Comparator.<Integer>reverseOrder());
-            CollectionAsserts.assertSorted(list, Comparator.<Integer>reverseOrder());
+            list.sort(Comparator.reverseOrder());
+            CollectionAsserts.assertSorted(list, Comparator.reverseOrder());
             if (!test.name.startsWith("reverse")) {
                 Collections.reverse(list);
             }
@@ -365,32 +375,35 @@
             CollectionAsserts.assertSorted(list, BIT_COUNT_COMPARATOR);
             // check sort by verifying that bitCount increases and never drops
             int minBitCount = 0;
-            int bitCount = 0;
             for (final Integer i : list) {
-                bitCount = Integer.bitCount(i);
+                int bitCount = Integer.bitCount(i);
                 assertTrue(bitCount >= minBitCount);
                 minBitCount = bitCount;
             }
 
+            // Resuse the supplier to store AtomicInteger instead of Integer
+            // Hence the use of raw type and cast
+            List<AtomicInteger> incomparablesData = new ArrayList<>();
+            for (int i = 0; i < test.expected.size(); i++) {
+                incomparablesData.add(new AtomicInteger(i));
+            }
+            Function f = test.supplier;
             @SuppressWarnings("unchecked")
-            final Constructor<? extends List<?>> defaultConstructor = ((Class<? extends List<?>>)test.collection.getClass()).getConstructor();
-            final List<AtomicInteger> incomparables = (List<AtomicInteger>) defaultConstructor.newInstance();
+            List<AtomicInteger> incomparables = (List<AtomicInteger>) f.apply(incomparablesData);
 
-            for (int i=0; i < test.expected.size(); i++) {
-                incomparables.add(new AtomicInteger(i));
-            }
             CollectionSupplier.shuffle(incomparables);
             incomparables.sort(ATOMIC_INTEGER_COMPARATOR);
-            for (int i=0; i < test.expected.size(); i++) {
+            for (int i = 0; i < test.expected.size(); i++) {
                 assertEquals(i, incomparables.get(i).intValue());
             }
 
+
             if (original.size() > SUBLIST_SIZE) {
                 final List<Integer> copy = new ArrayList<>(list);
                 final List<Integer> subList = list.subList(SUBLIST_FROM, SUBLIST_TO);
                 CollectionSupplier.shuffle(subList);
-                subList.sort(Comparator.<Integer>naturalOrder());
-                CollectionAsserts.assertSorted(subList, Comparator.<Integer>naturalOrder());
+                subList.sort(Comparator.naturalOrder());
+                CollectionAsserts.assertSorted(subList, Comparator.naturalOrder());
                 // verify that elements [0, from) remain unmodified
                 for (int i = 0; i < SUBLIST_FROM; i++) {
                     assertTrue(list.get(i) == copy.get(i),
@@ -404,25 +417,22 @@
             }
         }
 
-        for (final CollectionSupplier.TestCase test : supplier.get()) {
-            final List<Integer> list = ((List<Integer>) test.collection);
-            trimmedSubList(list, new Callback() {
-                @Override
-                public void call(final List<Integer> list) {
-                    final List<Integer> copy = new ArrayList<>(list);
-                    CollectionSupplier.shuffle(list);
-                    list.sort(Comparator.<Integer>naturalOrder());
-                    CollectionAsserts.assertSorted(list, Comparator.<Integer>naturalOrder());
-                }
+        for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
+            final List<Integer> list = test.collection;
+            trimmedSubList(list, l -> {
+                CollectionSupplier.shuffle(l);
+                l.sort(Comparator.naturalOrder());
+                CollectionAsserts.assertSorted(l, Comparator.naturalOrder());
             });
         }
     }
 
     @Test
-    public void testForEachThrowsCME() throws Exception {
-        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier((Supplier<List<Integer>>[])LIST_CME_CLASSES, SIZE);
+    public void testForEachThrowsCME() {
+        @SuppressWarnings("unchecked")
+        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_CME_SUPPLIERS, SIZE);
         for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
-            final List<Integer> list = ((List<Integer>) test.collection);
+            final List<Integer> list = test.collection;
 
             if (list.size() <= 1) {
                 continue;
@@ -430,7 +440,7 @@
             boolean gotException = false;
             try {
                 // bad predicate that modifies its list, should throw CME
-                list.forEach((x) -> {list.add(x);});
+                list.forEach(list::add);
             } catch (ConcurrentModificationException cme) {
                 gotException = true;
             }
@@ -441,11 +451,11 @@
     }
 
     @Test
-    public void testRemoveIfThrowsCME() throws Exception {
-        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier((Supplier<List<Integer>>[])LIST_CME_CLASSES, SIZE);
+    public void testRemoveIfThrowsCME() {
+        @SuppressWarnings("unchecked")
+        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_CME_SUPPLIERS, SIZE);
         for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
-            final List<Integer> original = ((List<Integer>) test.expected);
-            final List<Integer> list = ((List<Integer>) test.collection);
+            final List<Integer> list = test.collection;
 
             if (list.size() <= 1) {
                 continue;
@@ -453,7 +463,7 @@
             boolean gotException = false;
             try {
                 // bad predicate that modifies its list, should throw CME
-                list.removeIf((x) -> {return list.add(x);});
+                list.removeIf(list::add);
             } catch (ConcurrentModificationException cme) {
                 gotException = true;
             }
@@ -464,10 +474,11 @@
     }
 
     @Test
-    public void testReplaceAllThrowsCME() throws Exception {
-        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier((Supplier<List<Integer>>[])LIST_CME_CLASSES, SIZE);
+    public void testReplaceAllThrowsCME() {
+        @SuppressWarnings("unchecked")
+        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_CME_SUPPLIERS, SIZE);
         for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
-            final List<Integer> list = ((List<Integer>) test.collection);
+            final List<Integer> list = test.collection;
 
             if (list.size() <= 1) {
                 continue;
@@ -486,10 +497,11 @@
     }
 
     @Test
-    public void testSortThrowsCME() throws Exception {
-        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier((Supplier<List<Integer>>[])LIST_CME_CLASSES, SIZE);
+    public void testSortThrowsCME() {
+        @SuppressWarnings("unchecked")
+        final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_CME_SUPPLIERS, SIZE);
         for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
-            final List<Integer> list = ((List<Integer>) test.collection);
+            final List<Integer> list = test.collection;
 
             if (list.size() <= 1) {
                 continue;
@@ -523,7 +535,7 @@
     }
 
     @Test(dataProvider = "shortIntListProvider")
-    public void testRemoveIfFromSlice(final List<Integer> list) throws Exception {
+    public void testRemoveIfFromSlice(final List<Integer> list) {
         final List<Integer> sublist = list.subList(3, 6);
         assertTrue(sublist.removeIf(x -> x == 4));
         CollectionAsserts.assertContents(list, SLICED_EXPECTED);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/print/PrintServiceLookup/CountPrintServices.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 javax.print.PrintService;
+import javax.print.PrintServiceLookup;
+import javax.print.attribute.AttributeSet;
+import javax.print.attribute.HashAttributeSet;
+import javax.print.attribute.standard.PrinterName;
+
+/*
+ * @test
+ * @bug 8032693
+ * @summary Test that lpstat and JDK agree whether there are printers.
+ */
+public class CountPrintServices {
+
+  public static void main(String[] args) throws Exception {
+    String os = System.getProperty("os.name").toLowerCase();
+    System.out.println("OS is " + os);
+    if (!os.equals("linux")) {
+        System.out.println("Linux specific test. No need to continue");
+        return;
+    }
+    PrintService services[] =
+        PrintServiceLookup.lookupPrintServices(null, null);
+    if (services.length > 0) {
+       System.out.println("Services found. No need to test further.");
+       return;
+    }
+    String[] lpcmd = { "lpstat", "-a" };
+    Process proc = Runtime.getRuntime().exec(lpcmd);
+    proc.waitFor();
+    InputStreamReader ir = new InputStreamReader(proc.getInputStream());
+    BufferedReader br = new BufferedReader(ir);
+    int count = 0;
+    String printer;
+    while ((printer = br.readLine()) != null) {
+       System.out.println("lpstat:: " + printer);
+       count++;
+    }
+    if (count > 0) {
+        throw new RuntimeException("Services exist, but not found by JDK.");
+    }
+ }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/print/attribute/TestUnsupportedResolution.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * 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 8033277
+ * @summary Confirm that scaling of printout is correct.  Manual comparison with printout using a supported resolution is needed.
+ * @run main/manual TestUnsupportedResolution
+ */
+
+import java.awt.Graphics;
+import java.awt.print.PageFormat;
+import java.awt.print.Printable;
+import java.awt.print.PrinterException;
+import java.awt.print.PrinterJob;
+
+import javax.print.*;
+import javax.print.attribute.HashPrintRequestAttributeSet;
+import javax.print.attribute.PrintRequestAttributeSet;
+import javax.print.attribute.standard.*;
+import javax.print.attribute.ResolutionSyntax;
+
+public class TestUnsupportedResolution implements Printable
+{
+public static void main(String[] args)
+{
+    System.out.println("USAGE: default or no args: it will test 300 dpi\n       args is \"600\" : it will test 600 dpi\n------------------------------------------------------\n");
+    TestUnsupportedResolution pt=new TestUnsupportedResolution();
+    pt.printWorks(args);
+}
+
+public void printWorks(String[] args)
+{
+    PrinterJob job=PrinterJob.getPrinterJob();
+    job.setPrintable(this);
+    PrintRequestAttributeSet settings=new HashPrintRequestAttributeSet();
+    PrinterResolution pr = new PrinterResolution(300, 300, ResolutionSyntax.DPI);
+    if (args.length > 0 && (args[0].compareTo("600") == 0)) {
+        pr = new PrinterResolution(600, 600, ResolutionSyntax.DPI);
+        System.out.println("Adding 600 Dpi attribute");
+    } else {
+        System.out.println("Adding 300 Dpi attribute");
+    }
+    PrintService ps = job.getPrintService();
+    boolean resolutionSupported = ps.isAttributeValueSupported(pr, null, null);
+    System.out.println("Is "+pr+" supported by "+ps+"?    "+resolutionSupported);
+    if (resolutionSupported) {
+        System.out.println("Resolution is supported.\nTest is not applicable, PASSED");
+    }
+    settings.add(pr);
+    if (args.length > 0 && (args[0].equalsIgnoreCase("fidelity"))) {
+        settings.add(Fidelity.FIDELITY_TRUE);
+        System.out.println("Adding Fidelity.FIDELITY_TRUE attribute");
+   }
+
+   if (job.printDialog(settings))
+   {
+        try {
+            job.print(settings);
+        } catch (PrinterException e) {
+            e.printStackTrace();
+        }
+    }
+}
+
+public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException
+{
+    if (pageIndex>0)
+    {
+        return NO_SUCH_PAGE;
+    }
+
+    StringBuffer s=new StringBuffer();
+    for (int i=0;i<10;i++)
+    {
+        s.append("1234567890ABCDEFGHIJ");
+    }
+
+    int x=(int) pageFormat.getImageableX();
+    int y=(int) (pageFormat.getImageableY()+50);
+    graphics.drawString(s.toString(), x, y);
+
+    return PAGE_EXISTS;
+}
+}
+
--- a/jdk/test/javax/security/auth/kerberos/KerberosHashEqualsTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/javax/security/auth/kerberos/KerberosHashEqualsTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,11 @@
  * @test
  * @bug 4641821
  * @summary hashCode() and equals() for KerberosKey and KerberosTicket
- * @ignore Must set up KDC and setup Kerberos configuration file
+ * @run main/manual KerberosHashEqualsTest
+ */
+
+/*
+ * Must setup KDC and Kerberos configuration file
  */
 
 import java.net.InetAddress;
--- a/jdk/test/javax/security/auth/kerberos/KerberosTixDateTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/javax/security/auth/kerberos/KerberosTixDateTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,11 @@
  * @test
  * @bug 6659990
  * @summary test the immutability of the Date fields in KerberosTicket class.
- * @ignore Must set up KDC and setup Kerberos configuration file
+ * @run main/manual KerberosTixDateTest
+ */
+
+/*
+ * Must setup KDC and Kerberos configuration file
  */
 
 import java.net.InetAddress;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JButton/JButtonPaintNPE/JButtonPaintNPE.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,77 @@
+/*
+ * 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.awt.Graphics;
+import java.awt.Toolkit;
+import java.awt.image.BufferedImage;
+import java.lang.reflect.InvocationTargetException;
+
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.SwingUtilities;
+
+import sun.awt.SunToolkit;
+
+/**
+ * @test
+ * @bug 8009919
+ * @author Sergey Bylokhov
+ */
+public final class JButtonPaintNPE {
+
+    private static JFrame frame;
+
+    public static void main(final String[] args)
+            throws InvocationTargetException, InterruptedException {
+        SwingUtilities.invokeAndWait(() -> {
+            frame = new JFrame();
+            frame.add(new JButton() {
+                @Override
+                protected void paintComponent(final Graphics g) {
+                    Graphics gg = new BufferedImage(getWidth(), getHeight(),
+                                  BufferedImage.TYPE_INT_ARGB).createGraphics();
+                    super.paintComponent(gg);
+                    gg.dispose();
+                }
+            });
+            frame.setSize(300, 300);
+            frame.setLocationRelativeTo(null);
+            frame.setVisible(true);
+        });
+        sleep();
+        SwingUtilities.invokeAndWait(() -> {
+            if (frame != null) {
+                frame.dispose();
+            }
+        });
+    }
+
+    private static void sleep() {
+        try {
+            ((SunToolkit) Toolkit.getDefaultToolkit()).realSync();
+            Thread.sleep(1000);
+        } catch (final InterruptedException ignored) {
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JFileChooser/8010718/bug8010718.java	Wed Jul 05 19:33:51 2017 +0200
@@ -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.
+ */
+
+/*
+ * @test
+ * @bug 8010718
+ * @summary [macosx] JFileChooser current filter nullified by addChoosableFileFilter
+ * @author Tomas Hurka
+ */
+import java.io.File;
+import javax.swing.*;
+import javax.swing.filechooser.FileFilter;
+
+public class bug8010718 {
+
+    public static void main(String[] args) throws Exception {
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                JFileChooser fileChooser = new JFileChooser();
+                fileChooser.addChoosableFileFilter(new FileFilter() {
+                    @Override
+                    public boolean accept(File f) {
+                        return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
+                    }
+
+                    @Override
+                    public String getDescription() {
+                        return "XML";
+                    }
+                });
+                fileChooser.addChoosableFileFilter(new FileFilter() {
+                    @Override
+                    public boolean accept(File f) {
+                        return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt");
+                    }
+
+                    @Override
+                    public String getDescription() {
+                        return "TXT";
+                    }
+                });
+                if (fileChooser.getFileFilter() == null) {
+                    throw new RuntimeException("getFileFilter() should not return null");
+                }
+            }
+        });
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JMenuItem/8031573/bug8031573.html	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,40 @@
+<!--
+ Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ 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.
+-->
+
+<html>
+<body>
+
+Verify that high resolution system icons are used JCheckBoxMenuItem 
+on HiDPI displays.
+
+If the display does not support HiDPI mode press PASS.
+
+1. Run the test on HiDPI Display.
+2. Press the Menu in the applet
+3. Check that the icon on the JCheckBoxMenuItem is smooth
+If so, press PASS, else press FAIL.
+
+<applet  code="bug8031573.class" width=250 height=250></applet>
+
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JMenuItem/8031573/bug8031573.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.awt.FlowLayout;
+import javax.swing.JApplet;
+import javax.swing.JCheckBoxMenuItem;
+import javax.swing.JMenu;
+import javax.swing.JMenuBar;
+import javax.swing.SwingUtilities;
+
+/* @test
+ * @bug 8031573
+ * @summary [macosx] Checkmarks of JCheckBoxMenuItems aren't rendered
+ *           in high resolution on Retina
+ * @author Alexander Scherbatiy
+ * @run applet/manual=yesno bug8031573.html
+ */
+public class bug8031573 extends JApplet {
+
+    @Override
+    public void init() {
+        try {
+            SwingUtilities.invokeAndWait(new Runnable() {
+
+                @Override
+                public void run() {
+                    JMenuBar bar = new JMenuBar();
+                    JMenu menu = new JMenu("Menu");
+                    JCheckBoxMenuItem checkBoxMenuItem
+                            = new JCheckBoxMenuItem("JCheckBoxMenuItem");
+                    checkBoxMenuItem.setSelected(true);
+                    menu.add(checkBoxMenuItem);
+                    bar.add(menu);
+                    setJMenuBar(bar);
+                }
+            });
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JOptionPane/8024926/bug8024926.html	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,32 @@
+<!--
+ 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.
+-->
+
+<html>
+    <head>
+        <title>High resolution icon test, bug ID 8024926</title>
+    </head>
+    <body>
+    <applet CODE="bug8024926.class" WIDTH=300 HEIGHT=100></applet>
+    <p> See the dialog box (usually in upper left corner) for instructions</p>
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JOptionPane/8024926/bug8024926.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,209 @@
+/*
+ * 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.awt.BorderLayout;
+import java.awt.Dialog;
+import java.awt.EventQueue;
+import java.awt.Frame;
+import java.awt.TextArea;
+import javax.swing.JApplet;
+import javax.swing.JOptionPane;
+import sun.awt.OSInfo;
+
+/**
+ * @test
+ * @bug 8024926
+ * @summary [macosx] AquaIcon HiDPI support
+ * @author Alexander Scherbatiy
+ * @run applet/manual=yesno bug8024926.html
+ */
+public class bug8024926 extends JApplet {
+    //Declare things used in the test, like buttons and labels here
+
+    public void init() {
+        //Create instructions for the user here, as well as set up
+        // the environment -- set the layout manager, add buttons,
+        // etc.
+        this.setLayout(new BorderLayout());
+
+
+        if (OSInfo.getOSType().equals(OSInfo.OSType.MACOSX)) {
+            String[] instructions = {
+                "Verify that high resolution system icons are used"
+                + " in JOptionPane on HiDPI displays.",
+                "1) Run the test on Retina display or enable the Quartz Debug"
+                + " and select the screen resolution with (HiDPI) label",
+                "2) Check that the error icon on the JOptionPane is smooth",
+                "If so, press PASS, else press FAIL."
+            };
+            Sysout.createDialogWithInstructions(instructions);
+
+        } else {
+            String[] instructions = {
+                "This test is not applicable to the current platform. Press PASS."
+            };
+            Sysout.createDialogWithInstructions(instructions);
+        }
+
+
+    }//End  init()
+
+    public void start() {
+        //Get things going.  Request focus, set size, et cetera
+        setSize(200, 200);
+        setVisible(true);
+        validate();
+        EventQueue.invokeLater(new Runnable() {
+
+            public void run() {
+                createAndShowGUI();
+            }
+        });
+    }// start()
+
+    //The rest of this class is the actions which perform the test...
+    //Use Sysout.println to communicate with the user NOT System.out!!
+    //Sysout.println ("Something Happened!");
+    private static void createAndShowGUI() {
+        JOptionPane.showMessageDialog(null,
+                "Icons should have high resolution.",
+                "High resolution icon test.",
+                JOptionPane.ERROR_MESSAGE);
+    }
+}// class BlockedWindowTest
+
+/* Place other classes related to the test after this line */
+/**
+ * **************************************************
+ * Standard Test Machinery DO NOT modify anything below -- it's a standard chunk
+ * of code whose purpose is to make user interaction uniform, and thereby make
+ * it simpler to read and understand someone else's test.
+ * **************************************************
+ */
+/**
+ * This is part of the standard test machinery. It creates a dialog (with the
+ * instructions), and is the interface for sending text messages to the user. To
+ * print the instructions, send an array of strings to Sysout.createDialog
+ * WithInstructions method. Put one line of instructions per array entry. To
+ * display a message for the tester to see, simply call Sysout.println with the
+ * string to be displayed. This mimics System.out.println but works within the
+ * test harness as well as standalone.
+ */
+class Sysout {
+
+    private static TestDialog dialog;
+
+    public static void createDialogWithInstructions(String[] instructions) {
+        dialog = new TestDialog(new Frame(), "Instructions");
+        dialog.printInstructions(instructions);
+        dialog.setVisible(true);
+        println("Any messages for the tester will display here.");
+    }
+
+    public static void createDialog() {
+        dialog = new TestDialog(new Frame(), "Instructions");
+        String[] defInstr = {"Instructions will appear here. ", ""};
+        dialog.printInstructions(defInstr);
+        dialog.setVisible(true);
+        println("Any messages for the tester will display here.");
+    }
+
+    public static void printInstructions(String[] instructions) {
+        dialog.printInstructions(instructions);
+    }
+
+    public static void println(String messageIn) {
+        dialog.displayMessage(messageIn);
+    }
+}// Sysout  class
+
+/**
+ * This is part of the standard test machinery. It provides a place for the test
+ * instructions to be displayed, and a place for interactive messages to the
+ * user to be displayed. To have the test instructions displayed, see Sysout. To
+ * have a message to the user be displayed, see Sysout. Do not call anything in
+ * this dialog directly.
+ */
+class TestDialog extends Dialog {
+
+    TextArea instructionsText;
+    TextArea messageText;
+    int maxStringLength = 80;
+
+    //DO NOT call this directly, go through Sysout
+    public TestDialog(Frame frame, String name) {
+        super(frame, name);
+        int scrollBoth = TextArea.SCROLLBARS_BOTH;
+        instructionsText = new TextArea("", 15, maxStringLength, scrollBoth);
+        add("North", instructionsText);
+
+        messageText = new TextArea("", 5, maxStringLength, scrollBoth);
+        add("Center", messageText);
+
+        pack();
+
+        setVisible(true);
+    }// TestDialog()
+
+    //DO NOT call this directly, go through Sysout
+    public void printInstructions(String[] instructions) {
+        //Clear out any current instructions
+        instructionsText.setText("");
+
+        //Go down array of instruction strings
+
+        String printStr, remainingStr;
+        for (int i = 0; i < instructions.length; i++) {
+            //chop up each into pieces maxSringLength long
+            remainingStr = instructions[ i];
+            while (remainingStr.length() > 0) {
+                //if longer than max then chop off first max chars to print
+                if (remainingStr.length() >= maxStringLength) {
+                    //Try to chop on a word boundary
+                    int posOfSpace = remainingStr.lastIndexOf(' ', maxStringLength - 1);
+
+                    if (posOfSpace <= 0) {
+                        posOfSpace = maxStringLength - 1;
+                    }
+
+                    printStr = remainingStr.substring(0, posOfSpace + 1);
+                    remainingStr = remainingStr.substring(posOfSpace + 1);
+                } //else just print
+                else {
+                    printStr = remainingStr;
+                    remainingStr = "";
+                }
+
+                instructionsText.append(printStr + "\n");
+
+            }// while
+
+        }// for
+
+    }//printInstructions()
+
+    //DO NOT call this directly, go through Sysout
+    public void displayMessage(String messageIn) {
+        messageText.append(messageIn + "\n");
+        System.out.println(messageIn);
+    }
+}// TestDialog  class
--- a/jdk/test/javax/swing/JPopupMenu/6694823/bug6694823.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/javax/swing/JPopupMenu/6694823/bug6694823.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2014 Oracle and/or its affiliates. All rights reserved.
  * 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,7 +34,7 @@
 import java.awt.*;
 import sun.awt.SunToolkit;
 import java.security.Permission;
-import sun.security.util.SecurityConstants;
+import sun.awt.AWTPermissions;
 
 public class bug6694823 {
     private static JFrame frame;
@@ -61,7 +61,8 @@
 
         System.setSecurityManager(new SecurityManager(){
 
-            private String allowsAlwaysOnTopPermission = SecurityConstants.AWT.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION.getName();
+            private String allowsAlwaysOnTopPermission =
+                AWTPermissions.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION.getName();
 
             @Override
             public void checkPermission(Permission perm) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JPopupMenu/7154841/bug7154841.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,121 @@
+/*
+ * 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 7154841
+  @summary JPopupMenu is overlapped by a Dock on Mac OS X
+  @author Petr Pchelko
+ */
+
+import sun.awt.OSInfo;
+import sun.awt.SunToolkit;
+
+import java.awt.*;
+import javax.swing.*;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseMotionAdapter;
+import java.util.concurrent.atomic.AtomicReference;
+
+public class bug7154841 {
+
+    private static final int STEP = 10;
+
+    private static volatile boolean passed = false;
+    private static JFrame frame;
+    private static JPopupMenu popupMenu;
+    private static AtomicReference<Rectangle> screenBounds = new AtomicReference<>();
+
+    private static void initAndShowUI() {
+        popupMenu = new JPopupMenu();
+        for (int i = 0; i < 100; i++) {
+            JRadioButtonMenuItem item = new JRadioButtonMenuItem(" Test " + i);
+            item.addMouseMotionListener(new MouseMotionAdapter() {
+                @Override
+                public void mouseMoved(MouseEvent e) {
+                    passed = true;
+                }
+            });
+            popupMenu.add(item);
+        }
+
+        frame = new JFrame();
+        screenBounds.set(getScreenBounds());
+        frame.setBounds(screenBounds.get());
+        frame.setVisible(true);
+    }
+
+    public static void main(String[] args) throws Exception {
+        if (OSInfo.getOSType() != OSInfo.OSType.MACOSX) {
+            return; // Test only for Mac OS X
+        }
+
+        try {
+            Robot r = new Robot();
+            r.setAutoDelay(100);
+            r.setAutoWaitForIdle(true);
+            r.mouseMove(0, 0);
+
+            SwingUtilities.invokeAndWait(bug7154841::initAndShowUI);
+
+            sleep();
+
+            SwingUtilities.invokeAndWait(() -> {
+                popupMenu.show(frame, frame.getX() + frame.getWidth() / 2, frame.getY() + frame.getHeight() / 2);
+            });
+
+            sleep();
+
+            int y = (int)screenBounds.get().getY() + (int)screenBounds.get().getHeight() - 10;
+            int center = (int)(screenBounds.get().getX() + screenBounds.get().getWidth() / 2);
+            for (int x = center - 10 * STEP; x < center + 10 * STEP; x += STEP) {
+                r.mouseMove(x, y);
+            }
+
+            if (!passed) {
+                throw new RuntimeException("Failed: no mouse events on the popup menu");
+            }
+        } finally {
+            SwingUtilities.invokeLater(() -> {
+                if (frame != null) {
+                    frame.dispose();
+                }
+            });
+        }
+    }
+
+    public static Rectangle getScreenBounds() {
+        return GraphicsEnvironment
+                .getLocalGraphicsEnvironment()
+                .getDefaultScreenDevice()
+                .getDefaultConfiguration()
+                .getBounds();
+    }
+
+    private static void sleep() {
+        ((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
+        try {
+            Thread.sleep(200);
+        } catch (InterruptedException ignored) { }
+    }
+}
--- a/jdk/test/javax/swing/JPopupMenu/7160604/bug7160604.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/javax/swing/JPopupMenu/7160604/bug7160604.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,16 +38,24 @@
 import javax.swing.JPopupMenu;
 import javax.swing.JWindow;
 import javax.swing.SwingUtilities;
-import java.awt.BorderLayout;
-import java.awt.Color;
+import java.awt.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
+import static java.awt.GraphicsDevice.WindowTranslucency.*;
 
 public class bug7160604 extends JApplet {
 
     public void init() {
         SwingUtilities.invokeLater(() -> {
+            if (!GraphicsEnvironment
+                    .getLocalGraphicsEnvironment()
+                    .getDefaultScreenDevice()
+                    .isWindowTranslucencySupported(PERPIXEL_TRANSLUCENT)) {
+                // Tested translucency is not supported. Test passed
+                return;
+            }
+
             final JWindow window = new JWindow();
             window.setLocation(200, 200);
             window.setSize(300, 300);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JSpinner/8008657/bug8008657.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.awt.ComponentOrientation;
+import java.awt.Toolkit;
+import java.util.Calendar;
+import java.util.Date;
+import javax.swing.JFrame;
+import javax.swing.JSpinner;
+import javax.swing.JTextField;
+import javax.swing.SpinnerDateModel;
+import javax.swing.SpinnerModel;
+import javax.swing.SpinnerNumberModel;
+import javax.swing.SwingUtilities;
+import sun.awt.SunToolkit;
+
+/**
+ * @test
+ * @bug 8008657
+ * @author Alexander Scherbatiy
+ * @summary JSpinner setComponentOrientation doesn't affect on text orientation
+ * @run main bug8008657
+ */
+public class bug8008657 {
+
+    private static SunToolkit toolkit;
+    private static JSpinner spinner;
+
+    public static void main(String[] args) throws Exception {
+
+        toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
+
+        SwingUtilities.invokeAndWait(() -> {
+            createDateSpinner();
+            createAndShowUI();
+        });
+
+        toolkit.realSync();
+        testSpinner(false);
+
+        SwingUtilities.invokeAndWait(() -> {
+            createNumberSpinner();
+            createAndShowUI();
+        });
+
+        toolkit.realSync();
+        testSpinner(true);
+    }
+
+    static void testSpinner(boolean checkHorizontalAligment)
+            throws Exception {
+
+        SwingUtilities.invokeAndWait(() -> {
+            spinner.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
+        });
+        toolkit.realSync();
+
+        SwingUtilities.invokeAndWait(() -> {
+
+            JTextField textField = getTextField();
+            if (!ComponentOrientation.RIGHT_TO_LEFT.equals(
+                    textField.getComponentOrientation())) {
+                throw new RuntimeException("Wrong orientation!");
+            }
+
+            if (checkHorizontalAligment
+                    && textField.getHorizontalAlignment() != JTextField.LEFT) {
+                throw new RuntimeException("Wrong horizontal aligment!");
+            }
+
+            spinner.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
+        });
+
+        toolkit.realSync();
+
+        SwingUtilities.invokeAndWait(() -> {
+            JTextField textField = getTextField();
+            if (!ComponentOrientation.LEFT_TO_RIGHT.equals(
+                    textField.getComponentOrientation())) {
+                throw new RuntimeException("Wrong orientation!");
+            }
+
+            if (checkHorizontalAligment
+                    && textField.getHorizontalAlignment() != JTextField.RIGHT) {
+                throw new RuntimeException("Wrong horizontal aligment!");
+            }
+
+            spinner.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
+        });
+    }
+
+    static JTextField getTextField() {
+        return ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
+    }
+
+    static String getOrientation(ComponentOrientation orientation) {
+        return orientation == ComponentOrientation.LEFT_TO_RIGHT ? "LEFT_TO_RIGHT" : "RIGHT_TO_LEFT";
+    }
+
+    static void createDateSpinner() {
+        Calendar calendar = Calendar.getInstance();
+        Date initDate = calendar.getTime();
+        calendar.add(Calendar.YEAR, -1);
+        Date earliestDate = calendar.getTime();
+        calendar.add(Calendar.YEAR, 1);
+        Date latestDate = calendar.getTime();
+        SpinnerModel dateModel = new SpinnerDateModel(initDate,
+                earliestDate,
+                latestDate,
+                Calendar.YEAR);
+        spinner = new JSpinner();
+        spinner.setModel(dateModel);
+    }
+
+    static void createNumberSpinner() {
+        Calendar calendar = Calendar.getInstance();
+        calendar.add(Calendar.YEAR, -1);
+        calendar.add(Calendar.YEAR, 1);
+        int currentYear = calendar.get(Calendar.YEAR);
+        SpinnerModel yearModel = new SpinnerNumberModel(currentYear, //initial value
+                currentYear - 1, //min
+                currentYear + 2, //max
+                1);                //step
+        spinner = new JSpinner();
+        spinner.setModel(yearModel);
+    }
+
+    static void createAndShowUI() {
+        JFrame frame = new JFrame("Test");
+        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+        frame.setSize(300, 100);
+        frame.getContentPane().add(spinner);
+        frame.setVisible(true);
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JTable/8031971/bug8031971.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.Date;
+import java.util.Hashtable;
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+import javax.swing.JTable;
+import javax.swing.SwingUtilities;
+
+/**
+ * @test
+ * @bug 8031971
+ * @author Alexander Scherbatiy
+ * @summary Use only public methods in the SwingLazyValue
+ * @run main bug8031971
+ */
+public class bug8031971 {
+
+    static Object[][] RENDERERS = {
+        {Object.class, "javax.swing.table.DefaultTableCellRenderer$UIResource"},
+        {Number.class, "javax.swing.JTable$NumberRenderer"},
+        {Float.class, "javax.swing.JTable$DoubleRenderer"},
+        {Double.class, "javax.swing.JTable$DoubleRenderer"},
+        {Date.class, "javax.swing.JTable$DateRenderer"},
+        {Icon.class, "javax.swing.JTable$IconRenderer"},
+        {ImageIcon.class, "javax.swing.JTable$IconRenderer"},
+        {Boolean.class, "javax.swing.JTable$BooleanRenderer"}
+    };
+
+    static Object[][] EDITORS = {
+        {Object.class, "javax.swing.JTable$GenericEditor"},
+        {Number.class, "javax.swing.JTable$NumberEditor"},
+        {Boolean.class, "javax.swing.JTable$BooleanEditor"}
+    };
+
+    public static void main(String[] args) throws Exception {
+
+        SwingUtilities.invokeAndWait(() -> {
+
+            TestTable table = new TestTable();
+            test(table.getDefaultRenderersByColumnClass(), RENDERERS);
+            test(table.getDefaultEditorsByColumnClass(), EDITORS);
+        });
+    }
+
+    static void test(Hashtable table, Object[][] values) {
+        for (int i = 0; i < values.length; i++) {
+            test(table.get(values[i][0]), (String) values[i][1]);
+        }
+    }
+
+    static void test(Object obj, String className) {
+        if (!obj.getClass().getCanonicalName().equals(className.replace('$', '.'))) {
+            throw new RuntimeException("Wrong value!");
+        }
+    }
+
+    static class TestTable extends JTable {
+
+        Hashtable getDefaultRenderersByColumnClass() {
+            return defaultRenderersByColumnClass;
+        }
+
+        Hashtable getDefaultEditorsByColumnClass() {
+            return defaultEditorsByColumnClass;
+        }
+    }
+}
--- a/jdk/test/javax/swing/text/AbstractDocument/7146146/bug7146146.java	Tue Mar 25 12:31:49 2014 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,77 +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.
- */
-
-/* @test
-   @bug 7146146
-   @summary Deadlock between subclass of AbstractDocument and UndoManager
-   @author Pavel Porvatov
-*/
-
-import javax.swing.text.BadLocationException;
-import javax.swing.text.PlainDocument;
-import javax.swing.text.StringContent;
-import javax.swing.undo.UndoManager;
-
-public class bug7146146 {
-    public static void main(String[] args) throws Exception {
-        for (int i = 0; i < 1000; i++) {
-            System.out.print("Iteration " + i);
-
-            test();
-
-            System.out.print(" passed");
-        }
-    }
-
-    private static void test() throws Exception {
-        final PlainDocument doc = new PlainDocument(new StringContent());
-        final UndoManager undoManager = new UndoManager();
-
-        doc.addUndoableEditListener(undoManager);
-        doc.insertString(0, "<Test 1>", null);
-
-        Thread t1 = new Thread("Thread 1") {
-            @Override
-            public void run() {
-                try {
-                    doc.insertString(0, "<Test 2>", null);
-                } catch (BadLocationException e) {
-                    throw new RuntimeException(e);
-                }
-            }
-        };
-
-        Thread t2 = new Thread("Thread 2") {
-            @Override
-            public void run() {
-                undoManager.undo();
-            }
-        };
-
-        t1.start();
-        t2.start();
-
-        t1.join();
-        t2.join();
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/text/AbstractDocument/8030118/Test8030118.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,83 @@
+/*
+ * 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 javax.swing.event.DocumentEvent;
+import javax.swing.event.DocumentListener;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.PlainDocument;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/*
+ * @test
+ * @bug 8030118
+ * @summary Tests that AbstractDocument cannot be modified from another thread
+ * @author Sergey Malenkov
+ */
+
+public class Test8030118 implements DocumentListener, Runnable {
+    private final CountDownLatch latch = new CountDownLatch(1);
+    private final PlainDocument doc = new PlainDocument();
+
+    private Test8030118(String string) throws Exception {
+        this.doc.addDocumentListener(this);
+        this.doc.insertString(0, string, null);
+    }
+
+    @Override
+    public void run() {
+        try {
+            this.doc.remove(0, this.doc.getLength());
+        } catch (BadLocationException exception) {
+            throw new Error("unexpected", exception);
+        }
+        this.latch.countDown();
+    }
+
+    @Override
+    public void insertUpdate(DocumentEvent event) {
+        new Thread(this).start();
+        try {
+            this.latch.await(10, TimeUnit.SECONDS);
+        } catch (InterruptedException exception) {
+            throw new Error("unexpected", exception);
+        }
+        try {
+            event.getDocument().getText(event.getOffset(), event.getLength());
+        } catch (BadLocationException exception) {
+            throw new Error("concurrent modification", exception);
+        }
+    }
+
+    @Override
+    public void removeUpdate(DocumentEvent event) {
+    }
+
+    @Override
+    public void changedUpdate(DocumentEvent event) {
+    }
+
+    public static void main(String[] args) throws Exception {
+        new Test8030118("string");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/text/html/parser/Parser/8028616/bug8028616.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8028616
+ * @summary Tests correct parsing of the text with leading slash (/)
+ * @author Dmitry Markov
+ */
+
+import javax.swing.text.html.HTMLDocument;
+import javax.swing.text.html.HTMLEditorKit;
+import java.io.StringReader;
+
+public class bug8028616 {
+    private static final String text = "/ at start is bad";
+    private static Object lock = new Object();
+    private static boolean isCallbackInvoked = false;
+    private static Exception exception = null;
+
+    public static void main(String[] args) throws Exception {
+        ParserCB cb = new ParserCB();
+        HTMLEditorKit htmlKit = new HTMLEditorKit();
+        HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
+
+        htmlDoc.getParser().parse(new StringReader(text), cb, true);
+
+        synchronized (lock) {
+            if (!isCallbackInvoked) {
+                lock.wait(5000);
+            }
+        }
+
+        if (!isCallbackInvoked) {
+            throw new RuntimeException("Test Failed: ParserCallback.handleText() is not invoked for text - " + text);
+        }
+
+        if (exception != null) {
+            throw exception;
+        }
+    }
+
+    private static class ParserCB extends HTMLEditorKit.ParserCallback {
+        @Override
+        public void handleText(char[] data, int pos) {
+            synchronized (lock) {
+                if (!text.equals(new String(data)) || pos != 0) {
+                    exception = new RuntimeException(
+                        "Test Failed: the data passed to ParserCallback.handleText() does not meet the expectation");
+                }
+                isCallbackInvoked = true;
+                lock.notifyAll();
+            }
+        }
+    }
+}
+
--- a/jdk/test/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxy.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxy.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -98,6 +98,7 @@
             ServerSocketFactory ssf =
                 PostThruProxy.getServerSocketFactory(useSSL);
             ServerSocket ss = ssf.createServerSocket(serverPort);
+            ss.setSoTimeout(30000);  // 30 seconds
             serverPort = ss.getLocalPort();
             new TestServer(ss);
         } catch (Exception e) {
--- a/jdk/test/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxyWithAuth.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/net/www/protocol/https/HttpsURLConnection/PostThruProxyWithAuth.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -100,6 +100,7 @@
             ServerSocketFactory ssf =
                 PostThruProxyWithAuth.getServerSocketFactory(useSSL);
             ServerSocket ss = ssf.createServerSocket(serverPort);
+            ss.setSoTimeout(30000);  // 30 seconds
             serverPort = ss.getLocalPort();
             new TestServer(ss);
         } catch (Exception e) {
--- a/jdk/test/sun/security/krb5/auto/BadKdc.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/krb5/auto/BadKdc.java	Wed Jul 05 19:33:51 2017 +0200
@@ -39,7 +39,29 @@
     //                                               ^ kdc#         ^ timeout
     static final Pattern re = Pattern.compile(
             ">>> KDCCommunication: kdc=kdc.rabbit.hole UDP:(\\d)...., " +
-            "timeout=(\\d)000,");
+            "timeout=(\\d+),");
+
+    // Ratio for timeout values of all timeout tests. Not final so that
+    // each test can choose their own.
+    static float ratio = 2f;
+
+    static void setRatio(float ratio) {
+        BadKdc.ratio = ratio;
+    }
+
+    static float getRatio() {
+        return ratio;
+    }
+
+    // Gets real timeout value. This method is called when writing krb5.conf
+    static int toReal(int from) {
+        return (int)(from * ratio + .5);
+    }
+
+    // De-ratio a millisecond value to second
+    static int toSymbolicSec(int from) {
+        return (int)(from / ratio / 1000f + 0.5);
+    }
 
     /*
      * There are several cases this test fails:
@@ -101,7 +123,7 @@
 
         fw.write("[libdefaults]\n" +
                 "default_realm = " + OneKDC.REALM + "\n" +
-                "kdc_timeout = 2000\n");
+                "kdc_timeout = " + toReal(2000) + "\n");
         fw.write("[realms]\n" + OneKDC.REALM + " = {\n" +
                 "kdc = " + OneKDC.KDCHOST + ":" + p1 + "\n" +
                 "kdc = " + OneKDC.KDCHOST + ":" + p2 + "\n" +
@@ -184,7 +206,8 @@
             Matcher m = re.matcher(line);
             if (m.find()) {
                 System.out.println(line);
-                sb.append(m.group(1)).append(m.group(2));
+                sb.append(m.group(1))
+                        .append(toSymbolicSec(Integer.parseInt(m.group(2))));
             }
         }
         if (failed) sb.append('-');
--- a/jdk/test/sun/security/krb5/auto/BadKdc1.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/krb5/auto/BadKdc1.java	Wed Jul 05 19:33:51 2017 +0200
@@ -28,14 +28,21 @@
  * @summary krb5 should not try to access unavailable kdc too often
  */
 
-import java.io.*;
 import java.security.Security;
 
 public class BadKdc1 {
 
    public static void main(String[] args)
            throws Exception {
-       Security.setProperty("krb5.kdc.bad.policy", "tryLess");
+
+       // 5 sec is default timeout for tryLess
+       if (BadKdc.getRatio() > 2.5) {
+           Security.setProperty("krb5.kdc.bad.policy",
+                   "tryLess:1," + BadKdc.toReal(2000));
+       } else {
+           Security.setProperty("krb5.kdc.bad.policy", "tryLess");
+       }
+
        BadKdc.go(
                "121212222222(32){1,2}1222(32){1,2}", // 1 2
                // The above line means try kdc1 for 2 seconds then kdc1
--- a/jdk/test/sun/security/krb5/auto/BadKdc2.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/krb5/auto/BadKdc2.java	Wed Jul 05 19:33:51 2017 +0200
@@ -35,7 +35,12 @@
 
     public static void main(String[] args)
             throws Exception {
-        Security.setProperty("krb5.kdc.bad.policy", "tryLess:2,1000");
+
+        // 1 sec is too short.
+        BadKdc.setRatio(3.0f);
+
+        Security.setProperty(
+                "krb5.kdc.bad.policy", "tryLess:2," + BadKdc.toReal(1000));
         BadKdc.go(
                 "121212222222(32){1,2}11112121(32){1,2}", // 1 2
                 "11112121(32){1,2}11112121(32){1,2}", // 1 2
--- a/jdk/test/sun/security/krb5/auto/MaxRetries.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/krb5/auto/MaxRetries.java	Wed Jul 05 19:33:51 2017 +0200
@@ -60,7 +60,7 @@
         test1(5000, 2);         // 2 2
 
         // For tryLess
-        Security.setProperty("krb5.kdc.bad.policy", "tryless");
+        Security.setProperty("krb5.kdc.bad.policy", "tryless:1," + BadKdc.toReal(5000));
         rewriteMaxRetries(4);
         test1(4000, 7);         // 1 1 1 1 2 1 2
         test1(4000, 4);         // 1 2 1 2
@@ -94,7 +94,7 @@
      * @param count the expected total try
      */
     private static void test1(int timeout, int count) throws Exception {
-        String timeoutTag = "timeout=" + timeout;
+        String timeoutTag = "timeout=" + BadKdc.toReal(timeout);
         ByteArrayOutputStream bo = new ByteArrayOutputStream();
         PrintStream oldout = System.out;
         System.setOut(new PrintStream(bo));
@@ -192,12 +192,12 @@
             if (s.startsWith("[realms]")) {
                 // Reconfig global setting
                 fw.write("max_retries = 2\n");
-                fw.write("kdc_timeout = 5000\n");
+                fw.write("kdc_timeout = " + BadKdc.toReal(5000) + "\n");
             } else if (s.trim().startsWith("kdc = ")) {
                 if (value != -1) {
                     // Reconfig for realm
                     fw.write("    max_retries = " + value + "\n");
-                    fw.write("    kdc_timeout = " + (value*1000) + "\n");
+                    fw.write("    kdc_timeout = " + BadKdc.toReal(value*1000) + "\n");
                 }
                 // Add a bad KDC as the first candidate
                 fw.write("    kdc = localhost:33333\n");
--- a/jdk/test/sun/security/krb5/auto/TcpTimeout.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/krb5/auto/TcpTimeout.java	Wed Jul 05 19:33:51 2017 +0200
@@ -63,7 +63,7 @@
                     "udp_preference_limit = 1\n" +
                     "max_retries = 2\n" +
                     "default_realm = " + OneKDC.REALM + "\n" +
-                    "kdc_timeout = 5000\n");
+                    "kdc_timeout = " + BadKdc.toReal(5000) + "\n");
             fw.write("[realms]\n" + OneKDC.REALM + " = {\n" +
                     "kdc = " + OneKDC.KDCHOST + ":" + p1 + "\n" +
                     "kdc = " + OneKDC.KDCHOST + ":" + p2 + "\n" +
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/krb5/config/ExtraLines.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8036971
+ * @compile -XDignore.symbol.file ExtraLines.java
+ * @run main/othervm ExtraLines
+ * @summary krb5.conf does not accept directive lines before the first section
+ */
+
+import sun.security.krb5.Config;
+import java.nio.file.*;
+import java.util.Objects;
+
+public class ExtraLines {
+    public static void main(String[] args) throws Exception {
+        Path base = Paths.get("krb5.conf");
+        Path include = Paths.get("included.conf");
+        String baseConf = "include " + include.toAbsolutePath().toString()
+                + "\n[x]\na = b\n";
+        String includeConf = "[y]\nc = d\n";
+        Files.write(include, includeConf.getBytes());
+        Files.write(base, baseConf.getBytes());
+
+        System.setProperty("java.security.krb5.conf", base.toString());
+        Config.refresh();
+
+        if (!Objects.equals(Config.getInstance().get("x", "a"), "b")) {
+            throw new Exception("Failed");
+        }
+    }
+}
--- a/jdk/test/sun/security/pkcs11/fips/ClientJSSEServerJSSE.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/pkcs11/fips/ClientJSSEServerJSSE.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,13 @@
  * @bug 6313675 6323647
  * @summary Verify that all ciphersuites work in FIPS mode
  * @library ..
- * @ignore JSSE supported cipher suites are changed with CR 6916074,
- *     need to update this test case in JDK 7 soon
- * @run main/othervm ClientJSSEServerJSSE
  * @author Andreas Sterbenz
+ * @run main/manual ClientJSSEServerJSSE
+ */
+
+/*
+ * JSSE supported cipher suites are changed with CR 6916074,
+ * need to update this test case in JDK 7 soon
  */
 
 import java.security.*;
--- a/jdk/test/sun/security/provider/PolicyFile/GrantAllPermToExtWhenNoPolicy.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/provider/PolicyFile/GrantAllPermToExtWhenNoPolicy.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,8 +23,7 @@
 
 /*
  * @test
- * @bug 4231980
- * @bug 4233913
+ * @bug 4231980 4233913
  * @summary Make sure that when no system policy and user policy files exist,
  * the built-in default policy will be used, which - amongst other things -
  * grants standard extensions the AllPermission. This regression is for 2
@@ -34,7 +33,7 @@
  *
  * @build SomeExtensionClass
  * @build GrantAllPermToExtWhenNoPolicy
- * @ignore shell GrantAllPermToExtWhenNoPolicy.sh
+ * @run shell/manual GrantAllPermToExtWhenNoPolicy.sh
  */
 
 import java.security.*;
--- a/jdk/test/sun/security/provider/PolicyParser/ExtDirs.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/provider/PolicyParser/ExtDirs.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,13 +26,16 @@
  * @bug 4215035
  * @summary standard extensions path is hard-coded in default
  *      system policy file
- * @ignore run this by hand
- *
- *      java    -Djava.security.manager \
- *              -Djava.ext.dirs=./ExtDirsA:./ExtDirsB \
- *              -Djava.security.policy==./ExtDirs.policy \
- *              -Djava.security.debug=parser \
- *              ExtDirs
+ * @run main/manual ExtDirs
+ */
+
+/*
+ * Run this test manually with:
+ * java    -Djava.security.manager \
+ *         -Djava.ext.dirs=./ExtDirsA:./ExtDirsB \
+ *         -Djava.security.policy==./ExtDirs.policy \
+ *         -Djava.security.debug=parser \
+ *         ExtDirs
  */
 
 public class ExtDirs {
--- a/jdk/test/sun/security/provider/PolicyParser/ExtDirsChange.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/provider/PolicyParser/ExtDirsChange.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,16 +26,19 @@
  * @bug 4993819
  * @summary standard extensions path is hard-coded in default
  *      system policy file
- * @ignore run this by hand
- *
- *      javac ExtDirChange
- *      rm ExtDirsA*.class ExtDirsB*.class
- *      java    -Djava.security.manager \
- *              -Dtest.src=. \
- *              -Djava.security.policy=ExtDirsChange.policy \
- *              -Djava.security.debug=parser \
- *              -cp ExtDirsA/a.jar:ExtDirsB/b.jar:. \
- *              ExtDirsChange
+ * @run main/manual ExtDirsChange
+ */
+
+/*
+ * Run this test manually with:
+ * javac ExtDirChange
+ * rm ExtDirsA*.class ExtDirsB*.class
+ * java    -Djava.security.manager \
+ *         -Dtest.src=. \
+ *         -Djava.security.policy=ExtDirsChange.policy \
+ *         -Djava.security.debug=parser \
+ *         -cp ExtDirsA/a.jar:ExtDirsB/b.jar:. \
+ *         ExtDirsChange
  */
 
 import java.io.File;
--- a/jdk/test/sun/security/provider/PolicyParser/ExtDirsDefaultPolicy.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/provider/PolicyParser/ExtDirsDefaultPolicy.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,22 +26,25 @@
  * @bug 4993819
  * @summary standard extensions path is hard-coded in default
  *      system policy file
- * @ignore run this by hand
- *
- *      java    -Djava.security.manager \
- *              -Djava.ext.dirs=./ExtDirsA:./ExtDirsB \
- *              -Djava.security.debug=parser \
- *              ExtDirsDefaultPolicy
+ * @run main/manual ExtDirsDefaultPolicy
+ */
+
+/*
+ * Run this test manually with:
+ * java    -Djava.security.manager \
+ *         -Djava.ext.dirs=./ExtDirsA:./ExtDirsB \
+ *         -Djava.security.debug=parser \
+ *         ExtDirsDefaultPolicy
  *
  * To test other varients of the ${{java.ext.dirs}} protocol, remove
  * the grant statement for java.ext.dirs in $JAVA_HOME/lib/security/java.policy
  * and then run against the 3 different policy files.
  *
- *      java    -Djava.security.manager \
- *              -Djava.ext.dirs=./ExtDirsA:./ExtDirsB \
- *              -Djava.security.debug=parser \
- *              -Djava.security.policy=ExtDirs{1,2,3}.policy \
- *              ExtDirsDefaultPolicy
+ * java    -Djava.security.manager \
+ *         -Djava.ext.dirs=./ExtDirsA:./ExtDirsB \
+ *         -Djava.security.debug=parser \
+ *         -Djava.security.policy=ExtDirs{1,2,3}.policy \
+ *         ExtDirsDefaultPolicy
  */
 
 public class ExtDirsDefaultPolicy {
--- a/jdk/test/sun/security/provider/PolicyParser/PrincipalExpansionError.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/provider/PolicyParser/PrincipalExpansionError.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,56 +25,54 @@
  * @test
  * @bug 4373996
  * @summary parser incorrectly ignores a principal if the principal name
- *      expands to nothing.  this test is a bit complicated.
- *
- *      1) PrincipalExpansionError.java
- *              the test itself.  this test creates a Subject with a
- *              SolarisPrincipal("TestPrincipal") and calls doAs
- *              with a PrincipalExpansionErrorAction.
- *
- *      2) PrincipalExpansionErrorAction
- *              this action tries to read the file, /testfile
+ *      expands to nothing.
+ * @run main/manual PrincipalExpansionError
+ */
+
+/*
+ * This test is a bit complicated.
+ * 1) PrincipalExpansionError.java
+ *         the test itself.  this test creates a Subject with a
+ *         SolarisPrincipal("TestPrincipal") and calls doAs
+ *         with a PrincipalExpansionErrorAction.
+ * 2) PrincipalExpansionErrorAction
+ *         this action tries to read the file, /testfile
+ * 3) to run the test:
+ *         a) jtreg -verbose:all -testjdk:<your_jdk>/build/sparc
+ *                 PrincipalExpansionError.java
+ *         b) PrincipalExpansionError is compiled and put into
+ *                 the "test.classes" directory
+ *         c) PrincipalExpansionErrorAction is compiled and put into
+ *                 the "test.classes"/apackage directory
+ *                 (since it belongs to the 'apackage' package
+ *         d) the PrincipalExpansionError shell script moves
+ *                 test.classes/apackage to test.src/apackage.
+ *                 this guarantees that the test will run
+ *                 with codebase test.classes, and the action
+ *                 will run with codebase test.src.
+ *         e) the test is executed.  permissions to read the file,
+ *                 /testfile, were granted to the PrincipalExpansionError.
+ *                 the policy entry for PrincipalExpansionErrorAction
+ *                 running as SolarisPrincipal("TestPrincipal")
+ *                 was also granted the file permission,
+ *                 but it has a bogus second SolarisPrincipal with
+ *                 a name that can't be property-expanded.
  *
- *      3) to run the test:
- *              a) jtreg -verbose:all -testjdk:<your_jdk>/build/sparc
- *                      PrincipalExpansionError.java
- *              b) PrincipalExpansionError is compiled and put into
- *                      the "test.classes" directory
- *              c) PrincipalExpansionErrorAction is compiled and put into
- *                      the "test.classes"/apackage directory
- *                      (since it belongs to the 'apackage' package
- *              d) the PrincipalExpansionError shell script moves
- *                      test.classes/apackage to test.src/apackage.
- *                      this guarantees that the test will run
- *                      with codebase test.classes, and the action
- *                      will run with codebase test.src.
- *              e) the test is executed.  permissions to read the file,
- *                      /testfile, were granted to the PrincipalExpansionError.
- *                      the policy entry for PrincipalExpansionErrorAction
- *                      running as SolarisPrincipal("TestPrincipal")
- *                      was also granted the file permission,
- *                      but it has a bogus second SolarisPrincipal with
- *                      a name that can't be property-expanded.
- *
- *                      the old behavior of the code would ignore the
- *                      bogus entry and incorrectly grants the file permission
- *                      to SolarisPrincipal("TestPrincipal").
- *                      the new behavior correctly ignores the entire
- *                      policy entry.
- *                      Please note that the jtreg needs to be granted
- *                      allpermissions for this test to succeed. If the codebase
- *                      for jtreg changes, the PrincipalExpansionError.policy
- *                      needs to be updated.
- *
- *              f) original @ tags:
- *                      compile PrincipalExpansionErrorAction.java
- *                      run shell PrincipalExpansionError.sh
- *                      run main/othervm/policy=PrincipalExpansionError.policy
- *                              -Djava.security.debug=access,domain,failure
- *                              PrincipalExpansionError
- *
- * @ignore unable to rely on location or javatest.jar
- *              (so we can grant it AllPermission)
+ *                 the old behavior of the code would ignore the
+ *                 bogus entry and incorrectly grants the file permission
+ *                 to SolarisPrincipal("TestPrincipal").
+ *                 the new behavior correctly ignores the entire
+ *                 policy entry.
+ *                 Please note that the jtreg needs to be granted
+ *                 allpermissions for this test to succeed. If the codebase
+ *                 for jtreg changes, the PrincipalExpansionError.policy
+ *                 needs to be updated.
+ *         f) original @ tags:
+ *                 compile PrincipalExpansionErrorAction.java
+ *                 run shell PrincipalExpansionError.sh
+ *                 run main/othervm/policy=PrincipalExpansionError.policy
+ *                         -Djava.security.debug=access,domain,failure
+ *                         PrincipalExpansionError
  */
 
 import javax.security.auth.*;
--- a/jdk/test/sun/security/provider/X509Factory/BigCRL.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/provider/X509Factory/BigCRL.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
     public static void main(String[] args) throws Exception {
         int n = 500000;
         String ks = System.getProperty("test.src", ".")
-                + "/../../ssl/etc/keystore";
+                + "/../../../../javax/net/ssl/etc/keystore";
         String pass = "passphrase";
         String alias = "dummy";
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/provider/certpath/PKIXCertPathValidator/Validity.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,134 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8021804
+ * @summary CertPath should validate even if the validity period of the
+ *          root cert does not include the validity period of a subordinate
+ *          cert.
+ */
+
+import java.io.ByteArrayInputStream;
+import java.security.cert.*;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Set;
+
+public class Validity {
+
+    /*
+     * Subject: OU=TestOrg, CN=TestCA
+     * Issuer: OU=TestOrg, CN=TestCA
+     * Validity
+     *     Not Before: Feb 26 21:33:55 2014 GMT
+           Not After : Feb 26 21:33:55 2024 GMT
+     * Version 1
+     */
+    static String CACertStr =
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIIBvTCCASYCCQCQRiTo4lBCFjANBgkqhkiG9w0BAQUFADAjMRAwDgYDVQQLDAdU\n" +
+        "ZXN0T3JnMQ8wDQYDVQQDDAZUZXN0Q0EwHhcNMTQwMjI2MjEzMzU1WhcNMjQwMjI2\n" +
+        "MjEzMzU1WjAjMRAwDgYDVQQLDAdUZXN0T3JnMQ8wDQYDVQQDDAZUZXN0Q0EwgZ8w\n" +
+        "DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOtKS4ZrsM3ansd61ZxitcrN0w184I+A\n" +
+        "z0kyrSP1eMtlam+cC2U91NpTz11FYV4XUfBhqqxaXW043AWTUer8pS90Pt4sCrUX\n" +
+        "COx1+QA1M3ZhbZ4sTM7XQ90JbGaBJ/sEza9mlQP7hQ2yQO/hATKbP6J5qvgG2sT2\n" +
+        "S2WYjEgwNwmFAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAQ/CXEpnx2WY4LJtv4jwE\n" +
+        "4jIVirur3pdzV5oBhPyqqHMsyhQBkukCfX7uD7L5wN1+xuM81DfANpIxlnUfybp5\n" +
+        "CpjcmktLpmyK4kJ6XnSd2blbLOIpsr9x6FqxPxpVDlyw/ySHYrIG/GZdsLHgmzGn\n" +
+        "B06jeYzH8OLf879VxAxSsPc=\n" +
+        "-----END CERTIFICATE-----";
+
+    /*
+     * Subject: OU=TestOrg, CN=TestEE0
+     * Issuer: OU=TestOrg, CN=TestCA
+     * Validity
+     *     Not Before: Feb 26 22:55:12 2014 GMT
+     *     Not After : Feb 25 22:55:12 2025 GMT
+     * Version 1
+     */
+    static String EECertStr =
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIIBtjCCAR8CAQQwDQYJKoZIhvcNAQEFBQAwIzEQMA4GA1UECwwHVGVzdE9yZzEP\n" +
+        "MA0GA1UEAwwGVGVzdENBMB4XDTE0MDIyNjIyNTUxMloXDTI1MDIyNTIyNTUxMlow\n" +
+        "JDEQMA4GA1UECwwHVGVzdE9yZzEQMA4GA1UEAwwHVGVzdEVFMDCBnzANBgkqhkiG\n" +
+        "9w0BAQEFAAOBjQAwgYkCgYEAt8xz9W3ruCTHjSOtTX6cxsUZ0nRP6EavEfzgcOYh\n" +
+        "CXGA0gr+viSHq3c2vQBxiRny2hm5rLcqpPo+2OxZtw/ajxfyrV6d/r8YyQLBvyl3\n" +
+        "xdCZdOkG1DCM1oFAQDaSRt9wN5Zm5kyg7uMig5Y4L45fP9Yee4x6Xyh36qYbsR89\n" +
+        "rFMCAwEAATANBgkqhkiG9w0BAQUFAAOBgQDZrPqSo08va1m9TOWOztTuWilGdjK/\n" +
+        "2Ed2WXg8utIpy6uAV+NaOYtHQ7ULQBVRNmwg9nKghbVbh+E/xpoihjl1x7OXass4\n" +
+        "TbwXA5GKFIFpNtDvATQ/QQZoCuCzw1FW/mH0Q7UEQ/9/iJdDad6ebkapeMwtj/8B\n" +
+        "s2IZV7s85CEOXw==\n" +
+        "-----END CERTIFICATE-----";
+
+    public static void main(String[] args) throws Exception {
+
+        String[] certStrs = {EECertStr};
+        String[] trustedCertStrs = {CACertStr};
+        runTest(certStrs, trustedCertStrs);
+
+        System.out.println("Test passed.");
+    }
+
+    private static void runTest(String[] certStrs,
+                                String[] trustedCertStrs)
+            throws Exception {
+
+        CertificateFactory cf = CertificateFactory.getInstance("X509");
+
+        // Generate the CertPath from the certs named in certStrs
+        ArrayList<X509Certificate> certs = new ArrayList<>();
+        for (String certStr : certStrs) {
+            certs.add(generateCert(certStr, cf));
+        }
+        CertPath cp = cf.generateCertPath(certs);
+
+        // Generate the set of Trust Anchors from the certs named in
+        // trustedCertStrs
+        Set<TrustAnchor> trustAnchors = new HashSet<>();
+        for (String trustedCertStr : trustedCertStrs) {
+            TrustAnchor ta = new TrustAnchor(generateCert(trustedCertStr, cf),
+                                             null);
+            trustAnchors.add(ta);
+        }
+        PKIXParameters params = new PKIXParameters(trustAnchors);
+        params.setDate(new Date(114, 3, 1));   // 2014-03-01
+        params.setRevocationEnabled(false);
+
+        // Attempt to validate the CertPath. If no exception thrown, successful.
+        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
+        cpv.validate(cp, params);
+        System.out.println("CertPath validation successful.");
+    }
+
+    private static X509Certificate generateCert(String certStr,
+                                                CertificateFactory cf)
+            throws Exception {
+        ByteArrayInputStream stream
+                = new ByteArrayInputStream(certStr.getBytes());
+        return (X509Certificate) cf.generateCertificate(stream);
+
+    }
+}
--- a/jdk/test/sun/security/smartcardio/TestChannel.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/smartcardio/TestChannel.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,11 @@
  * @bug 6239117
  * @summary test logical channels work
  * @author Andreas Sterbenz
- * @ignore requires special hardware
- * @run main/manual TestExclusive
+ * @run main/manual TestChannel
  */
 
+// This test requires special hardware.
+
 import java.io.*;
 import java.util.*;
 
--- a/jdk/test/sun/security/smartcardio/TestConnect.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/smartcardio/TestConnect.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,11 @@
  * @bug 6293769 6294527 6309280
  * @summary test connect() works
  * @author Andreas Sterbenz
- * @ignore requires special hardware
  * @run main/manual TestConnect
  */
 
+// This test requires special hardware.
+
 import java.io.*;
 import java.util.*;
 
--- a/jdk/test/sun/security/smartcardio/TestConnectAgain.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/smartcardio/TestConnectAgain.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,11 @@
  * @bug 6239117
  * @summary test connect works correctly if called multiple times/card removed
  * @author Andreas Sterbenz
- * @ignore requires special hardware
- * @run main/manual TestTransmit
+ * @run main/manual TestConnectAgain
  */
 
+// This test requires special hardware.
+
 import java.io.*;
 import java.util.*;
 
--- a/jdk/test/sun/security/smartcardio/TestControl.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/smartcardio/TestControl.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,11 @@
  * @bug 6239117 6470320
  * @summary test if transmitControlCommand() works
  * @author Andreas Sterbenz
- * @ignore requires special hardware
  * @run main/manual TestControl
  */
 
+// This test requires special hardware.
+
 import java.io.*;
 import java.util.*;
 
--- a/jdk/test/sun/security/smartcardio/TestDefault.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/smartcardio/TestDefault.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,11 @@
  * @bug 6327047
  * @summary verify that TerminalFactory.getDefault() works
  * @author Andreas Sterbenz
- * @ignore requires special hardware
  * @run main/manual TestDefault
  */
 
+// This test requires special hardware.
+
 import java.io.*;
 import java.util.*;
 
--- a/jdk/test/sun/security/smartcardio/TestExclusive.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/smartcardio/TestExclusive.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,11 @@
  * @bug 6239117
  * @summary verify that beginExclusive()/endExclusive() works
  * @author Andreas Sterbenz
- * @ignore requires special hardware
  * @run main/manual TestExclusive
  */
 
+// This test requires special hardware.
+
 import java.io.*;
 import java.util.*;
 
--- a/jdk/test/sun/security/smartcardio/TestMultiplePresent.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/smartcardio/TestMultiplePresent.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,11 @@
  * @bug 6239117 6445367
  * @summary test that CardTerminals.waitForCard() works
  * @author Andreas Sterbenz
- * @ignore requires special hardware
- * @run main/manual TestPresent
+ * @run main/manual TestMultiplePresent
  */
 
+// This test requires special hardware.
+
 import java.io.*;
 import java.util.*;
 
--- a/jdk/test/sun/security/smartcardio/TestPresent.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/smartcardio/TestPresent.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,11 @@
  * @bug 6293769 6294527
  * @summary test that the isCardPresent()/waitForX() APIs work correctly
  * @author Andreas Sterbenz
- * @ignore requires special hardware
  * @run main/manual TestPresent
  */
 
+// This test requires special hardware.
+
 import java.io.*;
 import java.util.*;
 
--- a/jdk/test/sun/security/smartcardio/TestTransmit.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/smartcardio/TestTransmit.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,11 @@
  * @bug 6293769 6294527
  * @summary test transmit() works
  * @author Andreas Sterbenz
- * @ignore requires special hardware
  * @run main/manual TestTransmit
  */
 
+// This test requires special hardware.
+
 import java.io.*;
 import java.util.*;
 
--- a/jdk/test/sun/security/ssl/SSLSocketImpl/NotifyHandshakeTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/ssl/SSLSocketImpl/NotifyHandshakeTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -88,6 +88,7 @@
          */
         SSLServerSocket sslss =
             (SSLServerSocket)sslssf.createServerSocket(serverPort);
+        sslss.setSoTimeout(30000);  // 30 seconds
         serverPort = sslss.getLocalPort();
         Server server = new Server(sslss);
         server.start();
--- a/jdk/test/sun/security/ssl/X509TrustManagerImpl/ClientServer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/ssl/X509TrustManagerImpl/ClientServer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,14 +24,17 @@
 /*
  * @test
  * @bug 4717766
+ * @author Brad Wetmore
  * @summary 1.0.3 JsseX509TrustManager erroneously calls isClientTrusted()
- * @run main/othervm ClientServer
+ * @run main/manual ClientServer
+ */
+
+/*
+ * SunJSSE does not support dynamic system properties, no way to re-use
+ * system properties in samevm/agentvm mode.
  *
- *     SunJSSE does not support dynamic system properties, no way to re-use
- *     system properties in samevm/agentvm mode.
- * @ignore JSSE supports algorithm constraints with CR 6916074,
- *     need to update this test case in JDK 7 soon
- * @author Brad Wetmore
+ * JSSE supports algorithm constraints with CR 6916074, need to update
+ * this test case in JDK 7 soon.
  *
  * This problem didn't exist in JSSE 1.4, only JSSE 1.0.3.  However,
  * this is a useful test, so I decided to include it in 1.4.2.
--- a/jdk/test/sun/security/tools/keytool/PrintSSL.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/tools/keytool/PrintSSL.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +31,8 @@
     public static void main(String[] args) throws Exception {
         System.setProperty("javax.net.ssl.keyStorePassword", "passphrase");
         System.setProperty("javax.net.ssl.keyStore",
-                System.getProperty("test.src", "./") + "/../../ssl/etc/keystore");
+                           System.getProperty("test.src", "./")
+                               + "/../../../../javax/net/ssl/etc/keystore");
         SSLServerSocketFactory sslssf =
                 (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
         final ServerSocket server = sslssf.createServerSocket(0);
--- a/jdk/test/sun/security/tools/keytool/console.sh	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/tools/keytool/console.sh	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved.
 # 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 @@
 # @bug 6418647 8005527
 # @summary Doc bug 5035358 shows sun.security.util.Password.readPassword() is buggy.
 # @author Weijun Wang
-# @ignore unable to test manual tools that have input from stdin,
-#               and output to stderr and stdout
 # @run shell/manual console.sh
 
 if [ "$ALT_PASS" = "" ]; then
--- a/jdk/test/sun/security/tools/keytool/i18n.sh	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/tools/keytool/i18n.sh	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
 # 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 @@
 # @bug 4348369
 # @summary keytool not i18n compliant
 # @author charlie lai
-#
-# @ignore unable to test manual tools that have input from stdin,
-#		and output to stderr and stdout
+# @run shell/manual i18n.sh
 
 # set a few environment variables so that the shell-script can run stand-alone
 # in the source directory
--- a/jdk/test/sun/security/tools/keytool/printssl.sh	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/security/tools/keytool/printssl.sh	Wed Jul 05 19:33:51 2017 +0200
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -56,7 +56,15 @@
 esac
 
 ${COMPILEJAVA}${FS}bin${FS}javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} -d . ${TESTSRC}${FS}PrintSSL.java || exit 10
-${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -Dtest.src=$TESTSRC PrintSSL | ( read PORT; ${TESTJAVA}${FS}bin${FS}keytool -printcert -sslserver localhost:$PORT )
+${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -Dtest.src=$TESTSRC PrintSSL | (
+      read PORT
+      if [ "$PORT" = "" ]; then
+          echo "Server not started"
+          exit 2
+      else
+          ${TESTJAVA}${FS}bin${FS}keytool -printcert -sslserver localhost:$PORT
+      fi
+)
 status=$?
 
 rm PrintSSL*.class
--- a/jdk/test/sun/util/calendar/zi/Zoneinfo.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/util/calendar/zi/Zoneinfo.java	Wed Jul 05 19:33:51 2017 +0200
@@ -372,6 +372,7 @@
         ZoneRec zrec = zone.get(zone.size()-1);
         tz.getOffsetIndex(zrec.getGmtOffset());
 
+        int lastGmtOffsetValue = -1;
         int currentSave = 0;
         boolean usedZone;
         for (int zindex = 0; zindex < zone.size(); zindex++) {
@@ -380,9 +381,12 @@
             gmtOffset = zrec.getGmtOffset();
             int stdOffset = zrec.getDirectSave();
 
+            if (gmtOffset != lastGmtOffsetValue) {
+                tz.setRawOffset(gmtOffset, fromTime);
+                lastGmtOffsetValue = gmtOffset;
+            }
             // If this is the last zone record, take the last rule info.
             if (!zrec.hasUntil()) {
-                tz.setRawOffset(gmtOffset, fromTime);
                 if (zrec.hasRuleReference()) {
                     tz.setLastRules(zrec.getRuleRef().getLastRules());
                 } else if (stdOffset != 0) {
--- a/jdk/test/sun/util/calendar/zi/tzdata/VERSION	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/util/calendar/zi/tzdata/VERSION	Wed Jul 05 19:33:51 2017 +0200
@@ -21,4 +21,4 @@
 # or visit www.oracle.com if you need additional information or have any
 # questions.
 #
-tzdata2013i
+tzdata2014a
--- a/jdk/test/sun/util/calendar/zi/tzdata/asia	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/util/calendar/zi/tzdata/asia	Wed Jul 05 19:33:51 2017 +0200
@@ -1113,8 +1113,13 @@
 Rule	Zion	1986	only	-	Sep	 7	0:00	0	S
 Rule	Zion	1987	only	-	Apr	15	0:00	1:00	D
 Rule	Zion	1987	only	-	Sep	13	0:00	0	S
-Rule	Zion	1988	only	-	Apr	 9	0:00	1:00	D
-Rule	Zion	1988	only	-	Sep	 3	0:00	0	S
+
+# From Avigdor Finkelstein (2014-03-05):
+# I check the Parliament (Knesset) records and there it's stated that the
+# [1988] transition should take place on Saturday night, when the Sabbath
+# ends and changes to Sunday.
+Rule	Zion	1988	only	-	Apr	10	0:00	1:00	D
+Rule	Zion	1988	only	-	Sep	 4	0:00	0	S
 
 # From Ephraim Silverberg
 # (1997-03-04, 1998-03-16, 1998-12-28, 2000-01-17, 2000-07-25, 2004-12-22,
--- a/jdk/test/sun/util/calendar/zi/tzdata/australasia	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/util/calendar/zi/tzdata/australasia	Wed Jul 05 19:33:51 2017 +0200
@@ -377,16 +377,18 @@
 # http://www.fiji.gov.fj/index.php?option=com_content&view=article&id=6702&catid=71&Itemid=155
 
 # From the Fijian Government Media Center (2013-08-30) via David Wheeler:
-# Fiji will start daylight savings on Sunday 27th October, 2013 and end at 3am
-# on Sunday 19th January, 2014....  move clocks forward by one hour from 2am
+# Fiji will start daylight savings on Sunday 27th October, 2013 ...
+# move clocks forward by one hour from 2am
 # http://www.fiji.gov.fj/Media-Center/Press-Releases/DAYLIGHT-SAVING-STARTS-ON-SUNDAY,-27th-OCTOBER-201.aspx
-#
-# From Paul Eggert (2013-09-09):
+
+# From Steffen Thorsen (2013-01-10):
+# Fiji will end DST on 2014-01-19 02:00:
+# http://www.fiji.gov.fj/Media-Center/Press-Releases/DAYLIGHT-SAVINGS-TO-END-THIS-MONTH-%281%29.aspx
+
+# From Paul Eggert (2014-01-10):
 # For now, guess that Fiji springs forward the Sunday before the fourth
-# Monday in October.  This matches both recent practice and
-# timeanddate.com's current spring-forward prediction.
-# For the January 2014 transition we guessed right while timeanddate.com
-# guessed wrong, so leave the fall-back prediction alone.
+# Monday in October, and springs back the penultimate Sunday in January.
+# This is ad hoc, but matches recent practice.
 
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Fiji	1998	1999	-	Nov	Sun>=1	2:00	1:00	S
@@ -395,7 +397,8 @@
 Rule	Fiji	2010	only	-	Mar	lastSun	3:00	0	-
 Rule	Fiji	2010	max	-	Oct	Sun>=21	2:00	1:00	S
 Rule	Fiji	2011	only	-	Mar	Sun>=1	3:00	0	-
-Rule	Fiji	2012	max	-	Jan	Sun>=18	3:00	0	-
+Rule	Fiji	2012	2013	-	Jan	Sun>=18	3:00	0	-
+Rule	Fiji	2014	max	-	Jan	Sun>=18	2:00	0	-
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Pacific/Fiji	11:55:44 -	LMT	1915 Oct 26	# Suva
 			12:00	Fiji	FJ%sT	# Fiji Time
--- a/jdk/test/sun/util/calendar/zi/tzdata/europe	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/util/calendar/zi/tzdata/europe	Wed Jul 05 19:33:51 2017 +0200
@@ -2768,14 +2768,18 @@
 # According to the articles linked below, Turkey will change into summer
 # time zone (GMT+3) on March 28, 2011 at 3:00 a.m. instead of March 27.
 # This change is due to a nationwide exam on 27th.
-#
-# <a href="http://www.worldbulletin.net/?aType=haber&ArticleID=70872">
 # http://www.worldbulletin.net/?aType=haber&ArticleID=70872
-# </a>
 # Turkish:
-# <a href="http://www.hurriyet.com.tr/ekonomi/17230464.asp?gid=373">
 # http://www.hurriyet.com.tr/ekonomi/17230464.asp?gid=373
-# </a>
+
+# From Faruk Pasin (2014-02-14):
+# The DST for Turkey has been changed for this year because of the
+# Turkish Local election....
+# http://www.sabah.com.tr/Ekonomi/2014/02/12/yaz-saatinde-onemli-degisiklik
+# ... so Turkey will move clocks forward one hour on March 31 at 3:00 a.m.
+# From Paul Eggert (2014-02-17):
+# Here is an English-language source:
+# http://www.worldbulletin.net/turkey/129016/turkey-switches-to-daylight-saving-time-march-31
 
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Turkey	1916	only	-	May	 1	0:00	1:00	S
@@ -2844,6 +2848,8 @@
 			2:00	Turkey	EE%sT	2007
 			2:00	EU	EE%sT	2011 Mar 27 1:00u
 			2:00	-	EET	2011 Mar 28 1:00u
+			2:00	EU	EE%sT	2014 Mar 30 1:00u
+			2:00	-	EET	2014 Mar 31 1:00u
 			2:00	EU	EE%sT
 Link	Europe/Istanbul	Asia/Istanbul	# Istanbul is in both continents.
 
@@ -2865,19 +2871,13 @@
 # approval from 266 deputies.
 #
 # Ukraine abolishes transter back to the winter time (in Russian)
-# <a href="http://news.mail.ru/politics/6861560/">
 # http://news.mail.ru/politics/6861560/
-# </a>
 #
 # The Ukrainians will no longer change the clock (in Russian)
-# <a href="http://www.segodnya.ua/news/14290482.html">
 # http://www.segodnya.ua/news/14290482.html
-# </a>
 #
 # Deputies cancelled the winter time (in Russian)
-# <a href="http://www.pravda.com.ua/rus/news/2011/09/20/6600616/">
 # http://www.pravda.com.ua/rus/news/2011/09/20/6600616/
-# </a>
 #
 # From Philip Pizzey (2011-10-18):
 # Today my Ukrainian colleagues have informed me that the
@@ -2888,18 +2888,39 @@
 # As far as I understand, the recent change to the Ukrainian time zone
 # (Europe/Kiev) to introduce permanent daylight saving time (similar
 # to Russia) was reverted today:
-#
-# <a href="http://portal.rada.gov.ua/rada/control/en/publish/article/info_left?art_id=287324&cat_id=105995">
 # http://portal.rada.gov.ua/rada/control/en/publish/article/info_left?art_id=287324&cat_id=105995
-# </a>
 #
 # Also reported by Alexander Bokovoy (2011-10-18) who also noted:
 # The law documents themselves are at
+# http://w1.c1.rada.gov.ua/pls/zweb_n/webproc4_1?id=&pf3511=41484
+
+# From Vladimir in Moscow via Alois Treindl re Kiev time 1991/2 (2014-02-28):
+# First in Ukraine they changed Time zone from UTC+3 to UTC+2 with DST:
+#       03 25 1990 02:00 -03.00 1       Time Zone 3 with DST
+#       07 01 1990 02:00 -02.00 1       Time Zone 2 with DST
+# * Ukrainian Government's Resolution of 18.06.1990, No. 134.
+# http://search.ligazakon.ua/l_doc2.nsf/link1/T001500.html
 #
-# <a href="http://w1.c1.rada.gov.ua/pls/zweb_n/webproc4_1?id=&pf3511=41484">
-# http://w1.c1.rada.gov.ua/pls/zweb_n/webproc4_1?id=&pf3511=41484
-# </a>
-
+# They did not end DST in September, 1990 (according to the law,
+# "summer time" was still in action):
+#       09 30 1990 03:00 -02.00 1       Time Zone 2 with DST
+# * Ukrainian Government's Resolution of 21.09.1990, No. 272.
+# http://search.ligazakon.ua/l_doc2.nsf/link1/KP900272.html
+#
+# Again no change in March, 1991 ("summer time" in action):
+#       03 31 1991 02:00 -02.00 1       Time Zone 2 with DST
+#
+# DST ended in September 1991 ("summer time" ended):
+#       09 29 1991 03:00 -02.00 0       Time Zone 2, no DST
+# * Ukrainian Government's Resolution of 25.09.1991, No. 225.
+# http://www.uazakon.com/documents/date_21/pg_iwgdoc.htm
+# This is an answer.
+#
+# Since 1992 they had normal DST procedure:
+#       03 29 1992 02:00 -02.00 1       DST started
+#       09 27 1992 03:00 -02.00 0       DST ended
+# * Ukrainian Government's Resolution of 20.03.1992, No. 139.
+# http://www.uazakon.com/documents/date_8u/pg_grcasa.htm
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 # Most of Ukraine since 1970 has been like Kiev.
@@ -2910,9 +2931,8 @@
 			2:00	-	EET	1930 Jun 21
 			3:00	-	MSK	1941 Sep 20
 			1:00	C-Eur	CE%sT	1943 Nov  6
-			3:00	Russia	MSK/MSD	1990
-			3:00	-	MSK	1990 Jul  1 2:00
-			2:00	-	EET	1992
+			3:00	Russia	MSK/MSD	1990 Jul  1 2:00
+			2:00	1:00	EEST	1991 Sep 29 3:00
 			2:00	E-Eur	EE%sT	1995
 			2:00	EU	EE%sT
 # Ruthenia used CET 1990/1991.
--- a/jdk/test/sun/util/calendar/zi/tzdata/northamerica	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/util/calendar/zi/tzdata/northamerica	Wed Jul 05 19:33:51 2017 +0200
@@ -414,9 +414,10 @@
 # US Pacific time, represented by Los Angeles
 #
 # California, northern Idaho (Benewah, Bonner, Boundary, Clearwater,
-# Idaho, Kootenai, Latah, Lewis, Nez Perce, and Shoshone counties,
-# and the northern three-quarters of Idaho county),
-# most of Nevada, most of Oregon, and Washington
+# Kootenai, Latah, Lewis, Nez Perce, and Shoshone counties, Idaho county
+# north of the Salmon River, and the towns of Burgdorf and Warren),
+# Nevada (except West Wendover), Oregon (except the northern 3/4 of
+# Malheur county), and Washington
 #
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
 Rule	CA	1948	only	-	Mar	14	2:00	1:00	D
--- a/jdk/test/sun/util/calendar/zi/tzdata/southamerica	Tue Mar 25 12:31:49 2014 -0700
+++ b/jdk/test/sun/util/calendar/zi/tzdata/southamerica	Wed Jul 05 19:33:51 2017 +0200
@@ -1298,6 +1298,13 @@
 # start date is 2013-09-08 00:00....
 # http://www.gob.cl/informa/2013/02/15/gobierno-anuncia-fechas-de-cambio-de-hora-para-el-ano-2013.htm
 
+# From Jose Miguel Garrido (2014-02-19):
+# Today appeared in the Diario Oficial a decree amending the time change
+# dates to 2014.
+# DST End: last Saturday of April 2014 (Sun 27 Apr 2014 03:00 UTC)
+# DST Start: first Saturday of September 2014 (Sun 07 Sep 2014 04:00 UTC)
+# http://www.diariooficial.interior.gob.cl//media/2014/02/19/do-20140219.pdf
+
 # NOTE: ChileAQ rules for Antarctic bases are stored separately in the
 # 'antarctica' file.
 
@@ -1631,6 +1638,9 @@
 # From Carlos Raul Perasso (2013-03-15):
 # The change in Paraguay is now final.  Decree number 10780
 # http://www.presidencia.gov.py/uploads/pdf/presidencia-3b86ff4b691c79d4f5927ca964922ec74772ce857c02ca054a52a37b49afc7fb.pdf
+# From Carlos Raul Perasso (2014-02-28):
+# Decree 1264 can be found at:
+# http://www.presidencia.gov.py/archivos/documentos/DECRETO1264_ey9r8zai.pdf
 Rule	Para	2013	max	-	Mar	Sun>=22	0:00	0	-
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
@@ -1689,18 +1699,19 @@
 Zone America/Port_of_Spain -4:06:04 -	LMT	1912 Mar 2
 			-4:00	-	AST
 
+# These all agree with Trinidad and Tobago since 1970.
 Link America/Port_of_Spain America/Anguilla
 Link America/Port_of_Spain America/Dominica
 Link America/Port_of_Spain America/Grenada
 Link America/Port_of_Spain America/Guadeloupe
-Link America/Port_of_Spain America/Marigot
+Link America/Port_of_Spain America/Marigot	# St Martin (French part)
 Link America/Port_of_Spain America/Montserrat
 Link America/Port_of_Spain America/St_Barthelemy
-Link America/Port_of_Spain America/St_Kitts
+Link America/Port_of_Spain America/St_Kitts	# St Kitts & Nevis
 Link America/Port_of_Spain America/St_Lucia
-Link America/Port_of_Spain America/St_Thomas
+Link America/Port_of_Spain America/St_Thomas	# Virgin Islands (US)
 Link America/Port_of_Spain America/St_Vincent
-Link America/Port_of_Spain America/Tortola
+Link America/Port_of_Spain America/Tortola	# Virgin Islands (UK)
 
 # Uruguay
 # From Paul Eggert (1993-11-18):
--- a/make/common/JavaCompilation.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/make/common/JavaCompilation.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -143,6 +143,9 @@
   ifneq (,$2)
     $1_DEPS:=$2
   else
+    # Add all source roots to the find cache since we are likely going to run find 
+    # on these more than once. The cache will only be updated if necessary.
+    $$(eval $$(call FillCacheFind, $$($1_FIND_LIST)))
     $1_DEPS:=$$(filter $$(addprefix %,$$($1_SUFFIXES)), \
         $$(call CacheFind,$$($1_SRCS)))
     ifneq (,$$($1_GREP_INCLUDE_PATTERNS))
@@ -158,6 +161,10 @@
       $1_DEPS+=$$(call CacheFind,$$(wildcard $$(addsuffix /META-INF,$$($1_SRCS))))
     endif
   endif
+  # The dependency list should never be empty
+  ifeq ($$(strip $$($1_DEPS)), )
+    $$(warning No dependencies found for $1)
+  endif
 
   # Utility macros, to make the shell script receipt somewhat easier to decipher.
 
@@ -336,7 +343,20 @@
 # Previously this was inconsistently done in different repositories.
 # This is the new clean standard. Though it is to be superseded by
 # a standard annotation processor from with sjavac.
-define add_file_to_copy_and_clean
+#
+# The sed expression does this:
+# 1. Add a backslash before any :, = or ! that do not have a backslash already.
+# 2. Apply the file unicode2x.sed which does a whole bunch of \u00XX to \xXX 
+#    conversions.
+# 3. Delete all lines starting with #.
+# 4. Delete empty lines.
+# 5. Append lines ending with \ with the next line.
+# 6. Remove leading and trailing white space.
+# 7. Replace the first \= with just =.
+# 8. Finally it's all sorted to create a stable output.
+# 
+# It is assumed that = is the character used for separating names and values.
+define add_file_to_clean
   # param 1 = BUILD_MYPACKAGE
   # parma 2 = The source file to copy and clean.
   $2_TARGET:=$2
@@ -345,12 +365,13 @@
   # Now we can setup the depency that will trigger the copying.
   $$($1_BIN)$$($2_TARGET) : $2
 	$(MKDIR) -p $$(@D)
-	$(CAT) $$< | $(SED) -e 's/\([^\\]\):/\1\\:/g' -e 's/\([^\\]\)=/\1\\=/g' -e 's/#.*/#/g' \
+	$(CAT) $$< | $(SED) -e 's/\([^\\]\):/\1\\:/g' -e 's/\([^\\]\)=/\1\\=/g' \
+	        -e 's/\([^\\]\)!/\1\\!/g' -e 's/#.*/#/g' \
 	    | $(SED) -f "$(SRC_ROOT)/make/common/support/unicode2x.sed" \
 	    | $(SED) -e '/^#/d' -e '/^$$$$/d' \
 	        -e :a -e '/\\$$$$/N; s/\\\n//; ta' \
 	        -e 's/^[ \t]*//;s/[ \t]*$$$$//' \
-	        -e 's/\\=/=/' | LANG=C $(SORT) > $$@
+	        -e 's/\\=/=/' | LC_ALL=C $(SORT) > $$@
 	$(CHMOD) -f ug+w $$@
 
   # And do not forget this target
@@ -376,8 +397,9 @@
   #   INCLUDES:=myapp.foo means will only compile java files in myapp.foo or any of its sub-packages.
   #   EXCLUDES:=myapp.foo means will do not compile java files in myapp.foo or any of its sub-packages.
   #   COPY:=.prp means copy all prp files to the corresponding package in BIN.
+  #   COPY_FILES:=myapp/foo/setting.txt means copy this file over to the package myapp/foo
   #   CLEAN:=.properties means copy and clean all properties file to the corresponding package in BIN.
-  #   COPY_FILES:=myapp/foo/setting.txt means copy this file over to the package myapp/foo
+  #   CLEAN_FILES:=myapp/foo/setting.txt means clean this file over to the package myapp/foo
   #   SRCZIP:=Create a src.zip based on the found sources and copied files.
   #   INCLUDE_FILES:="com/sun/SolarisFoobar.java" means only compile this file!
   #   EXCLUDE_FILES:="com/sun/SolarisFoobar.java" means do not compile this particular file!
@@ -405,6 +427,9 @@
   # Make sure the dirs exist.
   $$(foreach d,$$($1_SRC), $$(if $$(wildcard $$d),,$$(error SRC specified to SetupJavaCompilation $1 contains missing directory $$d)))
   $$(eval $$(call MakeDir,$$($1_BIN)))
+  # Add all source roots to the find cache since we are likely going to run find 
+  # on these more than once. The cache will only be updated if necessary.
+  $$(eval $$(call FillCacheFind,$$($1_SRC)))
   # Find all files in the source trees.
   $1_ALL_SRCS += $$(filter-out $(OVR_SRCS),$$(call CacheFind,$$($1_SRC)))
   # Extract the java files.
@@ -437,7 +462,7 @@
   endif
 
   # Find all files to be copied from source to bin.
-  ifneq (,$$($1_COPY))
+  ifneq (,$$($1_COPY)$$($1_COPY_FILES))
     # Search for all files to be copied.
     $1_ALL_COPIES := $$(filter $$(addprefix %,$$($1_COPY)),$$($1_ALL_SRCS))
     # Copy these explicitly
@@ -452,20 +477,22 @@
     ifneq (,$$($1_EXCLUDE_FILES))
       $1_ALL_COPIES := $$(filter-out $$($1_EXCLUDE_FILES_PATTERN),$$($1_ALL_COPIES))
     endif
-    # All files below META-INF are always copied.
-    $1_ALL_COPIES += $$(filter $$(addsuffix /META-INF%,$$($1_SRC)),$$($1_ALL_SRCS))
-    ifneq (,$$($1_ALL_COPIES))
-      # Yep, there are files to be copied!
-      $1_ALL_COPY_TARGETS:=
-          $$(foreach i,$$($1_ALL_COPIES),$$(eval $$(call add_file_to_copy,$1,$$i)))
-      # Now we can depend on $$($1_ALL_COPY_TARGETS) to copy all files!
-    endif
+  endif
+  # All files below META-INF are always copied.
+  $1_ALL_COPIES += $$(filter $$(addsuffix /META-INF%,$$($1_SRC)),$$($1_ALL_SRCS))
+  ifneq (,$$($1_ALL_COPIES))
+    # Yep, there are files to be copied!
+    $1_ALL_COPY_TARGETS:=
+        $$(foreach i,$$($1_ALL_COPIES),$$(eval $$(call add_file_to_copy,$1,$$i)))
+    # Now we can depend on $$($1_ALL_COPY_TARGETS) to copy all files!
   endif
 
   # Find all property files to be copied and cleaned from source to bin.
-  ifneq (,$$($1_CLEAN))
+  ifneq (,$$($1_CLEAN)$$($1_CLEAN_FILES))
     # Search for all files to be copied.
     $1_ALL_CLEANS := $$(filter $$(addprefix %,$$($1_CLEAN)),$$($1_ALL_SRCS))
+    # Clean these explicitly
+    $1_ALL_CLEANS += $$($1_CLEAN_FILES)
     # Copy and clean must also respect filters.
     ifneq (,$$($1_INCLUDES))
       $1_ALL_CLEANS := $$(filter $$($1_SRC_INCLUDES),$$($1_ALL_CLEANS))
@@ -479,7 +506,7 @@
     ifneq (,$$($1_ALL_CLEANS))
       # Yep, there are files to be copied and cleaned!
       $1_ALL_COPY_CLEAN_TARGETS:=
-          $$(foreach i,$$($1_ALL_CLEANS),$$(eval $$(call add_file_to_copy_and_clean,$1,$$i)))
+          $$(foreach i,$$($1_ALL_CLEANS),$$(eval $$(call add_file_to_clean,$1,$$i)))
       # Now we can depend on $$($1_ALL_COPY_CLEAN_TARGETS) to copy all files!
     endif
   endif
--- a/make/common/MakeBase.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/make/common/MakeBase.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -380,11 +380,23 @@
   # On Solaris, if the target is a symlink and exists, cp won't overwrite.
   # Cp has to operate in recursive mode to allow for -P flag, to preserve soft links. If the
   # name of the target file differs from the source file, rename after copy.
+  # If the source and target parent directories are the same, recursive copy doesn't work
+  # so we fall back on regular copy, which isn't preserving symlinks.
   define install-file
 	$(MKDIR) -p $(@D)
 	$(RM) '$@'
-	$(CP) -f -r -P '$<' '$(@D)'
-	if [ "$(@F)" != "$(<F)" ]; then $(MV) '$(@D)/$(<F)' '$@'; fi
+	if [ "$(@D)" != "$(<D)" ]; then \
+	  $(CP) -f -r -P '$<' '$(@D)'; \
+	  if [ "$(@F)" != "$(<F)" ]; then \
+	    $(MV) '$(@D)/$(<F)' '$@'; \
+	  fi; \
+	else \
+	  if [ -L '$<' ]; then \
+	    $(ECHO) "Source file is a symlink and target is in the same directory: $< $@" ; \
+	    exit 1; \
+	  fi; \
+	  $(CP) -f '$<' '$@'; \
+	fi
   endef
 else ifeq ($(OPENJDK_TARGET_OS),macosx)
   # On mac, extended attributes sometimes creep into the source files, which may later
@@ -408,6 +420,7 @@
 containing = $(foreach v,$2,$(if $(findstring $1,$v),$v))
 not-containing = $(foreach v,$2,$(if $(findstring $1,$v),,$v))
 
+ifneq ($(DISABLE_CACHE_FIND), true)
 ################################################################################
 # In Cygwin, finds are very costly, both because of expensive forks and because
 # of bad file system caching. Find is used extensively in $(shell) commands to
@@ -421,16 +434,23 @@
 #
 # Needs to be called with $(eval )
 #
+  # Even if the performance benifit is negligible on other platforms, keep the
+  # functionality active unless explicitly disabled to exercise it more.
+  #
+  # Initialize FIND_CACHE_DIRS with := to make it a non recursively-expanded variable
+  FIND_CACHE_DIRS :=
 # Param 1 - Dir to find in
-ifeq ($(OPENJDK_BUILD_OS),windows)
   define FillCacheFind
-    FIND_CACHE_DIR += $1
-    FIND_CACHE := $$(sort $$(FIND_CACHE) $$(shell $(FIND) $1 -type f -o -type l))
+    # Filter out already cached dirs. The - is needed when FIND_CACHE_DIR is empty
+    # since filter out will then return empty.
+    FIND_CACHE_NEW_DIRS := $$(filter-out $$(addsuffix /%,\
+        - $(FIND_CACHE_DIRS)) $(FIND_CACHE_DIRS), $1)
+    ifneq ($$(FIND_CACHE_NEW_DIRS), )
+      # Remove any trailing slash from dirs in the cache dir list
+      FIND_CACHE_DIRS += $$(patsubst %/,%, $$(FIND_CACHE_NEW_DIRS))
+      FIND_CACHE := $$(sort $$(FIND_CACHE) $$(shell $(FIND) $$(FIND_CACHE_NEW_DIRS) -type f -o -type l))
+    endif
   endef
-else
-  define FillCacheFind
-  endef
-endif
 
 # Mimics find by looking in the cache if all of the directories have been cached.
 # Otherwise reverts to shell find. This is safe to call on all platforms, even if
@@ -439,10 +459,16 @@
 # The extra - is needed when FIND_CACHE_DIR is empty but should be harmless.
 # Param 1 - Dirs to find in
 define CacheFind
-  $(if $(filter-out $(addsuffix %,- $(FIND_CACHE_DIR)),$1), \
+    $(if $(filter-out $(addsuffix /%,- $(FIND_CACHE_DIRS)) $(FIND_CACHE_DIRS),$1), \
     $(shell $(FIND) $1 -type f -o -type l), \
     $(filter $(addsuffix %,$1),$(FIND_CACHE)))
 endef
+else
+  # If CacheFind is disabled, just run the find command.
+  define CacheFind
+    $(shell $(FIND) $1 -type f -o -type l)
+  endef
+endif
 
 ################################################################################
 
--- a/nashorn/.hgtags	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/.hgtags	Wed Jul 05 19:33:51 2017 +0200
@@ -238,3 +238,4 @@
 b3517e51f40477f10db8bc30a557aa0ea712c274 jdk9-b02
 832f89ff25d903c45cfc994553f1ade8821a4398 jdk9-b03
 3f6ef92cd7823372c45e79125adba4cbf1c9f7b2 jdk9-b04
+2a1cac93c33317d828d4a5b81239204a9927cc4a jdk9-b05
--- a/nashorn/make/BuildNashorn.gmk	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/make/BuildNashorn.gmk	Wed Jul 05 19:33:51 2017 +0200
@@ -77,7 +77,7 @@
 	$(RM) -rf $(@D)/jdk $(@D)/netscape
 	$(CP) -R -p $(NASHORN_OUTPUTDIR)/nashorn_classes/* $(@D)/
 	$(FIXPATH) $(JAVA) \
-	    -cp "$(NASHORN_OUTPUTDIR)/nasgen_classes$(PATH_SEP)$(NASHORN_OUTPUTDIR)/nashorn_classes" \
+	    -Xbootclasspath/p:"$(NASHORN_OUTPUTDIR)/nasgen_classes$(PATH_SEP)$(NASHORN_OUTPUTDIR)/nashorn_classes" \
 	    jdk.nashorn.internal.tools.nasgen.Main $(@D) jdk.nashorn.internal.objects $(@D)
 	$(TOUCH) $@
 
--- a/nashorn/make/build.xml	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/make/build.xml	Wed Jul 05 19:33:51 2017 +0200
@@ -125,6 +125,7 @@
       <compilerarg value="-Xlint:unchecked"/>
       <compilerarg value="-Xlint:deprecation"/>
       <compilerarg value="-XDignore.symbol.file"/>
+      <compilerarg value="-Xdiags:verbose"/>
     </javac>
     <copy todir="${build.classes.dir}/META-INF/services">
        <fileset dir="${meta.inf.dir}/services/"/>
@@ -243,6 +244,7 @@
         <compilerarg value="-J-Djava.ext.dirs="/>
         <compilerarg value="-Xlint:unchecked"/>
         <compilerarg value="-Xlint:deprecation"/>
+        <compilerarg value="-Xdiags:verbose"/>
     </javac>
 
     <copy todir="${build.test.classes.dir}/META-INF/services">
@@ -253,6 +255,10 @@
        <fileset dir="${test.src.dir}/jdk/nashorn/internal/runtime/resources"/>
     </copy>
 
+    <copy todir="${build.test.classes.dir}/jdk/nashorn/api/scripting/resources">
+       <fileset dir="${test.src.dir}/jdk/nashorn/api/scripting/resources"/>
+    </copy>
+
     <!-- tests that check nashorn internals and internal API -->
     <jar jarfile="${nashorn.internal.tests.jar}">
       <fileset dir="${build.test.classes.dir}" excludes="**/api/**"/>
--- a/nashorn/make/project.properties	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/make/project.properties	Wed Jul 05 19:33:51 2017 +0200
@@ -206,7 +206,7 @@
 
 # test262 test frameworks
 test262-test-sys-prop.test.js.framework=\
-    --class-cache-size=0 \
+    --class-cache-size=10 \
     --no-java \
     --no-typed-arrays \
     -timezone=PST \
--- a/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java	Wed Jul 05 19:33:51 2017 +0200
@@ -57,9 +57,9 @@
 import javax.script.ScriptEngineFactory;
 import javax.script.ScriptException;
 import javax.script.SimpleBindings;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.Context;
 import jdk.nashorn.internal.runtime.ErrorManager;
-import jdk.nashorn.internal.runtime.GlobalObject;
 import jdk.nashorn.internal.runtime.Property;
 import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptObject;
@@ -99,7 +99,7 @@
     private final boolean             _global_per_engine;
     // This is the initial default Nashorn global object.
     // This is used as "shared" global if above option is true.
-    private final ScriptObject        global;
+    private final Global              global;
     // initialized bit late to be made 'final'.
     // Property object for "context" property of global object.
     private volatile Property         contextProperty;
@@ -264,7 +264,7 @@
     public Object __noSuchProperty__(final Object self, final ScriptContext ctxt, final String name) {
         if (ctxt != null) {
             final int scope = ctxt.getAttributesScope(name);
-            final ScriptObject ctxtGlobal = getNashornGlobalFrom(ctxt);
+            final Global ctxtGlobal = getNashornGlobalFrom(ctxt);
             if (scope != -1) {
                 return ScriptObjectMirror.unwrap(ctxt.getAttribute(name, scope), ctxtGlobal);
             }
@@ -317,7 +317,7 @@
         }
 
         ScriptObject realSelf = null;
-        ScriptObject realGlobal = null;
+        Global realGlobal = null;
         if(thiz == null) {
             // making interface out of global functions
             realSelf = realGlobal = getNashornGlobalFrom(context);
@@ -346,7 +346,7 @@
         }
 
         try {
-            final ScriptObject oldGlobal = Context.getGlobal();
+            final Global oldGlobal = Context.getGlobal();
             final boolean globalChanged = (oldGlobal != realGlobal);
             try {
                 if (globalChanged) {
@@ -371,7 +371,7 @@
     }
 
     // Retrieve nashorn Global object for a given ScriptContext object
-    private ScriptObject getNashornGlobalFrom(final ScriptContext ctxt) {
+    private Global getNashornGlobalFrom(final ScriptContext ctxt) {
         if (_global_per_engine) {
             // shared single global object for all ENGINE_SCOPE Bindings
             return global;
@@ -380,18 +380,18 @@
         final Bindings bindings = ctxt.getBindings(ScriptContext.ENGINE_SCOPE);
         // is this Nashorn's own Bindings implementation?
         if (bindings instanceof ScriptObjectMirror) {
-            final ScriptObject sobj = globalFromMirror((ScriptObjectMirror)bindings);
-            if (sobj != null) {
-                return sobj;
+            final Global glob = globalFromMirror((ScriptObjectMirror)bindings);
+            if (glob != null) {
+                return glob;
             }
         }
 
         // Arbitrary user Bindings implementation. Look for NASHORN_GLOBAL in it!
         Object scope = bindings.get(NASHORN_GLOBAL);
         if (scope instanceof ScriptObjectMirror) {
-            final ScriptObject sobj = globalFromMirror((ScriptObjectMirror)scope);
-            if (sobj != null) {
-                return sobj;
+            final Global glob = globalFromMirror((ScriptObjectMirror)scope);
+            if (glob != null) {
+                return glob;
             }
         }
 
@@ -399,14 +399,14 @@
         // Create new global instance mirror and associate with the Bindings.
         final ScriptObjectMirror mirror = createGlobalMirror(ctxt);
         bindings.put(NASHORN_GLOBAL, mirror);
-        return mirror.getScriptObject();
+        return mirror.getHomeGlobal();
     }
 
     // Retrieve nashorn Global object from a given ScriptObjectMirror
-    private ScriptObject globalFromMirror(final ScriptObjectMirror mirror) {
+    private Global globalFromMirror(final ScriptObjectMirror mirror) {
         ScriptObject sobj = mirror.getScriptObject();
-        if (sobj instanceof GlobalObject && isOfContext(sobj, nashornContext)) {
-            return sobj;
+        if (sobj instanceof Global && isOfContext((Global)sobj, nashornContext)) {
+            return (Global)sobj;
         }
 
         return null;
@@ -414,15 +414,15 @@
 
     // Create a new ScriptObjectMirror wrapping a newly created Nashorn Global object
     private ScriptObjectMirror createGlobalMirror(final ScriptContext ctxt) {
-        final ScriptObject newGlobal = createNashornGlobal(ctxt);
+        final Global newGlobal = createNashornGlobal(ctxt);
         return new ScriptObjectMirror(newGlobal, newGlobal);
     }
 
     // Create a new Nashorn Global object
-    private ScriptObject createNashornGlobal(final ScriptContext ctxt) {
-        final ScriptObject newGlobal = AccessController.doPrivileged(new PrivilegedAction<ScriptObject>() {
+    private Global createNashornGlobal(final ScriptContext ctxt) {
+        final Global newGlobal = AccessController.doPrivileged(new PrivilegedAction<Global>() {
             @Override
-            public ScriptObject run() {
+            public Global run() {
                 try {
                     return nashornContext.newGlobal();
                 } catch (final RuntimeException e) {
@@ -460,7 +460,7 @@
     }
 
     // scripts should see "context" and "engine" as variables in the given global object
-    private void setContextVariables(final ScriptObject ctxtGlobal, final ScriptContext ctxt) {
+    private void setContextVariables(final Global ctxtGlobal, final ScriptContext ctxt) {
         // set "context" global variable via contextProperty - because this
         // property is non-writable
         contextProperty.setObjectValue(ctxtGlobal, ctxtGlobal, ctxt, false);
@@ -470,7 +470,7 @@
         }
         // if no arguments passed, expose it
         if (! (args instanceof ScriptObject)) {
-            args = ((GlobalObject)ctxtGlobal).wrapAsObject(args);
+            args = ctxtGlobal.wrapAsObject(args);
             ctxtGlobal.set("arguments", args, false);
         }
     }
@@ -478,7 +478,7 @@
     private Object invokeImpl(final Object selfObject, final String name, final Object... args) throws ScriptException, NoSuchMethodException {
         name.getClass(); // null check
 
-        ScriptObject invokeGlobal = null;
+        Global invokeGlobal = null;
         ScriptObjectMirror selfMirror = null;
         if (selfObject instanceof ScriptObjectMirror) {
             selfMirror = (ScriptObjectMirror)selfObject;
@@ -489,7 +489,7 @@
         } else if (selfObject instanceof ScriptObject) {
             // invokeMethod called from script code - in which case we may get 'naked' ScriptObject
             // Wrap it with oldGlobal to make a ScriptObjectMirror for the same.
-            final ScriptObject oldGlobal = Context.getGlobal();
+            final Global oldGlobal = Context.getGlobal();
             invokeGlobal = oldGlobal;
             if (oldGlobal == null) {
                 throw new IllegalArgumentException(getMessage("no.current.nashorn.global"));
@@ -502,7 +502,7 @@
             selfMirror = (ScriptObjectMirror)ScriptObjectMirror.wrap(selfObject, oldGlobal);
         } else if (selfObject == null) {
             // selfObject is null => global function call
-            final ScriptObject ctxtGlobal = getNashornGlobalFrom(context);
+            final Global ctxtGlobal = getNashornGlobalFrom(context);
             invokeGlobal = ctxtGlobal;
             selfMirror = (ScriptObjectMirror)ScriptObjectMirror.wrap(ctxtGlobal, ctxtGlobal);
         }
@@ -532,11 +532,11 @@
         return evalImpl(script, ctxt, getNashornGlobalFrom(ctxt));
     }
 
-    private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final ScriptObject ctxtGlobal) throws ScriptException {
+    private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
         if (script == null) {
             return null;
         }
-        final ScriptObject oldGlobal = Context.getGlobal();
+        final Global oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != ctxtGlobal);
         try {
             if (globalChanged) {
@@ -558,7 +558,7 @@
         }
     }
 
-    private static void throwAsScriptException(final Exception e, final ScriptObject global) throws ScriptException {
+    private static void throwAsScriptException(final Exception e, final Global global) throws ScriptException {
         if (e instanceof ScriptException) {
             throw (ScriptException)e;
         } else if (e instanceof NashornException) {
@@ -582,7 +582,7 @@
         return new CompiledScript() {
             @Override
             public Object eval(final ScriptContext ctxt) throws ScriptException {
-                final ScriptObject globalObject = getNashornGlobalFrom(ctxt);
+                final Global globalObject = getNashornGlobalFrom(ctxt);
                 // Are we running the script in the correct global?
                 if (func.getScope() == globalObject) {
                     return evalImpl(func, ctxt, globalObject);
@@ -602,8 +602,8 @@
         return compileImpl(source, getNashornGlobalFrom(ctxt));
     }
 
-    private ScriptFunction compileImpl(final Source source, final ScriptObject newGlobal) throws ScriptException {
-        final ScriptObject oldGlobal = Context.getGlobal();
+    private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException {
+        final Global oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != newGlobal);
         try {
             if (globalChanged) {
@@ -641,8 +641,7 @@
         return true;
     }
 
-    private static boolean isOfContext(final ScriptObject global, final Context context) {
-        assert global instanceof GlobalObject: "Not a Global object";
-        return ((GlobalObject)global).isOfContext(context);
+    private static boolean isOfContext(final Global global, final Context context) {
+        return global.isOfContext(context);
     }
 }
--- a/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java	Wed Jul 05 19:33:51 2017 +0200
@@ -42,10 +42,10 @@
 import java.util.Set;
 import java.util.concurrent.Callable;
 import javax.script.Bindings;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.arrays.ArrayData;
 import jdk.nashorn.internal.runtime.ConsString;
 import jdk.nashorn.internal.runtime.Context;
-import jdk.nashorn.internal.runtime.GlobalObject;
 import jdk.nashorn.internal.runtime.JSType;
 import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptObject;
@@ -64,7 +64,7 @@
     private static final AccessControlContext GET_CONTEXT_ACC_CTXT = getContextAccCtxt();
 
     private final ScriptObject sobj;
-    private final ScriptObject global;
+    private final Global  global;
     private final boolean strict;
 
     @Override
@@ -95,7 +95,7 @@
 
     @Override
     public Object call(final Object thiz, final Object... args) {
-        final ScriptObject oldGlobal = Context.getGlobal();
+        final Global oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
 
         try {
@@ -125,7 +125,7 @@
 
     @Override
     public Object newObject(final Object... args) {
-        final ScriptObject oldGlobal = Context.getGlobal();
+        final Global oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
 
         try {
@@ -171,7 +171,7 @@
 
     public Object callMember(final String functionName, final Object... args) {
         functionName.getClass(); // null check
-        final ScriptObject oldGlobal = Context.getGlobal();
+        final Global oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
 
         try {
@@ -642,7 +642,7 @@
      */
     public static Object wrap(final Object obj, final Object homeGlobal) {
         if(obj instanceof ScriptObject) {
-            return homeGlobal instanceof ScriptObject ? new ScriptObjectMirror((ScriptObject)obj, (ScriptObject)homeGlobal) : obj;
+            return homeGlobal instanceof Global ? new ScriptObjectMirror((ScriptObject)obj, (Global)homeGlobal) : obj;
         }
         if(obj instanceof ConsString) {
             return obj.toString();
@@ -710,13 +710,13 @@
 
     // package-privates below this.
 
-    ScriptObjectMirror(final ScriptObject sobj, final ScriptObject global) {
+    ScriptObjectMirror(final ScriptObject sobj, final Global global) {
         assert sobj != null : "ScriptObjectMirror on null!";
-        assert global instanceof GlobalObject : "global is not a GlobalObject";
+        assert global != null : "home Global is null";
 
         this.sobj = sobj;
         this.global = global;
-        this.strict = ((GlobalObject)global).isStrictContext();
+        this.strict = global.isStrictContext();
     }
 
     // accessors for script engine
@@ -724,7 +724,7 @@
         return sobj;
     }
 
-    ScriptObject getHomeGlobal() {
+    Global getHomeGlobal() {
         return global;
     }
 
@@ -734,7 +734,7 @@
 
     // internals only below this.
     private <V> V inGlobal(final Callable<V> callable) {
-        final ScriptObject oldGlobal = Context.getGlobal();
+        final Global oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
         if (globalChanged) {
             Context.setGlobal(global);
--- a/nashorn/src/jdk/nashorn/internal/codegen/Attr.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/codegen/Attr.java	Wed Jul 05 19:33:51 2017 +0200
@@ -375,10 +375,11 @@
      * @return Symbol for given name or null for redefinition.
      */
     private Symbol defineSymbol(final Block block, final String name, final int symbolFlags) {
-        int    flags  = symbolFlags;
-        Symbol symbol = findSymbol(block, name); // Locate symbol.
+        int     flags    = symbolFlags;
+        Symbol  symbol   = findSymbol(block, name); // Locate symbol.
+        boolean isGlobal = (flags & KINDMASK) == IS_GLOBAL;
 
-        if ((flags & KINDMASK) == IS_GLOBAL) {
+        if (isGlobal) {
             flags |= IS_SCOPE;
         }
 
@@ -414,6 +415,8 @@
             // Determine where to create it.
             if ((flags & Symbol.KINDMASK) == IS_VAR && ((flags & IS_INTERNAL) == IS_INTERNAL || (flags & IS_LET) == IS_LET)) {
                 symbolBlock = block; //internal vars are always defined in the block closest to them
+            } else if (isGlobal) {
+                symbolBlock = lc.getOutermostFunction().getBody();
             } else {
                 symbolBlock = lc.getFunctionBody(function);
             }
--- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java	Wed Jul 05 19:33:51 2017 +0200
@@ -685,7 +685,7 @@
             private void scopeCall(final IdentNode node, final int flags) {
                 load(node, Type.OBJECT); // Type.OBJECT as foo() makes no sense if foo == 3
                 // ScriptFunction will see CALLSITE_SCOPE and will bind scope accordingly.
-                method.loadNull(); //the 'this'
+                method.loadUndefined(Type.OBJECT); //the 'this' object
                 method.dynamicCall(callNodeType, 2 + loadArgs(args), flags);
             }
 
@@ -818,7 +818,7 @@
             protected boolean enterDefault(final Node node) {
                 // Load up function.
                 load(function, Type.OBJECT); //TODO, e.g. booleans can be used as functions
-                method.loadNull(); // ScriptFunction will figure out the correct this when it sees CALLSITE_SCOPE
+                method.loadUndefined(Type.OBJECT); // ScriptFunction will figure out the correct this when it sees CALLSITE_SCOPE
                 method.dynamicCall(callNodeType, 2 + loadArgs(args), getCallSiteFlags() | CALLSITE_SCOPE);
 
                 return false;
--- a/nashorn/src/jdk/nashorn/internal/codegen/SharedScopeCall.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/codegen/SharedScopeCall.java	Wed Jul 05 19:33:51 2017 +0200
@@ -156,7 +156,7 @@
         if (isCall) {
             method.convert(Type.OBJECT);
             // ScriptFunction will see CALLSITE_SCOPE and will bind scope accordingly.
-            method.loadNull();
+            method.loadUndefined(Type.OBJECT);
             int slot = 2;
             for (final Type type : paramTypes) {
                 method.load(type, slot++);
--- a/nashorn/src/jdk/nashorn/internal/ir/FunctionNode.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/ir/FunctionNode.java	Wed Jul 05 19:33:51 2017 +0200
@@ -164,11 +164,11 @@
     public static final int HAS_EVAL                    = 1 << 5;
 
     /** Does a nested function contain eval? If it does, then all variables in this function might be get/set by it. */
-    public static final int HAS_NESTED_EVAL = 1 << 6;
+    public static final int HAS_NESTED_EVAL             = 1 << 6;
 
     /** Does this function have any blocks that create a scope? This is used to determine if the function needs to
      * have a local variable slot for the scope symbol. */
-    public static final int HAS_SCOPE_BLOCK = 1 << 7;
+    public static final int HAS_SCOPE_BLOCK             = 1 << 7;
 
     /**
      * Flag this function as one that defines the identifier "arguments" as a function parameter or nested function
@@ -197,6 +197,9 @@
     /** Can this function be specialized? */
     public static final int CAN_SPECIALIZE              = 1 << 14;
 
+    /** Does this function use the "this" keyword? */
+    public static final int USES_THIS                   = 1 << 15;
+
     /** Does this function or any nested functions contain an eval? */
     private static final int HAS_DEEP_EVAL = HAS_EVAL | HAS_NESTED_EVAL;
 
@@ -591,6 +594,15 @@
     }
 
     /**
+     * Return {@code true} if this function makes use of the {@code this} object.
+     *
+     * @return true if function uses {@code this} object
+     */
+    public boolean usesThis() {
+        return getFlag(USES_THIS);
+    }
+
+    /**
      * Get the identifier for this function, this is its symbol.
      * @return the identifier as an IdentityNode
      */
--- a/nashorn/src/jdk/nashorn/internal/objects/AccessorPropertyDescriptor.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/AccessorPropertyDescriptor.java	Wed Jul 05 19:33:51 2017 +0200
@@ -67,12 +67,8 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     AccessorPropertyDescriptor(final boolean configurable, final boolean enumerable, final Object get, final Object set, final Global global) {
-        super(global.getObjectPrototype(), getInitialMap());
+        super(global.getObjectPrototype(), $nasgenmap$);
         this.configurable = configurable;
         this.enumerable   = enumerable;
         this.get          = get;
--- a/nashorn/src/jdk/nashorn/internal/objects/ArrayBufferView.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/ArrayBufferView.java	Wed Jul 05 19:33:51 2017 +0200
@@ -42,12 +42,8 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     private ArrayBufferView(final NativeArrayBuffer buffer, final int byteOffset, final int elementLength, final Global global) {
-        super(getInitialMap());
+        super($nasgenmap$);
         checkConstructorArgs(buffer, byteOffset, elementLength);
         this.setProto(getPrototype(global));
         this.setArray(factory().createArrayData(buffer, byteOffset, elementLength));
--- a/nashorn/src/jdk/nashorn/internal/objects/DataPropertyDescriptor.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/DataPropertyDescriptor.java	Wed Jul 05 19:33:51 2017 +0200
@@ -64,12 +64,8 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     DataPropertyDescriptor(final boolean configurable, final boolean enumerable, final boolean writable, final Object value, final Global global) {
-        super(global.getObjectPrototype(), getInitialMap());
+        super(global.getObjectPrototype(), $nasgenmap$);
         this.configurable = configurable;
         this.enumerable   = enumerable;
         this.writable     = writable;
--- a/nashorn/src/jdk/nashorn/internal/objects/GenericPropertyDescriptor.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/GenericPropertyDescriptor.java	Wed Jul 05 19:33:51 2017 +0200
@@ -55,12 +55,8 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     GenericPropertyDescriptor(final boolean configurable, final boolean enumerable, final Global global) {
-        super(global.getObjectPrototype(), getInitialMap());
+        super(global.getObjectPrototype(), $nasgenmap$);
         this.configurable = configurable;
         this.enumerable   = enumerable;
     }
--- a/nashorn/src/jdk/nashorn/internal/objects/Global.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/Global.java	Wed Jul 05 19:33:51 2017 +0200
@@ -33,11 +33,8 @@
 import java.io.PrintWriter;
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.SoftReference;
 import java.lang.reflect.Field;
 import java.util.Arrays;
-import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.Callable;
@@ -51,7 +48,6 @@
 import jdk.nashorn.internal.runtime.ConsString;
 import jdk.nashorn.internal.runtime.Context;
 import jdk.nashorn.internal.runtime.GlobalFunctions;
-import jdk.nashorn.internal.runtime.GlobalObject;
 import jdk.nashorn.internal.runtime.JSType;
 import jdk.nashorn.internal.runtime.NativeJavaPackage;
 import jdk.nashorn.internal.runtime.PropertyDescriptor;
@@ -59,10 +55,10 @@
 import jdk.nashorn.internal.runtime.Scope;
 import jdk.nashorn.internal.runtime.ScriptEnvironment;
 import jdk.nashorn.internal.runtime.ScriptFunction;
+import jdk.nashorn.internal.runtime.ScriptFunctionData;
 import jdk.nashorn.internal.runtime.ScriptObject;
 import jdk.nashorn.internal.runtime.ScriptRuntime;
 import jdk.nashorn.internal.runtime.ScriptingFunctions;
-import jdk.nashorn.internal.runtime.Source;
 import jdk.nashorn.internal.runtime.arrays.ArrayData;
 import jdk.nashorn.internal.runtime.linker.Bootstrap;
 import jdk.nashorn.internal.runtime.linker.InvokeByName;
@@ -73,7 +69,7 @@
  * Representation of global scope.
  */
 @ScriptClass("Global")
-public final class Global extends ScriptObject implements GlobalObject, Scope {
+public final class Global extends ScriptObject implements Scope {
     private final InvokeByName TO_STRING = new InvokeByName("toString", ScriptObject.class);
     private final InvokeByName VALUE_OF  = new InvokeByName("valueOf",  ScriptObject.class);
 
@@ -229,6 +225,10 @@
     @Property(name = "ArrayBuffer", attributes = Attribute.NOT_ENUMERABLE)
     public volatile Object arrayBuffer;
 
+    /** DataView object */
+    @Property(name = "DataView", attributes = Attribute.NOT_ENUMERABLE)
+    public volatile Object dataView;
+
     /** TypedArray (int8) */
     @Property(name = "Int8Array", attributes = Attribute.NOT_ENUMERABLE)
     public volatile Object int8Array;
@@ -355,6 +355,7 @@
     private ScriptObject   builtinJavaImporter;
     private ScriptObject   builtinJavaApi;
     private ScriptObject   builtinArrayBuffer;
+    private ScriptObject   builtinDataView;
     private ScriptObject   builtinInt8Array;
     private ScriptObject   builtinUint8Array;
     private ScriptObject   builtinUint8ClampedArray;
@@ -373,9 +374,6 @@
     // Flag to indicate that a split method issued a return statement
     private int splitState = -1;
 
-    // class cache
-    private ClassCache classCache;
-
     // Used to store the last RegExp result to support deprecated RegExp constructor properties
     private RegExpResult lastRegExpResult;
 
@@ -426,11 +424,6 @@
         super(checkAndGetMap(context));
         this.context = context;
         this.setIsScope();
-
-        final int cacheSize = context.getEnv()._class_cache_size;
-        if (cacheSize > 0) {
-            classCache = new ClassCache(cacheSize);
-        }
     }
 
     /**
@@ -439,11 +432,9 @@
      * @return the global singleton
      */
     public static Global instance() {
-        ScriptObject global = Context.getGlobal();
-        if (! (global instanceof Global)) {
-            throw new IllegalStateException("no current global instance");
-        }
-        return (Global)global;
+        Global global = Context.getGlobal();
+        global.getClass(); // null check
+        return global;
     }
 
     /**
@@ -464,19 +455,30 @@
         return instance().getContext();
     }
 
-    // GlobalObject interface implementation
+    // Runtime interface to Global
 
-    @Override
+    /**
+     * Is this global of the given Context?
+     * @param ctxt the context
+     * @return true if this global belongs to the given Context
+     */
     public boolean isOfContext(final Context ctxt) {
         return this.context == ctxt;
     }
 
-    @Override
+    /**
+     * Does this global belong to a strict Context?
+     * @return true if this global belongs to a strict Context
+     */
     public boolean isStrictContext() {
         return context.getEnv()._strict;
     }
 
-    @Override
+    /**
+     * Initialize standard builtin objects like "Object", "Array", "Function" etc.
+     * as well as our extension builtin objects like "Java", "JSAdapter" as properties
+     * of the global scope object.
+     */
     public void initBuiltinObjects() {
         if (this.builtinObject != null) {
             // already initialized, just return
@@ -486,12 +488,26 @@
         init();
     }
 
-    @Override
+    /**
+     * Create a new ScriptFunction object
+     *
+     * @param name   function name
+     * @param handle invocation handle for function
+     * @param scope  the scope
+     * @param strict are we in strict mode
+     *
+     * @return new script function
+     */
     public ScriptFunction newScriptFunction(final String name, final MethodHandle handle, final ScriptObject scope, final boolean strict) {
-        return new ScriptFunctionImpl(name, handle, scope, null, strict, false, true);
+        return new ScriptFunctionImpl(name, handle, scope, null, strict ? ScriptFunctionData.IS_STRICT_CONSTRUCTOR : ScriptFunctionData.IS_CONSTRUCTOR);
     }
 
-    @Override
+    /**
+     * Wrap a Java object as corresponding script object
+     *
+     * @param obj object to wrap
+     * @return    wrapped object
+     */
     public Object wrapAsObject(final Object obj) {
         if (obj instanceof Boolean) {
             return new NativeBoolean((Boolean)obj, this);
@@ -513,7 +529,14 @@
         }
     }
 
-    @Override
+    /**
+     * Lookup helper for JS primitive types
+     *
+     * @param request the link request for the dynamic call site.
+     * @param self     self reference
+     *
+     * @return guarded invocation
+     */
     public GuardedInvocation primitiveLookup(final LinkRequest request, final Object self) {
         if (self instanceof String || self instanceof ConsString) {
             return NativeString.lookupPrimitive(request, self);
@@ -525,12 +548,23 @@
         throw new IllegalArgumentException("Unsupported primitive: " + self);
     }
 
-    @Override
+    /**
+     * Create a new empty script object
+     *
+     * @return the new ScriptObject
+     */
     public ScriptObject newObject() {
         return new JO(getObjectPrototype(), JO.getInitialMap());
     }
 
-    @Override
+    /**
+     * Default value of given type
+     *
+     * @param sobj     script object
+     * @param typeHint type hint
+     *
+     * @return default value
+     */
     public Object getDefaultValue(final ScriptObject sobj, final Class<?> typeHint) {
         // When the [[DefaultValue]] internal method of O is called with no hint,
         // then it behaves as if the hint were Number, unless O is a Date object
@@ -590,7 +624,12 @@
         return UNDEFINED;
     }
 
-    @Override
+    /**
+     * Is the given ScriptObject an ECMAScript Error object?
+     *
+     * @param sobj the object being checked
+     * @return true if sobj is an Error object
+     */
     public boolean isError(final ScriptObject sobj) {
         final ScriptObject errorProto = getErrorPrototype();
         ScriptObject proto = sobj.getProto();
@@ -603,52 +642,108 @@
         return false;
     }
 
-    @Override
+    /**
+     * Create a new ECMAScript Error object.
+     *
+     * @param msg error message
+     * @return newly created Error object
+     */
     public ScriptObject newError(final String msg) {
         return new NativeError(msg, this);
     }
 
-    @Override
+    /**
+     * Create a new ECMAScript EvalError object.
+     *
+     * @param msg error message
+     * @return newly created EvalError object
+     */
     public ScriptObject newEvalError(final String msg) {
         return new NativeEvalError(msg, this);
     }
 
-    @Override
+    /**
+     * Create a new ECMAScript RangeError object.
+     *
+     * @param msg error message
+     * @return newly created RangeError object
+     */
     public ScriptObject newRangeError(final String msg) {
         return new NativeRangeError(msg, this);
     }
 
-    @Override
+    /**
+     * Create a new ECMAScript ReferenceError object.
+     *
+     * @param msg error message
+     * @return newly created ReferenceError object
+     */
     public ScriptObject newReferenceError(final String msg) {
         return new NativeReferenceError(msg, this);
     }
 
-    @Override
+    /**
+     * Create a new ECMAScript SyntaxError object.
+     *
+     * @param msg error message
+     * @return newly created SyntaxError object
+     */
     public ScriptObject newSyntaxError(final String msg) {
         return new NativeSyntaxError(msg, this);
     }
 
-    @Override
+    /**
+     * Create a new ECMAScript TypeError object.
+     *
+     * @param msg error message
+     * @return newly created TypeError object
+     */
     public ScriptObject newTypeError(final String msg) {
         return new NativeTypeError(msg, this);
     }
 
-    @Override
+    /**
+     * Create a new ECMAScript URIError object.
+     *
+     * @param msg error message
+     * @return newly created URIError object
+     */
     public ScriptObject newURIError(final String msg) {
         return new NativeURIError(msg, this);
     }
 
-    @Override
+    /**
+     * Create a new ECMAScript GenericDescriptor object.
+     *
+     * @param configurable is the property configurable?
+     * @param enumerable is the property enumerable?
+     * @return newly created GenericDescriptor object
+     */
     public PropertyDescriptor newGenericDescriptor(final boolean configurable, final boolean enumerable) {
         return new GenericPropertyDescriptor(configurable, enumerable, this);
     }
 
-    @Override
+    /**
+     * Create a new ECMAScript DatePropertyDescriptor object.
+     *
+     * @param value of the data property
+     * @param configurable is the property configurable?
+     * @param enumerable is the property enumerable?
+     * @return newly created DataPropertyDescriptor object
+     */
     public PropertyDescriptor newDataDescriptor(final Object value, final boolean configurable, final boolean enumerable, final boolean writable) {
         return new DataPropertyDescriptor(configurable, enumerable, writable, value, this);
     }
 
-    @Override
+    /**
+     * Create a new ECMAScript AccessorPropertyDescriptor object.
+     *
+     * @param get getter function of the user accessor property
+     * @param set setter function of the user accessor property
+     * @param configurable is the property configurable?
+     * @param enumerable is the property enumerable?
+     * @return newly created AccessorPropertyDescriptor object
+     */
     public PropertyDescriptor newAccessorDescriptor(final Object get, final Object set, final boolean configurable, final boolean enumerable) {
         final AccessorPropertyDescriptor desc = new AccessorPropertyDescriptor(configurable, enumerable, get == null ? UNDEFINED : get, set == null ? UNDEFINED : set, this);
 
@@ -664,62 +759,6 @@
     }
 
 
-    /**
-     * Cache for compiled script classes.
-     */
-    @SuppressWarnings("serial")
-    private static class ClassCache extends LinkedHashMap<Source, ClassReference> {
-        private final int size;
-        private final ReferenceQueue<Class<?>> queue;
-
-        ClassCache(int size) {
-            super(size, 0.75f, true);
-            this.size = size;
-            this.queue = new ReferenceQueue<>();
-        }
-
-        void cache(final Source source, final Class<?> clazz) {
-            put(source, new ClassReference(clazz, queue, source));
-        }
-
-        @Override
-        protected boolean removeEldestEntry(final Map.Entry<Source, ClassReference> eldest) {
-            return size() > size;
-        }
-
-        @Override
-        public ClassReference get(Object key) {
-            for (ClassReference ref; (ref = (ClassReference)queue.poll()) != null; ) {
-                remove(ref.source);
-            }
-            return super.get(key);
-        }
-
-    }
-
-    private static class ClassReference extends SoftReference<Class<?>> {
-        private final Source source;
-
-        ClassReference(final Class<?> clazz, final ReferenceQueue<Class<?>> queue, final Source source) {
-            super(clazz, queue);
-            this.source = source;
-        }
-    }
-
-    // Class cache management
-    @Override
-    public Class<?> findCachedClass(final Source source) {
-        assert classCache != null : "Class cache used without being initialized";
-        ClassReference ref = classCache.get(source);
-        return ref != null ? ref.get() : null;
-    }
-
-    @Override
-    public void cacheClass(final Source source, final Class<?> clazz) {
-        assert classCache != null : "Class cache used without being initialized";
-        classCache.cache(source, clazz);
-    }
-
     private static <T> T getLazilyCreatedValue(final Object key, final Callable<T> creator, final Map<Object, T> map) {
         final T obj = map.get(key);
         if (obj != null) {
@@ -737,14 +776,25 @@
 
     private final Map<Object, InvokeByName> namedInvokers = new ConcurrentHashMap<>();
 
-    @Override
+
+    /**
+     * Get cached InvokeByName object for the given key
+     * @param key key to be associated with InvokeByName object
+     * @param creator if InvokeByName is absent 'creator' is called to make one (lazy init)
+     * @return InvokeByName object associated with the key.
+     */
     public InvokeByName getInvokeByName(final Object key, final Callable<InvokeByName> creator) {
         return getLazilyCreatedValue(key, creator, namedInvokers);
     }
 
     private final Map<Object, MethodHandle> dynamicInvokers = new ConcurrentHashMap<>();
 
-    @Override
+    /**
+     * Get cached dynamic method handle for the given key
+     * @param key key to be associated with dynamic method handle
+     * @param creator if method handle is absent 'creator' is called to make one (lazy init)
+     * @return dynamic method handle associated with the key.
+     */
     public MethodHandle getDynamicInvoker(final Object key, final Callable<MethodHandle> creator) {
         return getLazilyCreatedValue(key, creator, dynamicInvokers);
     }
@@ -933,6 +983,10 @@
         return ScriptFunction.getPrototype(builtinArrayBuffer);
     }
 
+    ScriptObject getDataViewPrototype() {
+        return ScriptFunction.getPrototype(builtinDataView);
+    }
+
     ScriptObject getInt8ArrayPrototype() {
         return ScriptFunction.getPrototype(builtinInt8Array);
     }
@@ -1701,6 +1755,7 @@
 
     private void initTypedArray() {
         this.builtinArrayBuffer       = initConstructor("ArrayBuffer");
+        this.builtinDataView          = initConstructor("DataView");
         this.builtinInt8Array         = initConstructor("Int8Array");
         this.builtinUint8Array        = initConstructor("Uint8Array");
         this.builtinUint8ClampedArray = initConstructor("Uint8ClampedArray");
@@ -1741,6 +1796,7 @@
         this.typeError         = this.builtinTypeError;
         this.uriError          = this.builtinURIError;
         this.arrayBuffer       = this.builtinArrayBuffer;
+        this.dataView          = this.builtinDataView;
         this.int8Array         = this.builtinInt8Array;
         this.uint8Array        = this.builtinUint8Array;
         this.uint8ClampedArray = this.builtinUint8ClampedArray;
@@ -1838,7 +1894,7 @@
         anon.deleteOwnProperty(anon.getMap().findProperty("prototype"));
 
         // use "getter" so that [[ThrowTypeError]] function's arity is 0 - as specified in step 10 of section 13.2.3
-        this.typeErrorThrower = new ScriptFunctionImpl("TypeErrorThrower", Lookup.TYPE_ERROR_THROWER_GETTER, null, null, false, false, false);
+        this.typeErrorThrower = new ScriptFunctionImpl("TypeErrorThrower", Lookup.TYPE_ERROR_THROWER_GETTER, null, null, 0);
         typeErrorThrower.setPrototype(UNDEFINED);
         // Non-constructor built-in functions do not have "prototype" property
         typeErrorThrower.deleteOwnProperty(typeErrorThrower.getMap().findProperty("prototype"));
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeArray.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeArray.java	Wed Jul 05 19:33:51 2017 +0200
@@ -156,10 +156,6 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     /*
      * Constructors.
      */
@@ -208,7 +204,7 @@
     }
 
     NativeArray(final ArrayData arrayData, final Global global) {
-        super(global.getArrayPrototype(), getInitialMap());
+        super(global.getArrayPrototype(), $nasgenmap$);
         this.setArray(arrayData);
         this.setIsArray();
     }
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeArrayBuffer.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeArrayBuffer.java	Wed Jul 05 19:33:51 2017 +0200
@@ -25,6 +25,7 @@
 
 package jdk.nashorn.internal.objects;
 
+import java.nio.ByteBuffer;
 import java.util.Arrays;
 import jdk.nashorn.internal.objects.annotations.Attribute;
 import jdk.nashorn.internal.objects.annotations.Constructor;
@@ -43,10 +44,6 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     @Constructor(arity = 1)
     public static Object constructor(final boolean newObj, final Object self, final Object... args) {
         if (args.length == 0) {
@@ -57,7 +54,7 @@
     }
 
     protected NativeArrayBuffer(final byte[] byteArray, final Global global) {
-        super(global.getArrayBufferPrototype(), getInitialMap());
+        super(global.getArrayBufferPrototype(), $nasgenmap$);
         this.buffer = byteArray;
     }
 
@@ -128,4 +125,16 @@
     public int getByteLength() {
         return buffer.length;
     }
+
+    ByteBuffer getBuffer() {
+       return ByteBuffer.wrap(buffer);
+    }
+
+    ByteBuffer getBuffer(final int offset) {
+        return ByteBuffer.wrap(buffer, offset, buffer.length - offset);
+    }
+
+    ByteBuffer getBuffer(final int offset, final int length) {
+        return ByteBuffer.wrap(buffer, offset, length);
+    }
 }
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeBoolean.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeBoolean.java	Wed Jul 05 19:33:51 2017 +0200
@@ -30,6 +30,7 @@
 
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
 import jdk.internal.dynalink.linker.GuardedInvocation;
 import jdk.internal.dynalink.linker.LinkRequest;
 import jdk.nashorn.internal.objects.annotations.Attribute;
@@ -50,22 +51,21 @@
 public final class NativeBoolean extends ScriptObject {
     private final boolean value;
 
-    final static MethodHandle WRAPFILTER = findWrapFilter();
+    // Method handle to create an object wrapper for a primitive boolean
+    private static final MethodHandle WRAPFILTER = findOwnMH("wrapFilter", MH.type(NativeBoolean.class, Object.class));
+    // Method handle to retrieve the Boolean prototype object
+    private static final MethodHandle PROTOFILTER = findOwnMH("protoFilter", MH.type(Object.class, Object.class));
 
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     private NativeBoolean(final boolean value, final ScriptObject proto, final PropertyMap map) {
         super(proto, map);
         this.value = value;
     }
 
     NativeBoolean(final boolean flag, final Global global) {
-        this(flag, global.getBooleanPrototype(), getInitialMap());
+        this(flag, global.getBooleanPrototype(), $nasgenmap$);
     }
 
     NativeBoolean(final boolean flag) {
@@ -164,7 +164,7 @@
      * @return Link to be invoked at call site.
      */
     public static GuardedInvocation lookupPrimitive(final LinkRequest request, final Object receiver) {
-        return PrimitiveLookup.lookupPrimitive(request, Boolean.class, new NativeBoolean((Boolean)receiver), WRAPFILTER);
+        return PrimitiveLookup.lookupPrimitive(request, Boolean.class, new NativeBoolean((Boolean)receiver), WRAPFILTER, PROTOFILTER);
     }
 
     /**
@@ -178,7 +178,12 @@
         return new NativeBoolean((Boolean)receiver);
     }
 
-    private static MethodHandle findWrapFilter() {
-        return MH.findStatic(MethodHandles.lookup(), NativeBoolean.class, "wrapFilter", MH.type(NativeBoolean.class, Object.class));
+    @SuppressWarnings("unused")
+    private static Object protoFilter(final Object object) {
+        return Global.instance().getBooleanPrototype();
+    }
+
+    private static MethodHandle findOwnMH(final String name, final MethodType type) {
+        return MH.findStatic(MethodHandles.lookup(), NativeBoolean.class, name, type);
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeDataView.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,1015 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 jdk.nashorn.internal.objects;
+
+import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
+import static jdk.nashorn.internal.runtime.ECMAErrors.rangeError;
+import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import jdk.nashorn.internal.objects.annotations.Attribute;
+import jdk.nashorn.internal.objects.annotations.Constructor;
+import jdk.nashorn.internal.objects.annotations.Function;
+import jdk.nashorn.internal.objects.annotations.Property;
+import jdk.nashorn.internal.objects.annotations.ScriptClass;
+import jdk.nashorn.internal.objects.annotations.SpecializedConstructor;
+import jdk.nashorn.internal.objects.annotations.SpecializedFunction;
+import jdk.nashorn.internal.runtime.JSType;
+import jdk.nashorn.internal.runtime.PropertyMap;
+import jdk.nashorn.internal.runtime.ScriptObject;
+import jdk.nashorn.internal.runtime.ScriptRuntime;
+
+/**
+ * <p>
+ * DataView builtin constructor. Based on the specification here:
+ * http://www.khronos.org/registry/typedarray/specs/latest/#8
+ * </p>
+ * <p>
+ * An ArrayBuffer is a useful object for representing an arbitrary chunk of data.
+ * In many cases, such data will be read from disk or from the network, and will
+ * not follow the alignment restrictions that are imposed on the typed array views
+ * described earlier. In addition, the data will often be heterogeneous in nature
+ * and have a defined byte order. The DataView view provides a low-level interface
+ * for reading such data from and writing it to an ArrayBuffer.
+ * </p>
+ * <p>
+ * Regardless of the host computer's endianness, DataView reads or writes values
+ * to or from main memory with a specified endianness: big or little.
+ * </p>
+ */
+@ScriptClass("DataView")
+public class NativeDataView extends ScriptObject {
+    // initialized by nasgen
+    private static PropertyMap $nasgenmap$;
+
+    // inherited ArrayBufferView properties
+
+    /**
+     * Underlying ArrayBuffer storage object
+     */
+    @Property(attributes = Attribute.NON_ENUMERABLE_CONSTANT)
+    public final Object buffer;
+
+    /**
+     * The offset in bytes from the start of the ArrayBuffer
+     */
+    @Property(attributes = Attribute.NON_ENUMERABLE_CONSTANT)
+    public final int byteOffset;
+
+    /**
+     * The number of bytes from the offset that this DataView will reference
+     */
+    @Property(attributes = Attribute.NON_ENUMERABLE_CONSTANT)
+    public final int byteLength;
+
+    // underlying ByteBuffer
+    private final ByteBuffer buf;
+
+    private NativeDataView(NativeArrayBuffer arrBuf) {
+        this(arrBuf, arrBuf.getBuffer(), 0);
+    }
+
+    private NativeDataView(NativeArrayBuffer arrBuf, int offset) {
+        this(arrBuf, bufferFrom(arrBuf, offset), offset);
+    }
+
+    private NativeDataView(NativeArrayBuffer arrBuf, int offset, int length) {
+        this(arrBuf, bufferFrom(arrBuf, offset, length), offset, length);
+    }
+
+    private NativeDataView(final NativeArrayBuffer arrBuf, final ByteBuffer buf, final int offset) {
+       this(arrBuf, buf, offset, buf.capacity() - offset);
+    }
+
+    private NativeDataView(final NativeArrayBuffer arrBuf, final ByteBuffer buf, final int offset, final int length) {
+        super(Global.instance().getDataViewPrototype(), $nasgenmap$);
+        this.buffer = arrBuf;
+        this.byteOffset = offset;
+        this.byteLength = length;
+        this.buf = buf;
+    }
+
+    /**
+     * Create a new DataView object using the passed ArrayBuffer for its
+     * storage. Optional byteOffset and byteLength can be used to limit the
+     * section of the buffer referenced. The byteOffset indicates the offset in
+     * bytes from the start of the ArrayBuffer, and the byteLength is the number
+     * of bytes from the offset that this DataView will reference. If both
+     * byteOffset and byteLength are omitted, the DataView spans the entire
+     * ArrayBuffer range. If the byteLength is omitted, the DataView extends from
+     * the given byteOffset until the end of the ArrayBuffer.
+     *
+     * If the given byteOffset and byteLength references an area beyond the end
+     * of the ArrayBuffer an exception is raised.
+
+     * @param newObj if this constructor was invoked with 'new' or not
+     * @param self   constructor function object
+     * @param args   arguments to the constructor
+     * @return newly constructed DataView object
+     */
+    @Constructor(arity = 1)
+    public static Object constructor(final boolean newObj, final Object self, final Object... args) {
+        if (args.length == 0 || !(args[0] instanceof NativeArrayBuffer)) {
+            throw typeError("not.an.arraybuffer.in.dataview");
+        }
+
+        final NativeArrayBuffer arrBuf = (NativeArrayBuffer) args[0];
+        switch (args.length) {
+            case 1:
+                return new NativeDataView(arrBuf);
+            case 2:
+                return new NativeDataView(arrBuf, JSType.toInt32(args[1]));
+            default:
+                return new NativeDataView(arrBuf, JSType.toInt32(args[1]), JSType.toInt32(args[2]));
+        }
+    }
+
+    /**
+     * Specialized version of DataView constructor
+     *
+     * @param newObj if this constructor was invoked with 'new' or not
+     * @param self   constructor function object
+     * @param arrBuf underlying ArrayBuffer storage object
+     * @param offset offset in bytes from the start of the ArrayBuffer
+     * @return newly constructed DataView object
+     */
+    @SpecializedConstructor
+    public static Object constructor(final boolean newObj, final Object self, final Object arrBuf, final int offset) {
+        if (!(arrBuf instanceof NativeArrayBuffer)) {
+            throw typeError("not.an.arraybuffer.in.dataview");
+        }
+        return new NativeDataView((NativeArrayBuffer) arrBuf, offset);
+    }
+
+    /**
+     * Specialized version of DataView constructor
+     *
+     * @param newObj if this constructor was invoked with 'new' or not
+     * @param self   constructor function object
+     * @param arrBuf underlying ArrayBuffer storage object
+     * @param offset in bytes from the start of the ArrayBuffer
+     * @param length is the number of bytes from the offset that this DataView will reference
+     * @return newly constructed DataView object
+     */
+    @SpecializedConstructor
+    public static Object constructor(final boolean newObj, final Object self, final Object arrBuf, final int offset, final int length) {
+        if (!(arrBuf instanceof NativeArrayBuffer)) {
+            throw typeError("not.an.arraybuffer.in.dataview");
+        }
+        return new NativeDataView((NativeArrayBuffer) arrBuf, offset, length);
+    }
+
+    // Gets the value of the given type at the specified byte offset
+    // from the start of the view. There is no alignment constraint;
+    // multi-byte values may be fetched from any offset.
+    //
+    // For multi-byte values, the optional littleEndian argument
+    // indicates whether a big-endian or little-endian value should be
+    // read. If false or undefined, a big-endian value is read.
+    //
+    // These methods raise an exception if they would read
+    // beyond the end of the view.
+
+    /**
+     * Get 8-bit signed int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @return 8-bit signed int value at the byteOffset
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE)
+    public static int getInt8(final Object self, final Object byteOffset) {
+        try {
+            return getBuffer(self).get(JSType.toInt32(byteOffset));
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 8-bit signed int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @return 8-bit signed int value at the byteOffset
+     */
+    @SpecializedFunction
+    public static int getInt8(final Object self, final int byteOffset) {
+        try {
+            return getBuffer(self).get(byteOffset);
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 8-bit unsigned int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @return 8-bit unsigned int value at the byteOffset
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE)
+    public static int getUint8(final Object self, final Object byteOffset) {
+        try {
+            return (0xFF & getBuffer(self).get(JSType.toInt32(byteOffset)));
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 8-bit unsigned int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @return 8-bit unsigned int value at the byteOffset
+     */
+    @SpecializedFunction
+    public static int getUint8(final Object self, final int byteOffset) {
+        try {
+            return (0xFF & getBuffer(self).get(byteOffset));
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 16-bit signed int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param littleEndian (optional) flag indicating whether to read in little endian order
+     * @return 16-bit signed int value at the byteOffset
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
+    public static int getInt16(final Object self, final Object byteOffset, final Object littleEndian) {
+        try {
+            return getBuffer(self, littleEndian).getShort(JSType.toInt32(byteOffset));
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 16-bit signed int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @return 16-bit signed int value at the byteOffset
+     */
+    @SpecializedFunction
+    public static int getInt16(final Object self, final int byteOffset) {
+        try {
+            return getBuffer(self, false).getShort(byteOffset);
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 16-bit signed int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param littleEndian (optional) flag indicating whether to read in little endian order
+     * @return 16-bit signed int value at the byteOffset
+     */
+    @SpecializedFunction
+    public static int getInt16(final Object self, final int byteOffset, final boolean littleEndian) {
+        try {
+            return getBuffer(self, littleEndian).getShort(byteOffset);
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 16-bit unsigned int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param littleEndian (optional) flag indicating whether to read in little endian order
+     * @return 16-bit unsigned int value at the byteOffset
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
+    public static int getUint16(final Object self, final Object byteOffset, final Object littleEndian) {
+        try {
+            return (int) (0xFFFF & getBuffer(self, littleEndian).getShort(JSType.toInt32(byteOffset)));
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 16-bit unsigned int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @return 16-bit unsigned int value at the byteOffset
+     */
+    @SpecializedFunction
+    public static int getUint16(final Object self, final int byteOffset) {
+        try {
+            return (int) (0xFFFF & getBuffer(self, false).getShort(byteOffset));
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 16-bit unsigned int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param littleEndian (optional) flag indicating whether to read in little endian order
+     * @return 16-bit unsigned int value at the byteOffset
+     */
+    @SpecializedFunction
+    public static int getUint16(final Object self, final int byteOffset, final boolean littleEndian) {
+        try {
+            return (int) (0xFFFF & getBuffer(self, littleEndian).getShort(byteOffset));
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 32-bit signed int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param littleEndian (optional) flag indicating whether to read in little endian order
+     * @return 32-bit signed int value at the byteOffset
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
+    public static int getInt32(final Object self, final Object byteOffset, final Object littleEndian) {
+        try {
+            return getBuffer(self, littleEndian).getInt(JSType.toInt32(byteOffset));
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 32-bit signed int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @return 32-bit signed int value at the byteOffset
+     */
+    @SpecializedFunction
+    public static int getInt32(final Object self, final int byteOffset) {
+        try {
+            return getBuffer(self, false).getInt(byteOffset);
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 32-bit signed int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param littleEndian (optional) flag indicating whether to read in little endian order
+     * @return 32-bit signed int value at the byteOffset
+     */
+    @SpecializedFunction
+    public static int getInt32(final Object self, final int byteOffset, final boolean littleEndian) {
+        try {
+            return getBuffer(self, littleEndian).getInt(byteOffset);
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 32-bit unsigned int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param littleEndian (optional) flag indicating whether to read in little endian order
+     * @return 32-bit unsigned int value at the byteOffset
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
+    public static long getUint32(final Object self, final Object byteOffset, final Object littleEndian) {
+        try {
+            return (long) (0xFFFFFFFFL & getBuffer(self, littleEndian).getInt(JSType.toInt32(byteOffset)));
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 32-bit unsigned int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @return 32-bit unsigned int value at the byteOffset
+     */
+    @SpecializedFunction
+    public static long getUint32(final Object self, final int byteOffset) {
+        try {
+            return (long) (0xFFFFFFFFL & getBuffer(self, false).getInt(JSType.toInt32(byteOffset)));
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 32-bit unsigned int from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param littleEndian (optional) flag indicating whether to read in little endian order
+     * @return 32-bit unsigned int value at the byteOffset
+     */
+    @SpecializedFunction
+    public static long getUint32(final Object self, final int byteOffset, final boolean littleEndian) {
+        try {
+            return (long) (0xFFFFFFFFL & getBuffer(self, littleEndian).getInt(JSType.toInt32(byteOffset)));
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 32-bit float value from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param littleEndian (optional) flag indicating whether to read in little endian order
+     * @return 32-bit float value at the byteOffset
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
+    public static double getFloat32(final Object self, final Object byteOffset, final Object littleEndian) {
+        try {
+            return getBuffer(self, littleEndian).getFloat(JSType.toInt32(byteOffset));
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 32-bit float value from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @return 32-bit float value at the byteOffset
+     */
+    @SpecializedFunction
+    public static double getFloat32(final Object self, final int byteOffset) {
+        try {
+            return getBuffer(self, false).getFloat(byteOffset);
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 32-bit float value from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param littleEndian (optional) flag indicating whether to read in little endian order
+     * @return 32-bit float value at the byteOffset
+     */
+    @SpecializedFunction
+    public static double getFloat32(final Object self, final int byteOffset, final boolean littleEndian) {
+        try {
+            return getBuffer(self, littleEndian).getFloat(byteOffset);
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 64-bit float value from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param littleEndian (optional) flag indicating whether to read in little endian order
+     * @return 64-bit float value at the byteOffset
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
+    public static double getFloat64(final Object self, final Object byteOffset, final Object littleEndian) {
+        try {
+            return getBuffer(self, littleEndian).getDouble(JSType.toInt32(byteOffset));
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 64-bit float value from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @return 64-bit float value at the byteOffset
+     */
+    @SpecializedFunction
+    public static double getFloat64(final Object self, final int byteOffset) {
+        try {
+            return getBuffer(self, false).getDouble(byteOffset);
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Get 64-bit float value from given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param littleEndian (optional) flag indicating whether to read in little endian order
+     * @return 64-bit float value at the byteOffset
+     */
+    @SpecializedFunction
+    public static double getFloat64(final Object self, final int byteOffset, final boolean littleEndian) {
+        try {
+            return getBuffer(self, littleEndian).getDouble(byteOffset);
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    // Stores a value of the given type at the specified byte offset
+    // from the start of the view. There is no alignment constraint;
+    // multi-byte values may be stored at any offset.
+    //
+    // For multi-byte values, the optional littleEndian argument
+    // indicates whether the value should be stored in big-endian or
+    // little-endian byte order. If false or undefined, the value is
+    // stored in big-endian byte order.
+    //
+    // These methods raise an exception if they would write
+    // beyond the end of the view.
+
+    /**
+     * Set 8-bit signed int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param value byte value to set
+     * @return undefined
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
+    public static Object setInt8(final Object self, final Object byteOffset, final Object value) {
+        try {
+            getBuffer(self).put(JSType.toInt32(byteOffset), (byte)JSType.toInt32(value));
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 8-bit signed int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to read from
+     * @param value byte value to set
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setInt8(final Object self, final int byteOffset, final int value) {
+        try {
+            getBuffer(self).put(byteOffset, (byte)value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 8-bit unsigned int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value byte value to set
+     * @return undefined
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
+    public static Object setUint8(final Object self, final Object byteOffset, final Object value) {
+        try {
+            getBuffer(self).put(JSType.toInt32(byteOffset), (byte)JSType.toInt32(value));
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 8-bit unsigned int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value byte value to set
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setUint8(final Object self, final int byteOffset, final int value) {
+        try {
+            getBuffer(self).put(byteOffset, (byte)value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 16-bit signed int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value short value to set
+     * @param littleEndian (optional) flag indicating whether to write in little endian order
+     * @return undefined
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
+    public static Object setInt16(final Object self, final Object byteOffset, final Object value, final Object littleEndian) {
+        try {
+            getBuffer(self, littleEndian).putShort(JSType.toInt32(byteOffset), (short)JSType.toInt32(value));
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 16-bit signed int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value short value to set
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setInt16(final Object self, final int byteOffset, final int value) {
+        try {
+            getBuffer(self, false).putShort(byteOffset, (short)value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 16-bit signed int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value short value to set
+     * @param littleEndian (optional) flag indicating whether to write in little endian order
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setInt16(final Object self, final int byteOffset, final int value, final boolean littleEndian) {
+        try {
+            getBuffer(self, littleEndian).putShort(byteOffset, (short)value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 16-bit unsigned int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value short value to set
+     * @param littleEndian (optional) flag indicating whether to write in little endian order
+     * @return undefined
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
+    public static Object setUint16(final Object self, final Object byteOffset, final Object value, final Object littleEndian) {
+        try {
+            getBuffer(self, littleEndian).putShort(JSType.toInt32(byteOffset), (short)JSType.toInt32(value));
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 16-bit unsigned int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value short value to set
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setUint16(final Object self, final int byteOffset, final int value) {
+        try {
+            getBuffer(self, false).putShort(byteOffset, (short)value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 16-bit unsigned int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value short value to set
+     * @param littleEndian (optional) flag indicating whether to write in little endian order
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setUint16(final Object self, final int byteOffset, final int value, final boolean littleEndian) {
+        try {
+            getBuffer(self, littleEndian).putShort(byteOffset, (short)value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 32-bit signed int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value int value to set
+     * @param littleEndian (optional) flag indicating whether to write in little endian order
+     * @return undefined
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
+    public static Object setInt32(final Object self, final Object byteOffset, final Object value, final Object littleEndian) {
+        try {
+            getBuffer(self, littleEndian).putInt(JSType.toInt32(byteOffset), (int)JSType.toInt32(value));
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 32-bit signed int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value int value to set
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setInt32(final Object self, final int byteOffset, final int value) {
+        try {
+            getBuffer(self, false).putInt(byteOffset, value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 32-bit signed int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value int value to set
+     * @param littleEndian (optional) flag indicating whether to write in little endian order
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setInt32(final Object self, final int byteOffset, final int value, final boolean littleEndian) {
+        try {
+            getBuffer(self, littleEndian).putInt(byteOffset, value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 32-bit unsigned int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value int value to set
+     * @param littleEndian (optional) flag indicating whether to write in little endian order
+     * @return undefined
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
+    public static Object setUint32(final Object self, final Object byteOffset, final Object value, final Object littleEndian) {
+        try {
+            getBuffer(self, littleEndian).putInt(JSType.toInt32(byteOffset), (int)JSType.toUint32(value));
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 32-bit unsigned int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value int value to set
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setUint32(final Object self, final int byteOffset, final long value) {
+        try {
+            getBuffer(self, false).putInt(byteOffset, (int)value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 32-bit unsigned int at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value int value to set
+     * @param littleEndian (optional) flag indicating whether to write in little endian order
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setUint32(final Object self, final int byteOffset, final long value, final boolean littleEndian) {
+        try {
+            getBuffer(self, littleEndian).putInt(byteOffset, (int)value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 32-bit float at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value float value to set
+     * @param littleEndian (optional) flag indicating whether to write in little endian order
+     * @return undefined
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
+    public static Object setFloat32(final Object self, final Object byteOffset, final Object value, final Object littleEndian) {
+        try {
+            getBuffer(self, littleEndian).putFloat((int)JSType.toUint32(byteOffset), (float)JSType.toNumber(value));
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 32-bit float at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value float value to set
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setFloat32(final Object self, final int byteOffset, final double value) {
+        try {
+            getBuffer(self, false).putFloat(byteOffset, (float)value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 32-bit float at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value float value to set
+     * @param littleEndian (optional) flag indicating whether to write in little endian order
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setFloat32(final Object self, final int byteOffset, final double value, final boolean littleEndian) {
+        try {
+            getBuffer(self, littleEndian).putFloat(byteOffset, (float)value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 64-bit float at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value double value to set
+     * @param littleEndian (optional) flag indicating whether to write in little endian order
+     * @return undefined
+     */
+    @Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
+    public static Object setFloat64(final Object self, final Object byteOffset, final Object value, final Object littleEndian) {
+        try {
+            getBuffer(self, littleEndian).putDouble((int)JSType.toUint32(byteOffset), JSType.toNumber(value));
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 64-bit float at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value double value to set
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setFloat64(final Object self, final int byteOffset, final double value) {
+        try {
+            getBuffer(self, false).putDouble(byteOffset, value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    /**
+     * Set 64-bit float at the given byteOffset
+     *
+     * @param self DataView object
+     * @param byteOffset byte offset to write at
+     * @param value double value to set
+     * @param littleEndian (optional) flag indicating whether to write in little endian order
+     * @return undefined
+     */
+    @SpecializedFunction
+    public static Object setFloat64(final Object self, final int byteOffset, final double value, final boolean littleEndian) {
+        try {
+            getBuffer(self, littleEndian).putDouble(byteOffset, value);
+            return UNDEFINED;
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.offset");
+        }
+    }
+
+    // internals only below this point
+    private static ByteBuffer bufferFrom(final NativeArrayBuffer nab, final int offset) {
+        try {
+            return nab.getBuffer(offset);
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.constructor.offset");
+        }
+    }
+
+    private static ByteBuffer bufferFrom(final NativeArrayBuffer nab, final int offset, final int length) {
+        try {
+            return nab.getBuffer(offset, length);
+        } catch (final IndexOutOfBoundsException ioe) {
+            throw rangeError(ioe, "dataview.constructor.offset");
+        }
+    }
+
+    private static NativeDataView checkSelf(final Object self) {
+        if (!(self instanceof NativeDataView)) {
+            throw typeError("not.an.arraybuffer", ScriptRuntime.safeToString(self));
+        }
+        return (NativeDataView)self;
+    }
+
+    private static ByteBuffer getBuffer(final Object self) {
+        return checkSelf(self).buf;
+    }
+
+    private static ByteBuffer getBuffer(final Object self, final Object littleEndian) {
+        return getBuffer(self, JSType.toBoolean(littleEndian));
+    }
+
+    private static ByteBuffer getBuffer(final Object self, final boolean littleEndian) {
+        return getBuffer(self).order(littleEndian? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
+    }
+}
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeDate.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeDate.java	Wed Jul 05 19:33:51 2017 +0200
@@ -114,10 +114,6 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     private NativeDate(final double time, final ScriptObject proto, final PropertyMap map) {
         super(proto, map);
         final ScriptEnvironment env = Global.getEnv();
@@ -127,7 +123,7 @@
     }
 
     NativeDate(final double time, final Global global) {
-        this(time, global.getDatePrototype(), getInitialMap());
+        this(time, global.getDatePrototype(), $nasgenmap$);
     }
 
     private NativeDate (final double time) {
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeError.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeError.java	Wed Jul 05 19:33:51 2017 +0200
@@ -92,10 +92,6 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     @SuppressWarnings("LeakingThisInConstructor")
     private NativeError(final Object msg, final ScriptObject proto, final PropertyMap map) {
         super(proto, map);
@@ -108,7 +104,7 @@
     }
 
     NativeError(final Object msg, final Global global) {
-        this(msg, global.getErrorPrototype(), getInitialMap());
+        this(msg, global.getErrorPrototype(), $nasgenmap$);
     }
 
     private NativeError(final Object msg) {
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeEvalError.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeEvalError.java	Wed Jul 05 19:33:51 2017 +0200
@@ -62,10 +62,6 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     @SuppressWarnings("LeakingThisInConstructor")
     private NativeEvalError(final Object msg, final ScriptObject proto, final PropertyMap map) {
         super(proto, map);
@@ -78,7 +74,7 @@
     }
 
     NativeEvalError(final Object msg, final Global global) {
-        this(msg, global.getEvalErrorPrototype(), getInitialMap());
+        this(msg, global.getEvalErrorPrototype(), $nasgenmap$);
     }
 
     private NativeEvalError(final Object msg) {
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeJSAdapter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJSAdapter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -146,10 +146,6 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     NativeJSAdapter(final Object overrides, final ScriptObject adaptee, final ScriptObject proto, final PropertyMap map) {
         super(proto, map);
         this.adaptee = wrapAdaptee(adaptee);
@@ -577,7 +573,7 @@
             proto = global.getJSAdapterPrototype();
         }
 
-        return new NativeJSAdapter(overrides, (ScriptObject)adaptee, (ScriptObject)proto, getInitialMap());
+        return new NativeJSAdapter(overrides, (ScriptObject)adaptee, (ScriptObject)proto, $nasgenmap$);
     }
 
     @Override
@@ -622,7 +618,7 @@
         case "getMethod":
             final FindProperty find = adaptee.findProperty(__call__, true);
             if (find != null) {
-                final Object value = getObjectValue(find);
+                final Object value = find.getObjectValue();
                 if (value instanceof ScriptFunction) {
                     final ScriptFunctionImpl func = (ScriptFunctionImpl)value;
                     // TODO: It's a shame we need to produce a function bound to this and name, when we'd only need it bound
@@ -691,7 +687,7 @@
         final MethodType type = desc.getMethodType();
         if (findData != null) {
             final String name = desc.getNameTokenCount() > 2 ? desc.getNameToken(2) : null;
-            final Object value = getObjectValue(findData);
+            final Object value = findData.getObjectValue();
             if (value instanceof ScriptFunction) {
                 final ScriptFunction func = (ScriptFunction)value;
 
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeJavaImporter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJavaImporter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -60,17 +60,13 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     private NativeJavaImporter(final Object[] args, final ScriptObject proto, final PropertyMap map) {
         super(proto, map);
         this.args = args;
     }
 
     private NativeJavaImporter(final Object[] args, final Global global) {
-        this(args, global.getJavaImporterPrototype(), getInitialMap());
+        this(args, global.getJavaImporterPrototype(), $nasgenmap$);
     }
 
     private NativeJavaImporter(final Object[] args) {
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java	Wed Jul 05 19:33:51 2017 +0200
@@ -34,6 +34,7 @@
 
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
 import java.text.NumberFormat;
 import java.util.Locale;
 import jdk.internal.dynalink.linker.GuardedInvocation;
@@ -57,7 +58,10 @@
 @ScriptClass("Number")
 public final class NativeNumber extends ScriptObject {
 
-    static final MethodHandle WRAPFILTER = findWrapFilter();
+    // Method handle to create an object wrapper for a primitive number
+    private static final MethodHandle WRAPFILTER = findOwnMH("wrapFilter", MH.type(NativeNumber.class, Object.class));
+    // Method handle to retrieve the Number prototype object
+    private static final MethodHandle PROTOFILTER = findOwnMH("protoFilter", MH.type(Object.class, Object.class));
 
     /** ECMA 15.7.3.2 largest positive finite value */
     @Property(attributes = Attribute.NON_ENUMERABLE_CONSTANT, where = Where.CONSTRUCTOR)
@@ -86,10 +90,6 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     private NativeNumber(final double value, final ScriptObject proto, final PropertyMap map) {
         super(proto, map);
         this.value = value;
@@ -98,7 +98,7 @@
     }
 
     NativeNumber(final double value, final Global global) {
-        this(value, global.getNumberPrototype(), getInitialMap());
+        this(value, global.getNumberPrototype(), $nasgenmap$);
     }
 
     private NativeNumber(final double value) {
@@ -322,7 +322,7 @@
      * @return Link to be invoked at call site.
      */
     public static GuardedInvocation lookupPrimitive(final LinkRequest request, final Object receiver) {
-        return PrimitiveLookup.lookupPrimitive(request, Number.class, new NativeNumber(((Number)receiver).doubleValue()), WRAPFILTER);
+        return PrimitiveLookup.lookupPrimitive(request, Number.class, new NativeNumber(((Number)receiver).doubleValue()), WRAPFILTER, PROTOFILTER);
     }
 
     @SuppressWarnings("unused")
@@ -330,6 +330,11 @@
         return new NativeNumber(((Number)receiver).doubleValue());
     }
 
+    @SuppressWarnings("unused")
+    private static Object protoFilter(final Object object) {
+        return Global.instance().getNumberPrototype();
+    }
+
     private static double getNumberValue(final Object self) {
         if (self instanceof Number) {
             return ((Number)self).doubleValue();
@@ -378,7 +383,7 @@
         return str;
     }
 
-    private static MethodHandle findWrapFilter() {
-        return MH.findStatic(MethodHandles.lookup(), NativeNumber.class, "wrapFilter", MH.type(NativeNumber.class, Object.class));
+    private static MethodHandle findOwnMH(final String name, final MethodType type) {
+        return MH.findStatic(MethodHandles.lookup(), NativeNumber.class, name, type);
     }
 }
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeRangeError.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeRangeError.java	Wed Jul 05 19:33:51 2017 +0200
@@ -62,10 +62,6 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     @SuppressWarnings("LeakingThisInConstructor")
     private NativeRangeError(final Object msg, final ScriptObject proto, final PropertyMap map) {
         super(proto, map);
@@ -78,7 +74,7 @@
     }
 
     NativeRangeError(final Object msg, final Global global) {
-        this(msg, global.getRangeErrorPrototype(), getInitialMap());
+        this(msg, global.getRangeErrorPrototype(), $nasgenmap$);
     }
 
     private NativeRangeError(final Object msg) {
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeReferenceError.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeReferenceError.java	Wed Jul 05 19:33:51 2017 +0200
@@ -62,10 +62,6 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     @SuppressWarnings("LeakingThisInConstructor")
     private NativeReferenceError(final Object msg, final ScriptObject proto, final PropertyMap map) {
         super(proto, map);
@@ -78,7 +74,7 @@
     }
 
     NativeReferenceError(final Object msg, final Global global) {
-        this(msg, global.getReferenceErrorPrototype(), getInitialMap());
+        this(msg, global.getReferenceErrorPrototype(), $nasgenmap$);
     }
 
     private NativeReferenceError(final Object msg) {
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java	Wed Jul 05 19:33:51 2017 +0200
@@ -70,12 +70,8 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     private NativeRegExp(final Global global) {
-        super(global.getRegExpPrototype(), getInitialMap());
+        super(global.getRegExpPrototype(), $nasgenmap$);
         this.globalObject = global;
     }
 
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExpExecResult.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExpExecResult.java	Wed Jul 05 19:33:51 2017 +0200
@@ -53,12 +53,8 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     NativeRegExpExecResult(final RegExpResult result, final Global global) {
-        super(global.getArrayPrototype(), getInitialMap());
+        super(global.getArrayPrototype(), $nasgenmap$);
         setIsArray();
         this.setArray(ArrayData.allocate(result.getGroups().clone()));
         this.index = result.getIndex();
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeString.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeString.java	Wed Jul 05 19:33:51 2017 +0200
@@ -32,6 +32,7 @@
 
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
 import java.text.Collator;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -69,21 +70,20 @@
 
     private final CharSequence value;
 
-    static final MethodHandle WRAPFILTER = findWrapFilter();
+    // Method handle to create an object wrapper for a primitive string
+    private static final MethodHandle WRAPFILTER = findOwnMH("wrapFilter", MH.type(NativeString.class, Object.class));
+    // Method handle to retrieve the String prototype object
+    private static final MethodHandle PROTOFILTER = findOwnMH("protoFilter", MH.type(Object.class, Object.class));
 
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     private NativeString(final CharSequence value) {
         this(value, Global.instance());
     }
 
     NativeString(final CharSequence value, final Global global) {
-        this(value, global.getStringPrototype(), getInitialMap());
+        this(value, global.getStringPrototype(), $nasgenmap$);
     }
 
     private NativeString(final CharSequence value, final ScriptObject proto, final PropertyMap map) {
@@ -1199,7 +1199,7 @@
      */
     public static GuardedInvocation lookupPrimitive(final LinkRequest request, final Object receiver) {
         final MethodHandle guard = NashornGuards.getInstanceOf2Guard(String.class, ConsString.class);
-        return PrimitiveLookup.lookupPrimitive(request, guard, new NativeString((CharSequence)receiver), WRAPFILTER);
+        return PrimitiveLookup.lookupPrimitive(request, guard, new NativeString((CharSequence)receiver), WRAPFILTER, PROTOFILTER);
     }
 
     @SuppressWarnings("unused")
@@ -1207,6 +1207,11 @@
         return new NativeString((CharSequence)receiver);
     }
 
+    @SuppressWarnings("unused")
+    private static Object protoFilter(final Object object) {
+        return Global.instance().getStringPrototype();
+    }
+
     private static CharSequence getCharSequence(final Object self) {
         if (self instanceof String || self instanceof ConsString) {
             return (CharSequence)self;
@@ -1254,7 +1259,7 @@
         return key >= 0 && key < value.length();
     }
 
-    private static MethodHandle findWrapFilter() {
-        return MH.findStatic(MethodHandles.lookup(), NativeString.class, "wrapFilter", MH.type(NativeString.class, Object.class));
+    private static MethodHandle findOwnMH(final String name, final MethodType type) {
+        return MH.findStatic(MethodHandles.lookup(), NativeString.class, name, type);
     }
 }
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeSyntaxError.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeSyntaxError.java	Wed Jul 05 19:33:51 2017 +0200
@@ -62,13 +62,9 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     @SuppressWarnings("LeakingThisInConstructor")
     NativeSyntaxError(final Object msg, final Global global) {
-        super(global.getSyntaxErrorPrototype(), getInitialMap());
+        super(global.getSyntaxErrorPrototype(), $nasgenmap$);
         if (msg != UNDEFINED) {
             this.instMessage = JSType.toString(msg);
         } else {
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeTypeError.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeTypeError.java	Wed Jul 05 19:33:51 2017 +0200
@@ -62,13 +62,9 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     @SuppressWarnings("LeakingThisInConstructor")
     NativeTypeError(final Object msg, final Global global) {
-        super(global.getTypeErrorPrototype(), getInitialMap());
+        super(global.getTypeErrorPrototype(), $nasgenmap$);
         if (msg != UNDEFINED) {
             this.instMessage = JSType.toString(msg);
         } else {
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeURIError.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeURIError.java	Wed Jul 05 19:33:51 2017 +0200
@@ -61,13 +61,9 @@
     // initialized by nasgen
     private static PropertyMap $nasgenmap$;
 
-    static PropertyMap getInitialMap() {
-        return $nasgenmap$;
-    }
-
     @SuppressWarnings("LeakingThisInConstructor")
     NativeURIError(final Object msg, final Global global) {
-        super(global.getURIErrorPrototype(), getInitialMap());
+        super(global.getURIErrorPrototype(), $nasgenmap$);
         if (msg != UNDEFINED) {
             this.instMessage = JSType.toString(msg);
         } else {
--- a/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java	Wed Jul 05 19:33:51 2017 +0200
@@ -57,10 +57,6 @@
         map$ = PropertyMap.newMap(properties);
     }
 
-    static PropertyMap getInitialMap() {
-        return map$;
-    }
-
     private PrototypeObject(final Global global, final PropertyMap map) {
         super(global.getObjectPrototype(), map != map$? map.addAll(map$) : map$);
     }
--- a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java	Wed Jul 05 19:33:51 2017 +0200
@@ -55,27 +55,11 @@
     // property map for non-strict, non-bound functions.
     private static final PropertyMap map$;
 
-    static PropertyMap getInitialMap() {
-        return map$;
-    }
-
-    static PropertyMap getInitialAnonymousMap() {
-        return AnonymousFunction.getInitialMap();
-    }
-
-    static PropertyMap getInitialStrictMap() {
-        return strictmodemap$;
-    }
-
-    static PropertyMap getInitialBoundMap() {
-        return boundfunctionmap$;
-    }
-
     // Marker object for lazily initialized prototype object
     private static final Object LAZY_PROTOTYPE = new Object();
 
     private ScriptFunctionImpl(final String name, final MethodHandle invokeHandle, final MethodHandle[] specs, final Global global) {
-        super(name, invokeHandle, getInitialMap(), null, specs, false, true, true);
+        super(name, invokeHandle, map$, null, specs, ScriptFunctionData.IS_BUILTIN_CONSTRUCTOR);
         init(global);
     }
 
@@ -92,7 +76,7 @@
     }
 
     private ScriptFunctionImpl(final String name, final MethodHandle invokeHandle, final PropertyMap map, final MethodHandle[] specs, final Global global) {
-        super(name, invokeHandle, map.addAll(getInitialMap()), null, specs, false, true, true);
+        super(name, invokeHandle, map.addAll(map$), null, specs, ScriptFunctionData.IS_BUILTIN_CONSTRUCTOR);
         init(global);
     }
 
@@ -109,8 +93,8 @@
         this(name, invokeHandle, map, specs, Global.instance());
     }
 
-    private ScriptFunctionImpl(final String name, final MethodHandle methodHandle, final ScriptObject scope, final MethodHandle[] specs, final boolean isStrict, final boolean isBuiltin, final boolean isConstructor, final Global global) {
-        super(name, methodHandle, getMap(global, isStrict), scope, specs, isStrict, isBuiltin, isConstructor);
+    private ScriptFunctionImpl(final String name, final MethodHandle methodHandle, final ScriptObject scope, final MethodHandle[] specs, final int flags, final Global global) {
+        super(name, methodHandle, getMap(isStrict(flags)), scope, specs, flags);
         init(global);
     }
 
@@ -121,16 +105,14 @@
      * @param methodHandle handle for invocation
      * @param scope scope object
      * @param specs specialized versions of this method, if available, null otherwise
-     * @param isStrict are we in strict mode
-     * @param isBuiltin is this a built-in function
-     * @param isConstructor can the function be used as a constructor (most can; some built-ins are restricted).
+     * @param flags {@link ScriptFunctionData} flags
      */
-    ScriptFunctionImpl(final String name, final MethodHandle methodHandle, final ScriptObject scope, final MethodHandle[] specs, final boolean isStrict, final boolean isBuiltin, final boolean isConstructor) {
-        this(name, methodHandle, scope, specs, isStrict, isBuiltin, isConstructor, Global.instance());
+    ScriptFunctionImpl(final String name, final MethodHandle methodHandle, final ScriptObject scope, final MethodHandle[] specs, final int flags) {
+        this(name, methodHandle, scope, specs, flags, Global.instance());
     }
 
     private ScriptFunctionImpl(final RecompilableScriptFunctionData data, final ScriptObject scope, final Global global) {
-        super(data, getMap(global, data.isStrict()), scope);
+        super(data, getMap(data.isStrict()), scope);
         init(global);
     }
 
@@ -150,7 +132,7 @@
      * @param global the global object
      */
     ScriptFunctionImpl(final ScriptFunctionData data, final Global global) {
-        super(data, getInitialBoundMap(), null);
+        super(data, boundfunctionmap$, null);
         init(global);
     }
 
@@ -173,9 +155,13 @@
         return newMap;
     }
 
+    private static boolean isStrict(final int flags) {
+        return (flags & ScriptFunctionData.IS_STRICT) != 0;
+    }
+
     // Choose the map based on strict mode!
-    private static PropertyMap getMap(final Global global, final boolean strict) {
-        return strict ? getInitialStrictMap() : getInitialMap();
+    private static PropertyMap getMap(final boolean strict) {
+        return strict ? strictmodemap$ : map$;
     }
 
     private static PropertyMap createBoundFunctionMap(final PropertyMap strictModeMap) {
@@ -189,12 +175,8 @@
     private static class AnonymousFunction extends ScriptFunctionImpl {
         private static final PropertyMap anonmap$ = PropertyMap.newMap();
 
-        static PropertyMap getInitialMap() {
-            return anonmap$;
-        }
-
         AnonymousFunction(final Global global) {
-            super("", GlobalFunctions.ANONYMOUS, getInitialAnonymousMap(), null);
+            super("", GlobalFunctions.ANONYMOUS, anonmap$, null);
         }
     }
 
@@ -211,7 +193,7 @@
      * @return new ScriptFunction
      */
     static ScriptFunction makeFunction(final String name, final MethodHandle methodHandle, final MethodHandle[] specs) {
-        final ScriptFunctionImpl func = new ScriptFunctionImpl(name, methodHandle, null, specs, false, true, false);
+        final ScriptFunctionImpl func = new ScriptFunctionImpl(name, methodHandle, null, specs, ScriptFunctionData.IS_BUILTIN);
         func.setPrototype(UNDEFINED);
         // Non-constructor built-in functions do not have "prototype" property
         func.deleteOwnProperty(func.getMap().findProperty("prototype"));
--- a/nashorn/src/jdk/nashorn/internal/parser/Parser.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/parser/Parser.java	Wed Jul 05 19:33:51 2017 +0200
@@ -1799,6 +1799,7 @@
         case THIS:
             final String name = type.getName();
             next();
+            lc.setFlag(lc.getCurrentFunction(), FunctionNode.USES_THIS);
             return new IdentNode(primaryToken, finish, name);
         case IDENT:
             final IdentNode ident = getIdent();
--- a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java	Wed Jul 05 19:33:51 2017 +0200
@@ -141,10 +141,12 @@
     private Class<?> currentType;
 
     /**
-     * Delegate constructor. This is used when adding properties to the Global scope, which
-     * is necessary for outermost levels in a script (the ScriptObject is represented by
-     * a JO-prefixed ScriptObject class, but the properties need to be in the Global scope
-     * and are thus rebound with that as receiver
+     * Delegate constructor for bound properties. This is used for properties created by
+     * {@link ScriptRuntime#mergeScope} and the Nashorn {@code Object.bindProperties} method.
+     * The former is used to add a script's defined globals to the current global scope while
+     * still storing them in a JO-prefixed ScriptObject class.
+     *
+     * <p>All properties created by this constructor have the {@link #IS_BOUND} flag set.</p>
      *
      * @param property  accessor property to rebind
      * @param delegate  delegate object to rebind receiver to
@@ -157,6 +159,8 @@
         this.objectGetter    = bindTo(property.ensureObjectGetter(), delegate);
         this.objectSetter    = bindTo(property.ensureObjectSetter(), delegate);
 
+        // Properties created this way are bound to a delegate
+        this.flags |= IS_BOUND;
         setCurrentType(property.getCurrentType());
     }
 
--- a/nashorn/src/jdk/nashorn/internal/runtime/Context.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/Context.java	Wed Jul 05 19:33:51 2017 +0200
@@ -36,6 +36,8 @@
 import java.io.PrintWriter;
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.SoftReference;
 import java.lang.reflect.Modifier;
 import java.net.MalformedURLException;
 import java.net.URL;
@@ -46,6 +48,7 @@
 import java.security.Permissions;
 import java.security.PrivilegedAction;
 import java.security.ProtectionDomain;
+import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.concurrent.atomic.AtomicLong;
 import jdk.internal.org.objectweb.asm.ClassReader;
@@ -153,16 +156,19 @@
     /** Is Context global debug mode enabled ? */
     public static final boolean DEBUG = Options.getBooleanProperty("nashorn.debug");
 
-    private static final ThreadLocal<ScriptObject> currentGlobal = new ThreadLocal<>();
+    private static final ThreadLocal<Global> currentGlobal = new ThreadLocal<>();
+
+    // class cache
+    private ClassCache classCache;
 
     /**
      * Get the current global scope
      * @return the current global scope
      */
-    public static ScriptObject getGlobal() {
+    public static Global getGlobal() {
         // This class in a package.access protected package.
         // Trusted code only can call this method.
-        return getGlobalTrusted();
+        return currentGlobal.get();
     }
 
     /**
@@ -171,10 +177,19 @@
      */
     public static void setGlobal(final ScriptObject global) {
         if (global != null && !(global instanceof Global)) {
-            throw new IllegalArgumentException("global is not an instance of Global!");
+            throw new IllegalArgumentException("not a global!");
         }
+        setGlobal((Global)global);
+    }
 
-        setGlobalTrusted(global);
+    /**
+     * Set the current global scope
+     * @param global the global scope
+     */
+    public static void setGlobal(final Global global) {
+        // This class in a package.access protected package.
+        // Trusted code only can call this method.
+        currentGlobal.set(global);
     }
 
     /**
@@ -195,7 +210,7 @@
      * @return error writer of the current context
      */
     public static PrintWriter getCurrentErr() {
-        final ScriptObject global = getGlobalTrusted();
+        final ScriptObject global = getGlobal();
         return (global != null)? global.getContext().getErr() : new PrintWriter(System.err);
     }
 
@@ -348,6 +363,11 @@
             this.classPathLoader = null;
         }
 
+        final int cacheSize = env._class_cache_size;
+        if (cacheSize > 0) {
+            classCache = new ClassCache(cacheSize);
+        }
+
         // print version info if asked.
         if (env._version) {
             getErr().println("nashorn " + Version.version());
@@ -395,7 +415,7 @@
      * @return the property map of the current global scope
      */
     public static PropertyMap getGlobalMap() {
-        return Context.getGlobalTrusted().getMap();
+        return Context.getGlobal().getMap();
     }
 
     /**
@@ -425,7 +445,7 @@
         final String  file       = (location == UNDEFINED || location == null) ? "<eval>" : location.toString();
         final Source  source     = new Source(file, string);
         final boolean directEval = location != UNDEFINED; // is this direct 'eval' call or indirectly invoked eval?
-        final ScriptObject global = Context.getGlobalTrusted();
+        final Global  global = Context.getGlobal();
 
         ScriptObject scope = initialScope;
 
@@ -457,7 +477,7 @@
         // in the caller's environment. A new environment is created!
         if (strictFlag) {
             // Create a new scope object
-            final ScriptObject strictEvalScope = ((GlobalObject)global).newObject();
+            final ScriptObject strictEvalScope = global.newObject();
 
             // bless it as a "scope"
             strictEvalScope.setIsScope();
@@ -582,10 +602,10 @@
      * @throws IOException if source cannot be found or loaded
      */
     public Object loadWithNewGlobal(final Object from, final Object...args) throws IOException {
-        final ScriptObject oldGlobal = getGlobalTrusted();
-        final ScriptObject newGlobal = AccessController.doPrivileged(new PrivilegedAction<ScriptObject>() {
+        final Global oldGlobal = getGlobal();
+        final Global newGlobal = AccessController.doPrivileged(new PrivilegedAction<Global>() {
            @Override
-           public ScriptObject run() {
+           public Global run() {
                try {
                    return newGlobal();
                } catch (final RuntimeException e) {
@@ -598,17 +618,17 @@
         }, CREATE_GLOBAL_ACC_CTXT);
         // initialize newly created Global instance
         initGlobal(newGlobal);
-        setGlobalTrusted(newGlobal);
+        setGlobal(newGlobal);
 
         final Object[] wrapped = args == null? ScriptRuntime.EMPTY_ARRAY :  ScriptObjectMirror.wrapArray(args, oldGlobal);
-        newGlobal.put("arguments", ((GlobalObject)newGlobal).wrapAsObject(wrapped), env._strict);
+        newGlobal.put("arguments", newGlobal.wrapAsObject(wrapped), env._strict);
 
         try {
             // wrap objects from newGlobal's world as mirrors - but if result
             // is from oldGlobal's world, unwrap it!
             return ScriptObjectMirror.unwrap(ScriptObjectMirror.wrap(load(newGlobal, from), newGlobal), oldGlobal);
         } finally {
-            setGlobalTrusted(oldGlobal);
+            setGlobal(oldGlobal);
         }
     }
 
@@ -637,7 +657,7 @@
      * Checks that the given Class can be accessed from no permissions context.
      *
      * @param clazz Class object
-     * @throw SecurityException if not accessible
+     * @throws SecurityException if not accessible
      */
     public static void checkPackageAccess(final Class<?> clazz) {
         final SecurityManager sm = System.getSecurityManager();
@@ -654,12 +674,12 @@
      * Checks that the given package name can be accessed from no permissions context.
      *
      * @param pkgName package name
-     * @throw SecurityException if not accessible
+     * @throws SecurityException if not accessible
      */
     public static void checkPackageAccess(final String pkgName) {
         final SecurityManager sm = System.getSecurityManager();
         if (sm != null) {
-            checkPackageAccess(sm, pkgName.endsWith(".")? pkgName : pkgName + ".");
+            checkPackageAccess(sm, pkgName.endsWith(".") ? pkgName : pkgName + ".");
         }
     }
 
@@ -783,7 +803,7 @@
      *
      * @return the initialized global scope object.
      */
-    public ScriptObject createGlobal() {
+    public Global createGlobal() {
         return initGlobal(newGlobal());
     }
 
@@ -791,7 +811,7 @@
      * Create a new uninitialized global scope object
      * @return the global script object
      */
-    public ScriptObject newGlobal() {
+    public Global newGlobal() {
         return new Global(this);
     }
 
@@ -801,20 +821,16 @@
      * @param global the global
      * @return the initialized global scope object.
      */
-    public ScriptObject initGlobal(final ScriptObject global) {
-        if (! (global instanceof GlobalObject)) {
-            throw new IllegalArgumentException("not a global object!");
-        }
-
+    public Global initGlobal(final Global global) {
         // Need only minimal global object, if we are just compiling.
         if (!env._compile_only) {
-            final ScriptObject oldGlobal = Context.getGlobalTrusted();
+            final Global oldGlobal = Context.getGlobal();
             try {
-                Context.setGlobalTrusted(global);
+                Context.setGlobal(global);
                 // initialize global scope with builtin global objects
-                ((GlobalObject)global).initBuiltinObjects();
+                global.initBuiltinObjects();
             } finally {
-                Context.setGlobalTrusted(oldGlobal);
+                Context.setGlobal(oldGlobal);
             }
         }
 
@@ -822,30 +838,15 @@
     }
 
     /**
-     * Trusted variants - package-private
-     */
-
-    /**
-     * Return the current global scope
-     * @return current global scope
+     * Trusted variant - package-private
      */
-    static ScriptObject getGlobalTrusted() {
-        return currentGlobal.get();
-    }
-
-    /**
-     * Set the current global scope
-     */
-    static void setGlobalTrusted(ScriptObject global) {
-         currentGlobal.set(global);
-    }
 
     /**
      * Return the current global's context
      * @return current global's context
      */
     static Context getContextTrusted() {
-        return Context.getGlobalTrusted().getContext();
+        return ((ScriptObject)Context.getGlobal()).getContext();
     }
 
     /**
@@ -914,7 +915,7 @@
         }
 
         // Package as a JavaScript function and pass function back to shell.
-        return ((GlobalObject)Context.getGlobalTrusted()).newScriptFunction(RUN_SCRIPT.symbolName(), runMethodHandle, scope, strict);
+        return Context.getGlobal().newScriptFunction(RUN_SCRIPT.symbolName(), runMethodHandle, scope, strict);
     }
 
     private ScriptFunction compileScript(final Source source, final ScriptObject scope, final ErrorManager errMan) {
@@ -925,16 +926,10 @@
         // start with no errors, no warnings.
         errMan.reset();
 
-        GlobalObject global = null;
-        Class<?> script;
-
-        if (env._class_cache_size > 0) {
-            global = (GlobalObject)Context.getGlobalTrusted();
-            script = global.findCachedClass(source);
-            if (script != null) {
-                Compiler.LOG.fine("Code cache hit for ", source, " avoiding recompile.");
-                return script;
-            }
+        Class<?> script = findCachedClass(source);
+        if (script != null) {
+            Compiler.LOG.fine("Code cache hit for ", source, " avoiding recompile.");
+            return script;
         }
 
         final FunctionNode functionNode = new Parser(env, source, errMan, strict).parse();
@@ -963,10 +958,7 @@
 
         final FunctionNode newFunctionNode = compiler.compile(functionNode);
         script = compiler.install(newFunctionNode);
-
-        if (global != null) {
-            global.cacheClass(source, script);
-        }
+        cacheClass(source, script);
 
         return script;
     }
@@ -988,4 +980,60 @@
     private long getUniqueScriptId() {
         return uniqueScriptId.getAndIncrement();
     }
+
+    /**
+     * Cache for compiled script classes.
+     */
+    @SuppressWarnings("serial")
+    private static class ClassCache extends LinkedHashMap<Source, ClassReference> {
+        private final int size;
+        private final ReferenceQueue<Class<?>> queue;
+
+        ClassCache(int size) {
+            super(size, 0.75f, true);
+            this.size = size;
+            this.queue = new ReferenceQueue<>();
+        }
+
+        void cache(final Source source, final Class<?> clazz) {
+            put(source, new ClassReference(clazz, queue, source));
+        }
+
+        @Override
+        protected boolean removeEldestEntry(final Map.Entry<Source, ClassReference> eldest) {
+            return size() > size;
+        }
+
+        @Override
+        public ClassReference get(Object key) {
+            for (ClassReference ref; (ref = (ClassReference)queue.poll()) != null; ) {
+                remove(ref.source);
+            }
+            return super.get(key);
+        }
+
+    }
+
+    private static class ClassReference extends SoftReference<Class<?>> {
+        private final Source source;
+
+        ClassReference(final Class<?> clazz, final ReferenceQueue<Class<?>> queue, final Source source) {
+            super(clazz, queue);
+            this.source = source;
+        }
+    }
+
+    // Class cache management
+    private Class<?> findCachedClass(final Source source) {
+        ClassReference ref = classCache == null ? null : classCache.get(source);
+        return ref != null ? ref.get() : null;
+    }
+
+    private void cacheClass(final Source source, final Class<?> clazz) {
+        if (classCache != null) {
+            classCache.cache(source, clazz);
+        }
+    }
+
+
 }
--- a/nashorn/src/jdk/nashorn/internal/runtime/DebuggerSupport.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/DebuggerSupport.java	Wed Jul 05 19:33:51 2017 +0200
@@ -75,7 +75,7 @@
      * @return context global.
      */
     static Object getGlobal() {
-        return Context.getGlobalTrusted();
+        return Context.getGlobal();
     }
 
     /**
@@ -87,7 +87,7 @@
      * @return Result of eval as string, or, an exception or null depending on returnException.
      */
     static Object eval(final ScriptObject scope, final Object self, final String string, final boolean returnException) {
-        final ScriptObject global = Context.getGlobalTrusted();
+        final ScriptObject global = Context.getGlobal();
         final ScriptObject initialScope = scope != null ? scope : global;
         final Object callThis = self != null ? self : global;
         final Context context = global.getContext();
--- a/nashorn/src/jdk/nashorn/internal/runtime/ECMAErrors.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ECMAErrors.java	Wed Jul 05 19:33:51 2017 +0200
@@ -31,6 +31,7 @@
 import jdk.nashorn.api.scripting.NashornException;
 import jdk.nashorn.internal.scripts.JS;
 import jdk.nashorn.internal.codegen.CompilerConstants;
+import jdk.nashorn.internal.objects.Global;
 
 /**
  * Helper class to throw various standard "ECMA error" exceptions such as Error, ReferenceError, TypeError etc.
@@ -66,7 +67,7 @@
      * @return the resulting {@link ECMAException}
      */
     public static ECMAException asEcmaException(final ParserException e) {
-        return asEcmaException(Context.getGlobalTrusted(), e);
+        return asEcmaException(Context.getGlobal(), e);
     }
 
     /**
@@ -78,11 +79,11 @@
      *
      * @return the resulting {@link ECMAException}
      */
-    public static ECMAException asEcmaException(final ScriptObject global, final ParserException e) {
+    public static ECMAException asEcmaException(final Global global, final ParserException e) {
         final JSErrorType errorType = e.getErrorType();
         assert errorType != null : "error type for " + e + " was null";
 
-        final GlobalObject globalObj = (GlobalObject)global;
+        final Global globalObj    = global;
         final String       msg    = e.getMessage();
 
         // translate to ECMAScript Error object using error type
@@ -116,7 +117,7 @@
      * @return the resulting {@link ECMAException}
      */
     public static ECMAException syntaxError(final String msgId, final String... args) {
-        return syntaxError(Context.getGlobalTrusted(), msgId, args);
+        return syntaxError(Context.getGlobal(), msgId, args);
     }
 
     /**
@@ -128,7 +129,7 @@
      *
      * @return the resulting {@link ECMAException}
      */
-    public static ECMAException syntaxError(final ScriptObject global, final String msgId, final String... args) {
+    public static ECMAException syntaxError(final Global global, final String msgId, final String... args) {
         return syntaxError(global, null, msgId, args);
     }
 
@@ -142,7 +143,7 @@
      * @return the resulting {@link ECMAException}
      */
     public static ECMAException syntaxError(final Throwable cause, final String msgId, final String... args) {
-        return syntaxError(Context.getGlobalTrusted(), cause, msgId, args);
+        return syntaxError(Context.getGlobal(), cause, msgId, args);
     }
 
     /**
@@ -155,9 +156,9 @@
      *
      * @return the resulting {@link ECMAException}
      */
-    public static ECMAException syntaxError(final ScriptObject global, final Throwable cause, final String msgId, final String... args) {
+    public static ECMAException syntaxError(final Global global, final Throwable cause, final String msgId, final String... args) {
         final String msg = getMessage("syntax.error." + msgId, args);
-        return error(((GlobalObject)global).newSyntaxError(msg), cause);
+        return error(global.newSyntaxError(msg), cause);
     }
 
     /**
@@ -169,7 +170,7 @@
      * @return the resulting {@link ECMAException}
      */
     public static ECMAException typeError(final String msgId, final String... args) {
-        return typeError(Context.getGlobalTrusted(), msgId, args);
+        return typeError(Context.getGlobal(), msgId, args);
     }
 
     /**
@@ -181,7 +182,7 @@
      *
      * @return the resulting {@link ECMAException}
      */
-    public static ECMAException typeError(final ScriptObject global, final String msgId, final String... args) {
+    public static ECMAException typeError(final Global global, final String msgId, final String... args) {
         return typeError(global, null, msgId, args);
     }
 
@@ -195,7 +196,7 @@
      * @return the resulting {@link ECMAException}
      */
     public static ECMAException typeError(final Throwable cause, final String msgId, final String... args) {
-        return typeError(Context.getGlobalTrusted(), cause, msgId, args);
+        return typeError(Context.getGlobal(), cause, msgId, args);
     }
 
     /**
@@ -208,9 +209,9 @@
      *
      * @return the resulting {@link ECMAException}
      */
-    public static ECMAException typeError(final ScriptObject global, final Throwable cause, final String msgId, final String... args) {
+    public static ECMAException typeError(final Global global, final Throwable cause, final String msgId, final String... args) {
         final String msg = getMessage("type.error." + msgId, args);
-        return error(((GlobalObject)global).newTypeError(msg), cause);
+        return error(global.newTypeError(msg), cause);
     }
 
     /**
@@ -222,7 +223,7 @@
      * @return the resulting {@link ECMAException}
      */
     public static ECMAException rangeError(final String msgId, final String... args) {
-        return rangeError(Context.getGlobalTrusted(), msgId, args);
+        return rangeError(Context.getGlobal(), msgId, args);
     }
 
     /**
@@ -234,7 +235,7 @@
      *
      * @return the resulting {@link ECMAException}
      */
-    public static ECMAException rangeError(final ScriptObject global, final String msgId, final String... args) {
+    public static ECMAException rangeError(final Global global, final String msgId, final String... args) {
         return rangeError(global, null, msgId, args);
     }
 
@@ -248,7 +249,7 @@
      * @return the resulting {@link ECMAException}
      */
     public static ECMAException rangeError(final Throwable cause, final String msgId, final String... args) {
-        return rangeError(Context.getGlobalTrusted(), cause, msgId, args);
+        return rangeError(Context.getGlobal(), cause, msgId, args);
     }
 
     /**
@@ -261,9 +262,9 @@
      *
      * @return the resulting {@link ECMAException}
      */
-    public static ECMAException rangeError(final ScriptObject global, final Throwable cause, final String msgId, final String... args) {
+    public static ECMAException rangeError(final Global global, final Throwable cause, final String msgId, final String... args) {
         final String msg = getMessage("range.error." + msgId, args);
-        return error(((GlobalObject)global).newRangeError(msg), cause);
+        return error(global.newRangeError(msg), cause);
     }
 
     /**
@@ -275,7 +276,7 @@
      * @return the resulting {@link ECMAException}
      */
     public static ECMAException referenceError(final String msgId, final String... args) {
-        return referenceError(Context.getGlobalTrusted(), msgId, args);
+        return referenceError(Context.getGlobal(), msgId, args);
     }
 
     /**
@@ -287,7 +288,7 @@
      *
      * @return the resulting {@link ECMAException}
      */
-    public static ECMAException referenceError(final ScriptObject global, final String msgId, final String... args) {
+    public static ECMAException referenceError(final Global global, final String msgId, final String... args) {
         return referenceError(global, null, msgId, args);
     }
 
@@ -301,7 +302,7 @@
      * @return the resulting {@link ECMAException}
      */
     public static ECMAException referenceError(final Throwable cause, final String msgId, final String... args) {
-        return referenceError(Context.getGlobalTrusted(), cause, msgId, args);
+        return referenceError(Context.getGlobal(), cause, msgId, args);
     }
 
     /**
@@ -314,9 +315,9 @@
      *
      * @return the resulting {@link ECMAException}
      */
-    public static ECMAException referenceError(final ScriptObject global, final Throwable cause, final String msgId, final String... args) {
+    public static ECMAException referenceError(final Global global, final Throwable cause, final String msgId, final String... args) {
         final String msg = getMessage("reference.error." + msgId, args);
-        return error(((GlobalObject)global).newReferenceError(msg), cause);
+        return error(global.newReferenceError(msg), cause);
     }
 
     /**
@@ -328,7 +329,7 @@
      * @return the resulting {@link ECMAException}
      */
     public static ECMAException uriError(final String msgId, final String... args) {
-        return uriError(Context.getGlobalTrusted(), msgId, args);
+        return uriError(Context.getGlobal(), msgId, args);
     }
 
     /**
@@ -340,7 +341,7 @@
      *
      * @return the resulting {@link ECMAException}
      */
-    public static ECMAException uriError(final ScriptObject global, final String msgId, final String... args) {
+    public static ECMAException uriError(final Global global, final String msgId, final String... args) {
         return uriError(global, null, msgId, args);
     }
 
@@ -354,7 +355,7 @@
      * @return the resulting {@link ECMAException}
      */
     public static ECMAException uriError(final Throwable cause, final String msgId, final String... args) {
-        return uriError(Context.getGlobalTrusted(), cause, msgId, args);
+        return uriError(Context.getGlobal(), cause, msgId, args);
     }
 
     /**
@@ -367,9 +368,9 @@
      *
      * @return the resulting {@link ECMAException}
      */
-    public static ECMAException uriError(final ScriptObject global, final Throwable cause, final String msgId, final String... args) {
+    public static ECMAException uriError(final Global global, final Throwable cause, final String msgId, final String... args) {
         final String msg = getMessage("uri.error." + msgId, args);
-        return error(((GlobalObject)global).newURIError(msg), cause);
+        return error(global.newURIError(msg), cause);
     }
 
     /**
--- a/nashorn/src/jdk/nashorn/internal/runtime/FinalScriptFunctionData.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/FinalScriptFunctionData.java	Wed Jul 05 19:33:51 2017 +0200
@@ -38,31 +38,27 @@
     /**
      * Constructor - used for bind
      *
-     * @param name          name
-     * @param arity         arity
-     * @param functions     precompiled code
-     * @param isStrict      strict
-     * @param isBuiltin     builtin
-     * @param isConstructor constructor
+     * @param name      name
+     * @param arity     arity
+     * @param functions precompiled code
+     * @param flags     {@link ScriptFunctionData} flags
      */
-    FinalScriptFunctionData(final String name, int arity, CompiledFunctions functions, final boolean isStrict, final boolean isBuiltin, final boolean isConstructor) {
-        super(name, arity, isStrict, isBuiltin, isConstructor);
+    FinalScriptFunctionData(final String name, final int arity, final CompiledFunctions functions, final int flags) {
+        super(name, arity, flags);
         code.addAll(functions);
     }
 
     /**
-     * Constructor - used from ScriptFunction. This assumes that we have code alraedy for the
+     * Constructor - used from ScriptFunction. This assumes that we have code already for the
      * method (typically a native method) and possibly specializations.
      *
-     * @param name           name
-     * @param mh             method handle for generic version of method
-     * @param specs          specializations
-     * @param isStrict       strict
-     * @param isBuiltin      builtin
-     * @param isConstructor  constructor
+     * @param name  name
+     * @param mh    method handle for generic version of method
+     * @param specs specializations
+     * @param flags {@link ScriptFunctionData} flags
      */
-    FinalScriptFunctionData(final String name, final MethodHandle mh, final MethodHandle[] specs, final boolean isStrict, final boolean isBuiltin, final boolean isConstructor) {
-        super(name, arity(mh), isStrict, isBuiltin, isConstructor);
+    FinalScriptFunctionData(final String name, final MethodHandle mh, final MethodHandle[] specs, final int flags) {
+        super(name, arity(mh), flags);
 
         addInvoker(mh);
         if (specs != null) {
--- a/nashorn/src/jdk/nashorn/internal/runtime/GlobalObject.java	Tue Mar 25 12:31:49 2014 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,244 +0,0 @@
-/*
- * 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * 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 jdk.nashorn.internal.runtime;
-
-import java.lang.invoke.MethodHandle;
-import java.util.concurrent.Callable;
-import jdk.internal.dynalink.linker.GuardedInvocation;
-import jdk.internal.dynalink.linker.LinkRequest;
-import jdk.nashorn.internal.runtime.linker.InvokeByName;
-
-/**
- * Runtime interface to the global scope objects.
- */
-
-public interface GlobalObject {
-    /**
-     * Is this global of the given Context?
-     * @param ctxt the context
-     * @return true if this global belongs to the given Context
-     */
-    public boolean isOfContext(final Context ctxt);
-
-    /**
-     * Does this global belong to a strict Context?
-     * @return true if this global belongs to a strict Context
-     */
-    public boolean isStrictContext();
-
-    /**
-     * Initialize standard builtin objects like "Object", "Array", "Function" etc.
-     * as well as our extension builtin objects like "Java", "JSAdapter" as properties
-     * of the global scope object.
-     */
-    public void initBuiltinObjects();
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#newScriptFunction(String, MethodHandle, ScriptObject, boolean)}
-     *
-     * @param name   function name
-     * @param handle invocation handle for function
-     * @param scope  the scope
-     * @param strict are we in strict mode
-     *
-     * @return new script function
-     */
-   public ScriptFunction newScriptFunction(String name, MethodHandle handle, ScriptObject scope, boolean strict);
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#wrapAsObject(Object)}
-     *
-     * @param obj object to wrap
-     * @return    wrapped object
-     */
-   public Object wrapAsObject(Object obj);
-
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#primitiveLookup(LinkRequest, Object)}
-     *
-     * @param request the link request for the dynamic call site.
-     * @param self     self reference
-     *
-     * @return guarded invocation
-     */
-   public GuardedInvocation primitiveLookup(LinkRequest request, Object self);
-
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#newObject()}
-     *
-     * @return the new ScriptObject
-     */
-   public ScriptObject newObject();
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#isError(ScriptObject)}
-     *
-     * @param sobj to check if it is an error object
-     * @return true if error object
-     */
-   public boolean isError(ScriptObject sobj);
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#newError(String)}
-     *
-     * @param msg the error message
-     *
-     * @return the new ScriptObject representing the error
-     */
-   public ScriptObject newError(String msg);
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#newEvalError(String)}
-     *
-     * @param msg the error message
-     *
-     * @return the new ScriptObject representing the eval error
-     */
-   public ScriptObject newEvalError(String msg);
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#newRangeError(String)}
-     *
-     * @param msg the error message
-     *
-     * @return the new ScriptObject representing the range error
-     */
-   public ScriptObject newRangeError(String msg);
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#newReferenceError(String)}
-     *
-     * @param msg the error message
-     *
-     * @return the new ScriptObject representing the reference error
-     */
-   public ScriptObject newReferenceError(String msg);
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#newSyntaxError(String)}
-     *
-     * @param msg the error message
-     *
-     * @return the new ScriptObject representing the syntax error
-     */
-   public ScriptObject newSyntaxError(String msg);
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#newTypeError(String)}
-     *
-     * @param msg the error message
-     *
-     * @return the new ScriptObject representing the type error
-     */
-   public ScriptObject newTypeError(String msg);
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#newURIError(String)}
-     *
-     * @param msg the error message
-     *
-     * @return the new ScriptObject representing the URI error
-     */
-    public ScriptObject newURIError(String msg);
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#newGenericDescriptor(boolean, boolean)}
-     *
-     * @param configurable is the described property configurable
-     * @param enumerable   is the described property enumerable
-     *
-     * @return property descriptor
-     */
-    public PropertyDescriptor newGenericDescriptor(boolean configurable, boolean enumerable);
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#newDataDescriptor(Object, boolean, boolean, boolean)}
-     *
-     * @param value        data value
-     * @param configurable is the described property configurable
-     * @param enumerable   is the described property enumerable
-     * @param writable     is the described property writable
-     *
-     * @return property descriptor
-     */
-    public PropertyDescriptor newDataDescriptor(Object value, boolean configurable, boolean enumerable, boolean writable);
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#newAccessorDescriptor(Object, Object, boolean, boolean)}
-     *
-     * @param get          property getter, or null if none
-     * @param set          property setter, or null if none
-     * @param configurable is the described property configurable
-     * @param enumerable   is the described property enumerable
-     *
-     * @return property descriptor
-     */
-    public PropertyDescriptor newAccessorDescriptor(Object get, Object set, boolean configurable, boolean enumerable);
-
-    /**
-     * Wrapper for {@link jdk.nashorn.internal.objects.Global#getDefaultValue(ScriptObject, Class)}
-     *
-     * @param sobj     script object
-     * @param typeHint type hint
-     *
-     * @return default value
-     */
-    public Object getDefaultValue(ScriptObject sobj, Class<?> typeHint);
-
-    /**
-     * Find the compiled Class for the given script source, if available
-     *
-     * @param source Source object of the script
-     * @return compiled Class object or null
-     */
-    public Class<?> findCachedClass(Source source);
-
-    /**
-     * Put the Source associated Class object in the Source-to-Class cache
-     *
-     * @param source Source of the script
-     * @param clazz compiled Class object for the source
-     */
-    public void cacheClass(Source source, Class<?> clazz);
-
-    /**
-     * Get cached InvokeByName object for the given key
-     * @param key key to be associated with InvokeByName object
-     * @param creator if InvokeByName is absent 'creator' is called to make one (lazy init)
-     * @return InvokeByName object associated with the key.
-     */
-    public InvokeByName getInvokeByName(final Object key, final Callable<InvokeByName> creator);
-
-    /**
-     * Get cached dynamic method handle for the given key
-     * @param key key to be associated with dynamic method handle
-     * @param creator if method handle is absent 'creator' is called to make one (lazy init)
-     * @return dynamic method handle associated with the key.
-     */
-    public MethodHandle getDynamicInvoker(final Object key, final Callable<MethodHandle> creator);
-}
--- a/nashorn/src/jdk/nashorn/internal/runtime/JSONFunctions.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/JSONFunctions.java	Wed Jul 05 19:33:51 2017 +0200
@@ -33,6 +33,7 @@
 import jdk.nashorn.internal.ir.ObjectNode;
 import jdk.nashorn.internal.ir.PropertyNode;
 import jdk.nashorn.internal.ir.UnaryNode;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.parser.JSONParser;
 import jdk.nashorn.internal.parser.TokenType;
 import jdk.nashorn.internal.runtime.arrays.ArrayIndex;
@@ -47,7 +48,7 @@
     private static final Object REVIVER_INVOKER = new Object();
 
     private static MethodHandle getREVIVER_INVOKER() {
-        return ((GlobalObject)Context.getGlobal()).getDynamicInvoker(REVIVER_INVOKER,
+        return Context.getGlobal().getDynamicInvoker(REVIVER_INVOKER,
                 new Callable<MethodHandle>() {
                     @Override
                     public MethodHandle call() {
@@ -88,7 +89,7 @@
             throw ECMAErrors.syntaxError(e, "invalid.json", e.getMessage());
         }
 
-        final ScriptObject global = Context.getGlobalTrusted();
+        final Global global = Context.getGlobal();
         Object unfiltered = convertNode(global, node);
         return applyReviver(global, unfiltered, reviver);
     }
@@ -98,10 +99,10 @@
     // parse helpers
 
     // apply 'reviver' function if available
-    private static Object applyReviver(final ScriptObject global, final Object unfiltered, final Object reviver) {
+    private static Object applyReviver(final Global global, final Object unfiltered, final Object reviver) {
         if (reviver instanceof ScriptFunction) {
-            assert global instanceof GlobalObject;
-            final ScriptObject root = ((GlobalObject)global).newObject();
+            assert global instanceof Global;
+            final ScriptObject root = global.newObject();
             root.addOwnProperty("", Property.WRITABLE_ENUMERABLE_CONFIGURABLE, unfiltered);
             return walk(root, "", (ScriptFunction)reviver);
         }
@@ -138,8 +139,8 @@
     }
 
     // Converts IR node to runtime value
-    private static Object convertNode(final ScriptObject global, final Node node) {
-        assert global instanceof GlobalObject;
+    private static Object convertNode(final Global global, final Node node) {
+        assert global instanceof Global;
 
         if (node instanceof LiteralNode) {
             // check for array literal
@@ -157,7 +158,7 @@
                     for (final Node elem : elements) {
                         values[index++] = JSType.toNumber(convertNode(global, elem));
                     }
-                    return ((GlobalObject)global).wrapAsObject(values);
+                    return global.wrapAsObject(values);
                 }
 
                 final Object[] values = new Object[elements.length];
@@ -167,14 +168,14 @@
                     values[index++] = convertNode(global, elem);
                 }
 
-                return ((GlobalObject)global).wrapAsObject(values);
+                return global.wrapAsObject(values);
             }
 
             return ((LiteralNode<?>)node).getValue();
 
         } else if (node instanceof ObjectNode) {
             final ObjectNode   objNode  = (ObjectNode) node;
-            final ScriptObject object   = ((GlobalObject)global).newObject();
+            final ScriptObject object   = global.newObject();
 
             for (final PropertyNode pNode: objNode.getElements()) {
                 final Node         valueNode = pNode.getValue();
--- a/nashorn/src/jdk/nashorn/internal/runtime/JSType.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/JSType.java	Wed Jul 05 19:33:51 2017 +0200
@@ -36,6 +36,7 @@
 import jdk.internal.dynalink.beans.StaticClass;
 import jdk.nashorn.api.scripting.JSObject;
 import jdk.nashorn.internal.codegen.CompilerConstants.Call;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.parser.Lexer;
 import jdk.nashorn.internal.runtime.arrays.ArrayLikeIterator;
 import jdk.nashorn.internal.runtime.linker.Bootstrap;
@@ -852,7 +853,7 @@
      * @return the wrapped object
      */
     public static Object toScriptObject(final Object obj) {
-        return toScriptObject(Context.getGlobalTrusted(), obj);
+        return toScriptObject(Context.getGlobal(), obj);
     }
 
     /**
@@ -865,7 +866,7 @@
      *
      * @return the wrapped object
      */
-    public static Object toScriptObject(final ScriptObject global, final Object obj) {
+    public static Object toScriptObject(final Global global, final Object obj) {
         if (nullOrUndefined(obj)) {
             throw typeError(global, "not.an.object", ScriptRuntime.safeToString(obj));
         }
@@ -874,7 +875,7 @@
             return obj;
         }
 
-        return ((GlobalObject)global).wrapAsObject(obj);
+        return global.wrapAsObject(obj);
     }
 
     /**
@@ -984,7 +985,7 @@
         if (obj instanceof ScriptObject) {
             if (safe) {
                 final ScriptObject sobj = (ScriptObject)obj;
-                final GlobalObject gobj = (GlobalObject)Context.getGlobalTrusted();
+                final Global gobj = Context.getGlobal();
                 return gobj.isError(sobj) ?
                     ECMAException.safeToString(sobj) :
                     sobj.safeToString();
--- a/nashorn/src/jdk/nashorn/internal/runtime/ListAdapter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ListAdapter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -34,6 +34,7 @@
 import java.util.concurrent.Callable;
 import jdk.nashorn.api.scripting.JSObject;
 import jdk.nashorn.api.scripting.ScriptObjectMirror;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.linker.Bootstrap;
 import jdk.nashorn.internal.runtime.linker.InvokeByName;
 
@@ -54,7 +55,7 @@
     // These add to the back and front of the list
     private static final Object PUSH    = new Object();
     private static InvokeByName getPUSH() {
-        return ((GlobalObject)Context.getGlobal()).getInvokeByName(PUSH,
+        return Context.getGlobal().getInvokeByName(PUSH,
                 new Callable<InvokeByName>() {
                     @Override
                     public InvokeByName call() {
@@ -65,7 +66,7 @@
 
     private static final Object UNSHIFT = new Object();
     private static InvokeByName getUNSHIFT() {
-        return ((GlobalObject)Context.getGlobal()).getInvokeByName(UNSHIFT,
+        return Context.getGlobal().getInvokeByName(UNSHIFT,
                 new Callable<InvokeByName>() {
                     @Override
                     public InvokeByName call() {
@@ -77,7 +78,7 @@
     // These remove from the back and front of the list
     private static final Object POP = new Object();
     private static InvokeByName getPOP() {
-        return ((GlobalObject)Context.getGlobal()).getInvokeByName(POP,
+        return Context.getGlobal().getInvokeByName(POP,
                 new Callable<InvokeByName>() {
                     @Override
                     public InvokeByName call() {
@@ -88,7 +89,7 @@
 
     private static final Object SHIFT = new Object();
     private static InvokeByName getSHIFT() {
-        return ((GlobalObject)Context.getGlobal()).getInvokeByName(SHIFT,
+        return Context.getGlobal().getInvokeByName(SHIFT,
                 new Callable<InvokeByName>() {
                     @Override
                     public InvokeByName call() {
@@ -100,7 +101,7 @@
     // These insert and remove in the middle of the list
     private static final Object SPLICE_ADD = new Object();
     private static InvokeByName getSPLICE_ADD() {
-        return ((GlobalObject)Context.getGlobal()).getInvokeByName(SPLICE_ADD,
+        return Context.getGlobal().getInvokeByName(SPLICE_ADD,
                 new Callable<InvokeByName>() {
                     @Override
                     public InvokeByName call() {
@@ -111,7 +112,7 @@
 
     private static final Object SPLICE_REMOVE = new Object();
     private static InvokeByName getSPLICE_REMOVE() {
-        return ((GlobalObject)Context.getGlobal()).getInvokeByName(SPLICE_REMOVE,
+        return  Context.getGlobal().getInvokeByName(SPLICE_REMOVE,
                 new Callable<InvokeByName>() {
                     @Override
                     public InvokeByName call() {
--- a/nashorn/src/jdk/nashorn/internal/runtime/NativeJavaPackage.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/NativeJavaPackage.java	Wed Jul 05 19:33:51 2017 +0200
@@ -35,7 +35,6 @@
 import jdk.internal.dynalink.support.Guards;
 import jdk.nashorn.internal.lookup.MethodHandleFactory;
 import jdk.nashorn.internal.lookup.MethodHandleFunctionality;
-import jdk.nashorn.internal.objects.NativeJava;
 import jdk.nashorn.internal.objects.annotations.Attribute;
 import jdk.nashorn.internal.objects.annotations.Function;
 
@@ -52,7 +51,7 @@
  * var ArrayList = java.util.ArrayList
  * var list = new ArrayList
  * </pre>
- * You can also use {@link NativeJava#type(Object, Object)} to access Java classes. These two statements are mostly
+ * You can also use {@link jdk.nashorn.internal.objects.NativeJava#type(Object, Object)} to access Java classes. These two statements are mostly
  * equivalent:
  * <pre>
  * var listType1 = java.util.ArrayList
--- a/nashorn/src/jdk/nashorn/internal/runtime/ParserException.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ParserException.java	Wed Jul 05 19:33:51 2017 +0200
@@ -26,6 +26,7 @@
 package jdk.nashorn.internal.runtime;
 
 import jdk.nashorn.api.scripting.NashornException;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.parser.Token;
 
 /**
@@ -110,7 +111,7 @@
      * Throw this {@code ParserException} as one of the 7 native JavaScript errors
      * @param global global scope object
      */
-    public void throwAsEcmaException(final ScriptObject global) {
+    public void throwAsEcmaException(final Global global) {
         throw ECMAErrors.asEcmaException(global, this);
     }
 }
--- a/nashorn/src/jdk/nashorn/internal/runtime/Property.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/Property.java	Wed Jul 05 19:33:51 2017 +0200
@@ -84,9 +84,13 @@
     /** Can this property be undefined? */
     public static final int CAN_BE_UNDEFINED = 1 << 8;
 
-    /* Is this a function declaration property ? */
+    /** Is this a function declaration property ? */
     public static final int IS_FUNCTION_DECLARATION = 1 << 9;
 
+    /** Is this property bound to a receiver? This means get/set operations will be delegated to
+     *  a statically defined object instead of the object passed as callsite parameter. */
+    public static final int IS_BOUND = 1 << 10;
+
     /** Property key. */
     private final String key;
 
@@ -252,6 +256,16 @@
     }
 
     /**
+     * Is this property bound to a receiver? If this method returns {@code true} get and set operations
+     * will be delegated to a statically bound object instead of the object passed as parameter.
+     *
+     * @return true if this is a bound property
+     */
+    public boolean isBound() {
+        return (flags & IS_BOUND) == IS_BOUND;
+    }
+
+    /**
      * Does this property use any slots in the spill array described in
      * {@link Property#isSpill}? In that case how many. Currently a property
      * only uses max one spill slot, but this may change in future representations
--- a/nashorn/src/jdk/nashorn/internal/runtime/RecompilableScriptFunctionData.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/RecompilableScriptFunctionData.java	Wed Jul 05 19:33:51 2017 +0200
@@ -103,9 +103,7 @@
     public RecompilableScriptFunctionData(final FunctionNode functionNode, final CodeInstaller<ScriptEnvironment> installer, final String allocatorClassName, final PropertyMap allocatorMap) {
         super(functionName(functionNode),
               functionNode.getParameters().size(),
-              functionNode.isStrict(),
-              false,
-              true);
+              getFlags(functionNode));
 
         this.functionNode       = functionNode;
         this.source             = functionNode.getSource();
@@ -129,10 +127,11 @@
         final StringBuilder sb = new StringBuilder();
 
         if (source != null) {
-            sb.append(source.getName())
-                .append(':')
-                .append(functionNode.getLineNumber())
-                .append(' ');
+            sb.append(source.getName());
+            if (functionNode != null) {
+                sb.append(':').append(functionNode.getLineNumber());
+            }
+            sb.append(' ');
         }
 
         return sb.toString() + super.toString();
@@ -159,6 +158,20 @@
         return Token.toDesc(TokenType.FUNCTION, position, length);
     }
 
+    private static int getFlags(final FunctionNode functionNode) {
+        int flags = IS_CONSTRUCTOR;
+        if (functionNode.isStrict()) {
+            flags |= IS_STRICT;
+        }
+        if (functionNode.needsCallee()) {
+            flags |= NEEDS_CALLEE;
+        }
+        if (functionNode.usesThis() || functionNode.hasEval()) {
+            flags |= USES_THIS;
+        }
+        return flags;
+    }
+
     @Override
     ScriptObject allocate(final PropertyMap map) {
         try {
@@ -182,41 +195,42 @@
         return allocatorMap;
     }
 
+
+    @Override
+    protected void ensureCompiled() {
+        if (functionNode != null && functionNode.isLazy()) {
+            Compiler.LOG.info("Trampoline hit: need to do lazy compilation of '", functionNode.getName(), "'");
+            final Compiler compiler = new Compiler(installer);
+            functionNode = compiler.compile(functionNode);
+            assert !functionNode.isLazy();
+            compiler.install(functionNode);
+            flags = getFlags(functionNode);
+        }
+    }
+
     @Override
     protected synchronized void ensureCodeGenerated() {
-         if (!code.isEmpty()) {
-             return; // nothing to do, we have code, at least some.
-         }
+        if (!code.isEmpty()) {
+            return; // nothing to do, we have code, at least some.
+        }
 
-         if (functionNode.isLazy()) {
-             Compiler.LOG.info("Trampoline hit: need to do lazy compilation of '", functionNode.getName(), "'");
-             final Compiler compiler = new Compiler(installer);
-             functionNode = compiler.compile(functionNode);
-             assert !functionNode.isLazy();
-             compiler.install(functionNode);
+        ensureCompiled();
+
+        /*
+         * We can't get to this program point unless we have bytecode, either from
+         * eager compilation or from running a lazy compile on the lines above
+         */
 
-             /*
-              * We don't need to update any flags - varArgs and needsCallee are instrincic
-              * in the function world we need to get a destination node from the compile instead
-              * and replace it with our function node. TODO
-              */
-         }
+        assert functionNode.hasState(CompilationState.EMITTED) : functionNode.getName() + " " + functionNode.getState() + " " + Debug.id(functionNode);
+
+        // code exists - look it up and add it into the automatically sorted invoker list
+        addCode(functionNode);
 
-         /*
-          * We can't get to this program point unless we have bytecode, either from
-          * eager compilation or from running a lazy compile on the lines above
-          */
-
-         assert functionNode.hasState(CompilationState.EMITTED) : functionNode.getName() + " " + functionNode.getState() + " " + Debug.id(functionNode);
-
-         // code exists - look it up and add it into the automatically sorted invoker list
-         addCode(functionNode);
-
-         if (! functionNode.canSpecialize()) {
-             // allow GC to claim IR stuff that is not needed anymore
-             functionNode = null;
-             installer = null;
-         }
+        if (! functionNode.canSpecialize()) {
+            // allow GC to claim IR stuff that is not needed anymore
+            functionNode = null;
+            installer = null;
+        }
     }
 
     private MethodHandle addCode(final FunctionNode fn) {
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptFunction.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptFunction.java	Wed Jul 05 19:33:51 2017 +0200
@@ -38,6 +38,7 @@
 import jdk.internal.dynalink.linker.LinkRequest;
 import jdk.nashorn.internal.codegen.CompilerConstants.Call;
 import jdk.nashorn.internal.lookup.MethodHandleFactory;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
 import jdk.nashorn.internal.runtime.linker.NashornGuards;
 
@@ -66,6 +67,8 @@
 
     private static final MethodHandle WRAPFILTER = findOwnMH("wrapFilter", Object.class, Object.class);
 
+    private static final MethodHandle GLOBALFILTER = findOwnMH("globalFilter", Object.class, Object.class);
+
     /** method handle to scope getter for this ScriptFunction */
     public static final Call GET_SCOPE = virtualCallNoLookup(ScriptFunction.class, "getScope", ScriptObject.class);
 
@@ -91,9 +94,7 @@
      * @param map           property map
      * @param scope         scope
      * @param specs         specialized version of this function - other method handles
-     * @param strict        is this a strict mode function?
-     * @param builtin       is this a built in function?
-     * @param isConstructor is this a constructor?
+     * @param flags         {@link ScriptFunctionData} flags
      */
     protected ScriptFunction(
             final String name,
@@ -101,11 +102,9 @@
             final PropertyMap map,
             final ScriptObject scope,
             final MethodHandle[] specs,
-            final boolean strict,
-            final boolean builtin,
-            final boolean isConstructor) {
+            final int flags) {
 
-        this(new FinalScriptFunctionData(name, methodHandle, specs, strict, builtin, isConstructor), map, scope);
+        this(new FinalScriptFunctionData(name, methodHandle, specs, flags), map, scope);
     }
 
     /**
@@ -477,7 +476,14 @@
         if (obj instanceof ScriptObject || !ScriptFunctionData.isPrimitiveThis(obj)) {
             return obj;
         }
-        return ((GlobalObject)Context.getGlobalTrusted()).wrapAsObject(obj);
+        return Context.getGlobal().wrapAsObject(obj);
+    }
+
+
+    @SuppressWarnings("unused")
+    private static Object globalFilter(final Object object) {
+        // replace whatever we get with the current global object
+        return Context.getGlobal();
     }
 
     /**
@@ -495,11 +501,11 @@
     @Override
     protected GuardedInvocation findCallMethod(final CallSiteDescriptor desc, final LinkRequest request) {
         final MethodType type = desc.getMethodType();
+        final boolean scopeCall = NashornCallSiteDescriptor.isScope(desc);
 
         if (request.isCallSiteUnstable()) {
-            // (this, callee, args...) => (this, callee, args[])
-            final MethodHandle collector = MH.asCollector(ScriptRuntime.APPLY.methodHandle(), Object[].class,
-                    type.parameterCount() - 2);
+            // (callee, this, args...) => (callee, this, args[])
+            final MethodHandle collector = MH.asCollector(ScriptRuntime.APPLY.methodHandle(), Object[].class, type.parameterCount() - 2);
 
             // If call site is statically typed to take a ScriptFunction, we don't need a guard, otherwise we need a
             // generic "is this a ScriptFunction?" guard.
@@ -510,17 +516,12 @@
         MethodHandle boundHandle;
         MethodHandle guard = null;
 
-        final boolean scopeCall = NashornCallSiteDescriptor.isScope(desc);
-
         if (data.needsCallee()) {
             final MethodHandle callHandle = getBestInvoker(type, request.getArguments());
-            if (scopeCall) {
+            if (scopeCall && needsWrappedThis()) {
                 // Make a handle that drops the passed "this" argument and substitutes either Global or Undefined
-                // (callee, this, args...) => (callee, args...)
-                boundHandle = MH.insertArguments(callHandle, 1, needsWrappedThis() ? Context.getGlobalTrusted() : ScriptRuntime.UNDEFINED);
-                // (callee, args...) => (callee, [this], args...)
-                boundHandle = MH.dropArguments(boundHandle, 1, Object.class);
-
+                // (callee, this, args...) => (callee, [this], args...)
+                boundHandle = MH.filterArguments(callHandle, 1, GLOBALFILTER);
             } else {
                 // It's already (callee, this, args...), just what we need
                 boundHandle = callHandle;
@@ -531,12 +532,12 @@
                 // NOTE: the only built-in named "extend" is NativeJava.extend. As a special-case we're binding the
                 // current lookup as its "this" so it can do security-sensitive creation of adapter classes.
                 boundHandle = MH.dropArguments(MH.bindTo(callHandle, desc.getLookup()), 0, Object.class, Object.class);
-            } else if (scopeCall) {
+            } else if (scopeCall && needsWrappedThis()) {
                 // Make a handle that drops the passed "this" argument and substitutes either Global or Undefined
-                // (this, args...) => (args...)
-                boundHandle = MH.bindTo(callHandle, needsWrappedThis() ? Context.getGlobalTrusted() : ScriptRuntime.UNDEFINED);
-                // (args...) => ([callee], [this], args...)
-                boundHandle = MH.dropArguments(boundHandle, 0, Object.class, Object.class);
+                // (this, args...) => ([this], args...)
+                boundHandle = MH.filterArguments(callHandle, 0, GLOBALFILTER);
+                // ([this], args...) => ([callee], [this], args...)
+                boundHandle = MH.dropArguments(boundHandle, 0, Object.class);
             } else {
                 // (this, args...) => ([callee], this, args...)
                 boundHandle = MH.dropArguments(callHandle, 0, Object.class);
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptFunctionData.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptFunctionData.java	Wed Jul 05 19:33:51 2017 +0200
@@ -32,6 +32,7 @@
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
 import java.lang.invoke.MethodType;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.linker.JavaAdapterFactory;
 
 /**
@@ -47,33 +48,44 @@
     /** All versions of this function that have been generated to code */
     protected final CompiledFunctions code;
 
-    private int arity;
-
-    private final boolean isStrict;
+    /** Function flags */
+    protected int flags;
 
-    private final boolean isBuiltin;
-
-    private final boolean isConstructor;
+    private int arity;
 
     private static final MethodHandle NEWFILTER     = findOwnMH("newFilter", Object.class, Object.class, Object.class);
     private static final MethodHandle BIND_VAR_ARGS = findOwnMH("bindVarArgs", Object[].class, Object[].class, Object[].class);
 
+    /** Is this a strict mode function? */
+    public static final int IS_STRICT      = 1 << 0;
+    /** Is this a built-in function? */
+    public static final int IS_BUILTIN     = 1 << 1;
+    /** Is this a constructor function? */
+    public static final int IS_CONSTRUCTOR = 1 << 2;
+    /** Does this function expect a callee argument? */
+    public static final int NEEDS_CALLEE   = 1 << 3;
+    /** Does this function make use of the this-object argument? */
+    public static final int USES_THIS      = 1 << 4;
+
+    /** Flag for strict or built-in functions */
+    public static final int IS_STRICT_OR_BUILTIN = IS_STRICT | IS_BUILTIN;
+    /** Flag for built-in constructors */
+    public static final int IS_BUILTIN_CONSTRUCTOR = IS_BUILTIN | IS_CONSTRUCTOR;
+    /** Flag for strict constructors */
+    public static final int IS_STRICT_CONSTRUCTOR = IS_STRICT | IS_CONSTRUCTOR;
+
     /**
      * Constructor
      *
      * @param name          script function name
      * @param arity         arity
-     * @param isStrict      is the function strict
-     * @param isBuiltin     is the function built in
-     * @param isConstructor is the function a constructor
+     * @param flags         the function flags
      */
-    ScriptFunctionData(final String name, final int arity, final boolean isStrict, final boolean isBuiltin, final boolean isConstructor) {
-        this.name          = name;
-        this.arity         = arity;
-        this.code          = new CompiledFunctions();
-        this.isStrict      = isStrict;
-        this.isBuiltin     = isBuiltin;
-        this.isConstructor = isConstructor;
+    ScriptFunctionData(final String name, final int arity, final int flags) {
+        this.name  = name;
+        this.arity = arity;
+        this.code  = new CompiledFunctions();
+        this.flags = flags;
     }
 
     final int getArity() {
@@ -105,21 +117,21 @@
      * @return true if strict, false otherwise
      */
     public boolean isStrict() {
-        return isStrict;
+        return (flags & IS_STRICT) != 0;
     }
 
     boolean isBuiltin() {
-        return isBuiltin;
+        return (flags & IS_BUILTIN) != 0;
     }
 
     boolean isConstructor() {
-        return isConstructor;
+        return (flags & IS_CONSTRUCTOR) != 0;
     }
 
     boolean needsCallee() {
-        // we don't know if we need a callee or not unless we are generated
-        ensureCodeGenerated();
-        return code.needsCallee();
+        // we don't know if we need a callee or not unless code has been compiled
+        ensureCompiled();
+        return (flags & NEEDS_CALLEE) != 0;
     }
 
     /**
@@ -128,7 +140,7 @@
      * @return true if this argument must be an object
      */
     boolean needsWrappedThis() {
-        return !isStrict && !isBuiltin;
+        return (flags & USES_THIS) != 0 && (flags & IS_STRICT_OR_BUILTIN) == 0;
     }
 
     String toSource() {
@@ -202,6 +214,15 @@
     }
 
     /**
+     * If we can have lazy code generation, this is a hook to ensure that the code has been compiled.
+     * This does not guarantee the code been installed in this {@code ScriptFunctionData} instance;
+     * use {@link #ensureCodeGenerated()} to install the actual method handles.
+     */
+    protected void ensureCompiled() {
+        //empty
+    }
+
+    /**
      * Return a generic Object/Object invoker for this method. It will ensure code
      * is generated, get the most generic of all versions of this function and adapt it
      * to Objects.
@@ -259,6 +280,8 @@
 
         final Object[] allArgs = args == null ? ScriptRuntime.EMPTY_ARRAY : args;
         final int length = args == null ? 0 : args.length;
+        // Clear the callee and this flags
+        final int boundFlags = flags & ~NEEDS_CALLEE & ~USES_THIS;
 
         CompiledFunctions boundList = new CompiledFunctions();
         if (code.size() == 1) {
@@ -273,8 +296,7 @@
             boundList.add(bind(inv, fn, self, allArgs));
         }
 
-        ScriptFunctionData boundData = new FinalScriptFunctionData(name, arity == -1 ? -1 : Math.max(0, arity - length), boundList, isStrict(), isBuiltin(), isConstructor());
-        return boundData;
+        return new FinalScriptFunctionData(name, arity == -1 ? -1 : Math.max(0, arity - length), boundList, boundFlags);
     }
 
     /**
@@ -351,11 +373,11 @@
     private Object convertThisObject(final Object thiz) {
         if (!(thiz instanceof ScriptObject) && needsWrappedThis()) {
             if (JSType.nullOrUndefined(thiz)) {
-                return Context.getGlobalTrusted();
+                return Context.getGlobal();
             }
 
             if (isPrimitiveThis(thiz)) {
-                return ((GlobalObject)Context.getGlobalTrusted()).wrapAsObject(thiz);
+                return Context.getGlobal().wrapAsObject(thiz);
             }
         }
 
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java	Wed Jul 05 19:33:51 2017 +0200
@@ -66,6 +66,7 @@
 import jdk.nashorn.internal.lookup.MethodHandleFactory;
 import jdk.nashorn.internal.objects.AccessorPropertyDescriptor;
 import jdk.nashorn.internal.objects.DataPropertyDescriptor;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.arrays.ArrayData;
 import jdk.nashorn.internal.runtime.arrays.ArrayIndex;
 import jdk.nashorn.internal.runtime.linker.Bootstrap;
@@ -131,7 +132,8 @@
 
     static final MethodHandle GETPROTO           = findOwnMH("getProto", ScriptObject.class);
     static final MethodHandle SETPROTOCHECK      = findOwnMH("setProtoCheck", void.class, Object.class);
-    static final MethodHandle MEGAMORPHIC_GET    = findOwnMH("megamorphicGet", Object.class, String.class, boolean.class);
+    static final MethodHandle MEGAMORPHIC_GET    = findOwnMH("megamorphicGet", Object.class, String.class, boolean.class, boolean.class);
+    static final MethodHandle GLOBALFILTER       = findOwnMH("globalFilter", Object.class, Object.class);
 
     static final MethodHandle SETFIELD           = findOwnMH("setField",         void.class, CallSiteDescriptor.class, PropertyMap.class, PropertyMap.class, MethodHandle.class, Object.class, Object.class);
     static final MethodHandle SETSPILL           = findOwnMH("setSpill",         void.class, CallSiteDescriptor.class, PropertyMap.class, PropertyMap.class, int.class, Object.class, Object.class);
@@ -225,6 +227,7 @@
             final Property oldProp = newMap.findProperty(key);
             if (oldProp == null) {
                 if (property instanceof UserAccessorProperty) {
+                    // Note: we copy accessor functions to this object which is semantically different from binding.
                     final UserAccessorProperty prop = this.newUserAccessors(key, property.getFlags(), property.getGetterFunction(source), property.getSetterFunction(source));
                     newMap = newMap.addPropertyNoHistory(prop);
                 } else {
@@ -322,18 +325,18 @@
       * @return property descriptor
       */
     public final PropertyDescriptor toPropertyDescriptor() {
-        final GlobalObject global = (GlobalObject) Context.getGlobalTrusted();
+        final Global global = Context.getGlobal();
 
         final PropertyDescriptor desc;
         if (isDataDescriptor()) {
             if (has(SET) || has(GET)) {
-                throw typeError((ScriptObject)global, "inconsistent.property.descriptor");
+                throw typeError(global, "inconsistent.property.descriptor");
             }
 
             desc = global.newDataDescriptor(UNDEFINED, false, false, false);
         } else if (isAccessorDescriptor()) {
             if (has(VALUE) || has(WRITABLE)) {
-                throw typeError((ScriptObject)global, "inconsistent.property.descriptor");
+                throw typeError(global, "inconsistent.property.descriptor");
             }
 
             desc = global.newAccessorDescriptor(UNDEFINED, UNDEFINED, false, false);
@@ -352,7 +355,7 @@
      *
      * @return property descriptor
      */
-    public static PropertyDescriptor toPropertyDescriptor(final ScriptObject global, final Object obj) {
+    public static PropertyDescriptor toPropertyDescriptor(final Global global, final Object obj) {
         if (obj instanceof ScriptObject) {
             return ((ScriptObject)obj).toPropertyDescriptor();
         }
@@ -371,7 +374,7 @@
     public Object getOwnPropertyDescriptor(final String key) {
         final Property property = getMap().findProperty(key);
 
-        final GlobalObject global = (GlobalObject)Context.getGlobalTrusted();
+        final Global global = Context.getGlobal();
 
         if (property != null) {
             final ScriptFunction get   = property.getGetterFunction(this);
@@ -436,7 +439,7 @@
      * @return true if property was successfully defined
      */
     public boolean defineOwnProperty(final String key, final Object propertyDesc, final boolean reject) {
-        final ScriptObject       global  = Context.getGlobalTrusted();
+        final Global             global  = Context.getGlobal();
         final PropertyDescriptor desc    = toPropertyDescriptor(global, propertyDesc);
         final Object             current = getOwnPropertyDescriptor(key);
         final String             name    = JSType.toString(key);
@@ -634,7 +637,7 @@
         final int propFlags = Property.toFlags(pdesc);
 
         if (pdesc.type() == PropertyDescriptor.GENERIC) {
-            final GlobalObject global = (GlobalObject) Context.getGlobalTrusted();
+            final Global global = Context.getGlobal();
             final PropertyDescriptor dDesc = global.newDataDescriptor(UNDEFINED, false, false, false);
 
             dDesc.fillFrom((ScriptObject)pdesc);
@@ -975,17 +978,6 @@
     }
 
     /**
-      * Get the object value of a property
-      *
-      * @param find {@link FindProperty} lookup result
-      *
-      * @return the value of the property
-      */
-    protected static Object getObjectValue(final FindProperty find) {
-        return find.getObjectValue();
-    }
-
-    /**
      * Return methodHandle of value function for call.
      *
      * @param find      data from find property.
@@ -995,7 +987,7 @@
      * @return value of property as a MethodHandle or null.
      */
     protected MethodHandle getCallMethodHandle(final FindProperty find, final MethodType type, final String bindName) {
-        return getCallMethodHandle(getObjectValue(find), type, bindName);
+        return getCallMethodHandle(find.getObjectValue(), type, bindName);
     }
 
     /**
@@ -1019,7 +1011,7 @@
      * @return Value of property.
      */
     public final Object getWithProperty(final Property property) {
-        return getObjectValue(new FindProperty(this, this, property));
+        return new FindProperty(this, this, property).getObjectValue();
     }
 
     /**
@@ -1158,7 +1150,7 @@
             }
             setProto((ScriptObject)newProto);
         } else {
-            final ScriptObject global = Context.getGlobalTrusted();
+            final Global global = Context.getGlobal();
             final Object  newProtoObject = JSType.toScriptObject(global, newProto);
 
             if (newProtoObject instanceof ScriptObject) {
@@ -1248,11 +1240,11 @@
      * @return the default value
      */
     public Object getDefaultValue(final Class<?> typeHint) {
-        // We delegate to GlobalObject, as the implementation uses dynamic call sites to invoke object's "toString" and
+        // We delegate to Global, as the implementation uses dynamic call sites to invoke object's "toString" and
         // "valueOf" methods, and in order to avoid those call sites from becoming megamorphic when multiple contexts
         // are being executed in a long-running program, we move the code and their associated dynamic call sites
         // (Global.TO_STRING and Global.VALUE_OF) into per-context code.
-        return ((GlobalObject)Context.getGlobalTrusted()).getDefaultValue(this, typeHint);
+        return Context.getGlobal().getDefaultValue(this, typeHint);
     }
 
     /**
@@ -1740,7 +1732,7 @@
     protected GuardedInvocation findGetMethod(final CallSiteDescriptor desc, final LinkRequest request, final String operator) {
         final String name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
         if (request.isCallSiteUnstable() || hasWithScope()) {
-            return findMegaMorphicGetMethod(desc, name, "getMethod".equals(operator));
+            return findMegaMorphicGetMethod(desc, name, "getMethod".equals(operator), isScope() && NashornCallSiteDescriptor.isScope(desc));
         }
 
         final FindProperty find = findProperty(name, true);
@@ -1765,9 +1757,8 @@
         final Property property = find.getProperty();
         methodHandle = find.getGetter(returnType);
 
-        final boolean noGuard = ObjectClassGenerator.OBJECT_FIELDS_ONLY && NashornCallSiteDescriptor.isFastScope(desc) && !property.canChangeType();
-        // getMap() is fine as we have the prototype switchpoint depending on where the property was found
-        final MethodHandle guard = noGuard ? null : NashornGuards.getMapGuard(getMap());
+        // Get the appropriate guard for this callsite and property.
+        final MethodHandle guard = NashornGuards.getGuard(this, property, desc);
         final ScriptObject owner = find.getOwner();
 
         if (methodHandle != null) {
@@ -1777,31 +1768,32 @@
             }
 
             if (!property.hasGetterFunction(owner)) {
-                // If not a scope bind to actual prototype as changing prototype will change the property map.
-                // For scopes we install a filter that replaces the self object with the prototype owning the property.
-                methodHandle = isScope() ?
-                        addProtoFilter(methodHandle, find.getProtoChainLength()) :
-                        bindTo(methodHandle, owner);
+                // Add a filter that replaces the self object with the prototype owning the property.
+                methodHandle = addProtoFilter(methodHandle, find.getProtoChainLength());
             }
-            return new GuardedInvocation(methodHandle, noGuard ? null : getProtoSwitchPoint(name, owner), guard);
+            return new GuardedInvocation(methodHandle, guard == null ? null : getProtoSwitchPoint(name, owner), guard);
         }
 
         assert !NashornCallSiteDescriptor.isFastScope(desc);
         return new GuardedInvocation(Lookup.emptyGetter(returnType), getProtoSwitchPoint(name, owner), guard);
     }
 
-    private static GuardedInvocation findMegaMorphicGetMethod(final CallSiteDescriptor desc, final String name, final boolean isMethod) {
-        final MethodHandle invoker = MH.insertArguments(MEGAMORPHIC_GET, 1, name, isMethod);
+    private static GuardedInvocation findMegaMorphicGetMethod(final CallSiteDescriptor desc, final String name,
+                                                              final boolean isMethod, final boolean isScope) {
+        final MethodHandle invoker = MH.insertArguments(MEGAMORPHIC_GET, 1, name, isMethod, isScope);
         final MethodHandle guard = getScriptObjectGuard(desc.getMethodType());
         return new GuardedInvocation(invoker, guard);
     }
 
     @SuppressWarnings("unused")
-    private Object megamorphicGet(final String key, final boolean isMethod) {
+    private Object megamorphicGet(final String key, final boolean isMethod, final boolean isScope) {
         final FindProperty find = findProperty(key, true);
 
         if (find != null) {
-            return getObjectValue(find);
+            return find.getObjectValue();
+        }
+        if (isScope) {
+            throw referenceError("not.defined", key);
         }
 
         return isMethod ? getNoSuchMethod(key) : invokeNoSuchProperty(key);
@@ -1996,6 +1988,15 @@
         }
     }
 
+    @SuppressWarnings("unused")
+    private static Object globalFilter(final Object object) {
+        ScriptObject sobj = (ScriptObject) object;
+        while (sobj != null && !(sobj instanceof Global)) {
+            sobj = sobj.getProto();
+        }
+        return sobj;
+    }
+
     private static GuardedInvocation findMegaMorphicSetMethod(final CallSiteDescriptor desc, final String name) {
         final MethodType type = desc.getMethodType().insertParameterTypes(1, Object.class);
         final GuardedInvocation inv = findSetIndexMethod(type, NashornCallSiteDescriptor.isStrict(desc));
@@ -2041,7 +2042,7 @@
             return noSuchProperty(desc, request);
         }
 
-        final Object value = getObjectValue(find);
+        final Object value = find.getObjectValue();
         if (! (value instanceof ScriptFunction)) {
             return createEmptyGetter(desc, name);
         }
@@ -2067,7 +2068,7 @@
         final boolean scopeAccess = isScope() && NashornCallSiteDescriptor.isScope(desc);
 
         if (find != null) {
-            final Object   value        = getObjectValue(find);
+            final Object   value        = find.getObjectValue();
             ScriptFunction func         = null;
             MethodHandle   methodHandle = null;
 
@@ -2102,7 +2103,7 @@
         final FindProperty find = findProperty(NO_SUCH_PROPERTY_NAME, true);
 
         if (find != null) {
-            final Object func = getObjectValue(find);
+            final Object func = find.getObjectValue();
 
             if (func instanceof ScriptFunction) {
                 return ScriptRuntime.apply((ScriptFunction)func, this, name);
@@ -2124,7 +2125,7 @@
             return invokeNoSuchProperty(name);
         }
 
-        final Object value = getObjectValue(find);
+        final Object value = find.getObjectValue();
         if (! (value instanceof ScriptFunction)) {
             return UNDEFINED;
         }
@@ -2664,7 +2665,7 @@
                     final FindProperty find = object.findProperty(key, false, false, this);
 
                     if (find != null) {
-                        return getObjectValue(find);
+                        return find.getObjectValue();
                     }
                 }
 
@@ -2682,7 +2683,7 @@
             final FindProperty find = findProperty(key, true);
 
             if (find != null) {
-                return getObjectValue(find);
+                return find.getObjectValue();
             }
         }
 
@@ -2823,7 +2824,15 @@
                 throw typeError("object.non.extensible", key, ScriptRuntime.safeToString(this));
             }
         } else {
-            spill(key, value);
+            ScriptObject sobj = this;
+            // undefined scope properties are set in the global object.
+            if (isScope()) {
+                while (sobj != null && !(sobj instanceof Global)) {
+                    sobj = sobj.getProto();
+                }
+                assert sobj != null : "no parent global object in scope";
+            }
+            sobj.spill(key, value);
         }
     }
 
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java	Wed Jul 05 19:33:51 2017 +0200
@@ -474,7 +474,7 @@
      * @return {@link WithObject} that is the new scope
      */
     public static ScriptObject openWith(final ScriptObject scope, final Object expression) {
-        final ScriptObject global = Context.getGlobalTrusted();
+        final Global global = Context.getGlobal();
         if (expression == UNDEFINED) {
             throw typeError(global, "cant.apply.with.to.undefined");
         } else if (expression == null) {
--- a/nashorn/src/jdk/nashorn/internal/runtime/SetMethodCreator.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/SetMethodCreator.java	Wed Jul 05 19:33:51 2017 +0200
@@ -31,7 +31,6 @@
 import java.lang.invoke.MethodHandle;
 import jdk.internal.dynalink.CallSiteDescriptor;
 import jdk.internal.dynalink.linker.GuardedInvocation;
-import jdk.nashorn.internal.codegen.ObjectClassGenerator;
 import jdk.nashorn.internal.lookup.Lookup;
 import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
 import jdk.nashorn.internal.runtime.linker.NashornGuards;
@@ -104,21 +103,9 @@
          * @return the composed guarded invocation that represents the dynamic setter method for the property.
          */
         GuardedInvocation createGuardedInvocation() {
-            return new GuardedInvocation(methodHandle, getGuard());
-        }
-
-        private MethodHandle getGuard() {
-            return needsNoGuard() ? null : NashornGuards.getMapGuard(getMap());
+            return new GuardedInvocation(methodHandle, NashornGuards.getGuard(sobj, property, desc));
         }
 
-        private boolean needsNoGuard() {
-            return NashornCallSiteDescriptor.isFastScope(desc) &&
-                    (ObjectClassGenerator.OBJECT_FIELDS_ONLY || isPropertyTypeStable());
-        }
-
-        private boolean isPropertyTypeStable() {
-            return property == null || !property.canChangeType();
-        }
     }
 
     private SetMethod createSetMethod() {
@@ -153,10 +140,7 @@
 
         final MethodHandle boundHandle;
         if (!property.hasSetterFunction(find.getOwner()) && find.isInherited()) {
-            // Bind or add prototype filter depending on whether this is a scope object.
-            boundHandle = sobj.isScope() ?
-                    ScriptObject.addProtoFilter(methodHandle, find.getProtoChainLength()):
-                    ScriptObject.bindTo(methodHandle, find.getOwner());
+            boundHandle = ScriptObject.addProtoFilter(methodHandle, find.getProtoChainLength());
         } else {
             boundHandle = methodHandle;
         }
@@ -164,8 +148,8 @@
     }
 
     private SetMethod createGlobalPropertySetter() {
-        final ScriptObject global = Context.getGlobalTrusted();
-        return new SetMethod(ScriptObject.bindTo(global.addSpill(getName()), global), null);
+        final ScriptObject global = Context.getGlobal();
+        return new SetMethod(MH.filterArguments(global.addSpill(getName()), 0, ScriptObject.GLOBALFILTER), null);
     }
 
     private SetMethod createNewPropertySetter() {
--- a/nashorn/src/jdk/nashorn/internal/runtime/UserAccessorProperty.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/UserAccessorProperty.java	Wed Jul 05 19:33:51 2017 +0200
@@ -34,6 +34,7 @@
 import jdk.nashorn.internal.runtime.linker.Bootstrap;
 
 import static jdk.nashorn.internal.codegen.CompilerConstants.staticCall;
+import jdk.nashorn.internal.objects.Global;
 import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
 import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
 
@@ -73,7 +74,7 @@
 
     private static MethodHandle getINVOKE_UA_GETTER() {
 
-        return ((GlobalObject)Context.getGlobal()).getDynamicInvoker(INVOKE_UA_GETTER,
+        return Context.getGlobal().getDynamicInvoker(INVOKE_UA_GETTER,
                 new Callable<MethodHandle>() {
                     @Override
                     public MethodHandle call() {
@@ -86,7 +87,7 @@
     /** Dynamic invoker for setter */
     private static Object INVOKE_UA_SETTER = new Object();
     private static MethodHandle getINVOKE_UA_SETTER() {
-        return ((GlobalObject)Context.getGlobal()).getDynamicInvoker(INVOKE_UA_SETTER,
+        return Context.getGlobal().getDynamicInvoker(INVOKE_UA_SETTER,
                 new Callable<MethodHandle>() {
                     @Override
                     public MethodHandle call() {
--- a/nashorn/src/jdk/nashorn/internal/runtime/WithObject.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/WithObject.java	Wed Jul 05 19:33:51 2017 +0200
@@ -88,6 +88,11 @@
 
     @Override
     public GuardedInvocation lookup(final CallSiteDescriptor desc, final LinkRequest request) {
+        if (request.isCallSiteUnstable()) {
+            // Fall back to megamorphic invocation which performs a complete lookup each time without further relinking.
+            return super.lookup(desc, request);
+        }
+
         // With scopes can never be observed outside of Nashorn code, so all call sites that can address it will of
         // necessity have a Nashorn descriptor - it is safe to cast.
         final NashornCallSiteDescriptor ndesc = (NashornCallSiteDescriptor)desc;
@@ -265,7 +270,7 @@
     }
 
     private static MethodHandle filter(final MethodHandle mh, final MethodHandle filter) {
-        return MH.filterArguments(mh, 0, filter);
+        return MH.filterArguments(mh, 0, filter.asType(filter.type().changeReturnType(mh.type().parameterType(0))));
     }
 
     /**
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ArrayData.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ArrayData.java	Wed Jul 05 19:33:51 2017 +0200
@@ -27,7 +27,7 @@
 
 import java.lang.invoke.MethodHandle;
 import java.nio.ByteBuffer;
-import jdk.nashorn.internal.runtime.GlobalObject;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.JSType;
 import jdk.nashorn.internal.runtime.PropertyDescriptor;
 
@@ -399,7 +399,7 @@
      *
      * @return property descriptor for element
      */
-    public PropertyDescriptor getDescriptor(final GlobalObject global, final int index) {
+    public PropertyDescriptor getDescriptor(final Global global, final int index) {
         return global.newDataDescriptor(getObject(index), true, true, true);
     }
 
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ByteBufferArrayData.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ByteBufferArrayData.java	Wed Jul 05 19:33:51 2017 +0200
@@ -27,7 +27,7 @@
 import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
 
 import java.nio.ByteBuffer;
-import jdk.nashorn.internal.runtime.GlobalObject;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.PropertyDescriptor;
 import jdk.nashorn.internal.runtime.ScriptRuntime;
 
@@ -60,7 +60,8 @@
      *
      * @return property descriptor for element
      */
-    public PropertyDescriptor getDescriptor(final GlobalObject global, final int index) {
+    @Override
+    public PropertyDescriptor getDescriptor(final Global global, final int index) {
         // make the index properties not configurable
         return global.newDataDescriptor(getObject(index), false, true, true);
     }
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/FrozenArrayFilter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/FrozenArrayFilter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -25,9 +25,9 @@
 
 package jdk.nashorn.internal.runtime.arrays;
 
+import jdk.nashorn.internal.objects.Global;
 import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
 
-import jdk.nashorn.internal.runtime.GlobalObject;
 import jdk.nashorn.internal.runtime.PropertyDescriptor;
 
 /**
@@ -44,7 +44,7 @@
     }
 
     @Override
-    public PropertyDescriptor getDescriptor(final GlobalObject global, final int index) {
+    public PropertyDescriptor getDescriptor(final Global global, final int index) {
         return global.newDataDescriptor(getObject(index), false, true, false);
     }
 
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/SealedArrayFilter.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/SealedArrayFilter.java	Wed Jul 05 19:33:51 2017 +0200
@@ -25,9 +25,9 @@
 
 package jdk.nashorn.internal.runtime.arrays;
 
+import jdk.nashorn.internal.objects.Global;
 import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
 
-import jdk.nashorn.internal.runtime.GlobalObject;
 import jdk.nashorn.internal.runtime.PropertyDescriptor;
 
 /**
@@ -62,7 +62,7 @@
     }
 
     @Override
-    public PropertyDescriptor getDescriptor(final GlobalObject global, final int index) {
+    public PropertyDescriptor getDescriptor(final Global global, final int index) {
         return global.newDataDescriptor(getObject(index), false, true, true);
     }
 }
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java	Wed Jul 05 19:33:51 2017 +0200
@@ -64,6 +64,7 @@
 import jdk.internal.org.objectweb.asm.Opcodes;
 import jdk.internal.org.objectweb.asm.Type;
 import jdk.internal.org.objectweb.asm.commons.InstructionAdapter;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.Context;
 import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptObject;
@@ -134,6 +135,7 @@
     static final Type CONTEXT_TYPE       = Type.getType(Context.class);
     static final Type OBJECT_TYPE        = Type.getType(Object.class);
     static final Type SCRIPT_OBJECT_TYPE = Type.getType(ScriptObject.class);
+    static final Type GLOBAL_TYPE        = Type.getType(Global.class);
 
     static final String CONTEXT_TYPE_NAME = CONTEXT_TYPE.getInternalName();
     static final String OBJECT_TYPE_NAME  = OBJECT_TYPE.getInternalName();
@@ -143,8 +145,10 @@
     static final String GLOBAL_FIELD_NAME = "global";
 
     static final String SCRIPT_OBJECT_TYPE_DESCRIPTOR = SCRIPT_OBJECT_TYPE.getDescriptor();
+    static final String GLOBAL_TYPE_DESCRIPTOR = GLOBAL_TYPE.getDescriptor();
 
-    static final String SET_GLOBAL_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.VOID_TYPE, SCRIPT_OBJECT_TYPE);
+
+    static final String SET_GLOBAL_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.VOID_TYPE, GLOBAL_TYPE);
     static final String VOID_NOARG_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.VOID_TYPE);
 
     private static final Type SCRIPT_FUNCTION_TYPE = Type.getType(ScriptFunction.class);
@@ -167,7 +171,7 @@
     private static final String UNSUPPORTED_OPERATION_TYPE_NAME = UNSUPPORTED_OPERATION_TYPE.getInternalName();
 
     private static final String METHOD_HANDLE_TYPE_DESCRIPTOR = METHOD_HANDLE_TYPE.getDescriptor();
-    private static final String GET_GLOBAL_METHOD_DESCRIPTOR = Type.getMethodDescriptor(SCRIPT_OBJECT_TYPE);
+    private static final String GET_GLOBAL_METHOD_DESCRIPTOR = Type.getMethodDescriptor(GLOBAL_TYPE);
     private static final String GET_CLASS_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.getType(Class.class));
 
     // Package used when the adapter can't be defined in the adaptee's package (either because it's sealed, or because
@@ -259,7 +263,7 @@
     }
 
     private void generateGlobalFields() {
-        cw.visitField(ACC_PRIVATE | ACC_FINAL | (classOverride ? ACC_STATIC : 0), GLOBAL_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR, null, null).visitEnd();
+        cw.visitField(ACC_PRIVATE | ACC_FINAL | (classOverride ? ACC_STATIC : 0), GLOBAL_FIELD_NAME, GLOBAL_TYPE_DESCRIPTOR, null, null).visitEnd();
         usedFieldNames.add(GLOBAL_FIELD_NAME);
     }
 
@@ -363,7 +367,7 @@
         }
         // Assign "global = Context.getGlobal()"
         invokeGetGlobalWithNullCheck(mv);
-        mv.putstatic(generatedClassName, GLOBAL_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
+        mv.putstatic(generatedClassName, GLOBAL_FIELD_NAME, GLOBAL_TYPE_DESCRIPTOR);
 
         endInitMethod(mv);
     }
@@ -508,7 +512,7 @@
         // Assign "this.global = Context.getGlobal()"
         mv.visitVarInsn(ALOAD, 0);
         invokeGetGlobalWithNullCheck(mv);
-        mv.putfield(generatedClassName, GLOBAL_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
+        mv.putfield(generatedClassName, GLOBAL_FIELD_NAME, GLOBAL_TYPE_DESCRIPTOR);
 
         endInitMethod(mv);
     }
@@ -652,10 +656,10 @@
         // Load the creatingGlobal object
         if(classOverride) {
             // If class handle is defined, load the static defining global
-            mv.getstatic(generatedClassName, GLOBAL_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
+            mv.getstatic(generatedClassName, GLOBAL_FIELD_NAME, GLOBAL_TYPE_DESCRIPTOR);
         } else {
             mv.visitVarInsn(ALOAD, 0);
-            mv.getfield(generatedClassName, GLOBAL_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
+            mv.getfield(generatedClassName, GLOBAL_FIELD_NAME, GLOBAL_TYPE_DESCRIPTOR);
         }
         // stack: [creatingGlobal, handle]
         final Label setupGlobal = new Label();
@@ -674,7 +678,7 @@
         // stack: [creatingGlobal, creatingGlobal, handle]
 
         // Emit code for switching to the creating global
-        // ScriptObject currentGlobal = Context.getGlobal();
+        // Global currentGlobal = Context.getGlobal();
         invokeGetGlobal(mv);
         mv.dup();
 
@@ -744,7 +748,7 @@
         final Label methodEnd = new Label();
         mv.visitLabel(methodEnd);
 
-        mv.visitLocalVariable("currentGlobal", SCRIPT_OBJECT_TYPE_DESCRIPTOR, null, setupGlobal, methodEnd, currentGlobalVar);
+        mv.visitLocalVariable("currentGlobal", GLOBAL_TYPE_DESCRIPTOR, null, setupGlobal, methodEnd, currentGlobalVar);
         mv.visitLocalVariable("globalsDiffer", Type.INT_TYPE.getDescriptor(), null, setupGlobal, methodEnd, globalsDifferVar);
 
         if(throwableDeclared) {
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java	Wed Jul 05 19:33:51 2017 +0200
@@ -48,7 +48,6 @@
 import java.util.concurrent.ConcurrentHashMap;
 import jdk.internal.dynalink.beans.StaticClass;
 import jdk.internal.dynalink.support.LinkRequestImpl;
-import jdk.nashorn.internal.objects.NativeJava;
 import jdk.nashorn.internal.runtime.Context;
 import jdk.nashorn.internal.runtime.ECMAException;
 import jdk.nashorn.internal.runtime.ScriptFunction;
@@ -68,8 +67,8 @@
  * generate the adapter class itself; see its documentation for details about the generated class.
  * </p><p>
  * You normally don't use this class directly, but rather either create adapters from script using
- * {@link NativeJava#extend(Object, Object...)}, using the {@code new} operator on abstract classes and interfaces (see
- * {@link NativeJava#type(Object, Object)}), or implicitly when passing script functions to Java methods expecting SAM
+ * {@link jdk.nashorn.internal.objects.NativeJava#extend(Object, Object...)}, using the {@code new} operator on abstract classes and interfaces (see
+ * {@link jdk.nashorn.internal.objects.NativeJava#type(Object, Object)}), or implicitly when passing script functions to Java methods expecting SAM
  * types.
  * </p>
  */
@@ -337,6 +336,7 @@
     private static ProtectionDomain createMinimalPermissionDomain() {
         // Generated classes need to have at least the permission to access Nashorn runtime and runtime.linker packages.
         final Permissions permissions = new Permissions();
+        permissions.add(new RuntimePermission("accessClassInPackage.jdk.nashorn.internal.objects"));
         permissions.add(new RuntimePermission("accessClassInPackage.jdk.nashorn.internal.runtime"));
         permissions.add(new RuntimePermission("accessClassInPackage.jdk.nashorn.internal.runtime.linker"));
         return new ProtectionDomain(new CodeSource(null, (CodeSigner[])null), permissions);
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornGuards.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornGuards.java	Wed Jul 05 19:33:51 2017 +0200
@@ -29,6 +29,11 @@
 
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
+import java.lang.ref.WeakReference;
+import jdk.internal.dynalink.CallSiteDescriptor;
+import jdk.nashorn.internal.codegen.ObjectClassGenerator;
+import jdk.nashorn.internal.objects.Global;
+import jdk.nashorn.internal.runtime.Property;
 import jdk.nashorn.internal.runtime.PropertyMap;
 import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptObject;
@@ -40,6 +45,7 @@
     private static final MethodHandle IS_SCRIPTOBJECT   = findOwnMH("isScriptObject", boolean.class, Object.class);
     private static final MethodHandle IS_SCRIPTFUNCTION = findOwnMH("isScriptFunction", boolean.class, Object.class);
     private static final MethodHandle IS_MAP            = findOwnMH("isMap", boolean.class, Object.class, PropertyMap.class);
+    private static final MethodHandle SAME_OBJECT       = findOwnMH("sameObject", boolean.class, Object.class, WeakReference.class);
     private static final MethodHandle IS_INSTANCEOF_2   = findOwnMH("isInstanceOf2", boolean.class, Object.class, Class.class, Class.class);
 
     // don't create me!
@@ -75,6 +81,55 @@
     }
 
     /**
+     * Determine whether the given callsite needs a guard.
+     * @param property the property, or null
+     * @param desc the callsite descriptor
+     * @return true if a guard should be used for this callsite
+     */
+    static boolean needsGuard(final Property property, final CallSiteDescriptor desc) {
+        return property == null || property.isConfigurable()
+                || property.isBound() || !ObjectClassGenerator.OBJECT_FIELDS_ONLY
+                || !NashornCallSiteDescriptor.isFastScope(desc) || property.canChangeType();
+    }
+
+    /**
+     * Get the guard for a property access. This returns an identity guard for non-configurable global properties
+     * and a map guard for everything else.
+     *
+     * @param sobj the first object in the prototype chain
+     * @param property the property
+     * @param desc the callsite descriptor
+     * @return method handle for guard
+     */
+    public static MethodHandle getGuard(final ScriptObject sobj, final Property property, final CallSiteDescriptor desc) {
+        if (!needsGuard(property, desc)) {
+            return null;
+        }
+        if (NashornCallSiteDescriptor.isScope(desc)) {
+            if (property != null && property.isBound()) {
+                // This is a declared top level variables in main script or eval, use identity guard.
+                return getIdentityGuard(sobj);
+            }
+            if (!(sobj instanceof Global) && (property == null || property.isConfigurable())) {
+                // Undeclared variables in nested evals need stronger guards
+                return combineGuards(getIdentityGuard(sobj), getMapGuard(sobj.getMap()));
+            }
+        }
+        return getMapGuard(sobj.getMap());
+    }
+
+
+    /**
+     * Get a guard that checks referential identity of the current object.
+     *
+     * @param sobj the self object
+     * @return true if same self object instance
+     */
+    public static MethodHandle getIdentityGuard(final ScriptObject sobj) {
+        return MH.insertArguments(SAME_OBJECT, 1, new WeakReference<>(sobj));
+    }
+
+    /**
      * Get a guard that checks if in item is an instance of either of two classes.
      *
      * @param class1 the first class
@@ -112,6 +167,11 @@
     }
 
     @SuppressWarnings("unused")
+    private static boolean sameObject(final Object self, final WeakReference<ScriptObject> ref) {
+        return self == ref.get();
+    }
+
+    @SuppressWarnings("unused")
     private static boolean isInstanceOf2(final Object self, final Class<?> class1, final Class<?> class2) {
         return class1.isInstance(self) || class2.isInstance(self);
     }
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornPrimitiveLinker.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornPrimitiveLinker.java	Wed Jul 05 19:33:51 2017 +0200
@@ -37,9 +37,9 @@
 import jdk.internal.dynalink.linker.LinkerServices;
 import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker;
 import jdk.internal.dynalink.support.TypeUtilities;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.ConsString;
 import jdk.nashorn.internal.runtime.Context;
-import jdk.nashorn.internal.runtime.GlobalObject;
 
 /**
  * Internal linker for String, Boolean, and Number objects, only ever used by Nashorn engine and not exposed to other
@@ -62,7 +62,7 @@
         final LinkRequest request = origRequest.withoutRuntimeContext(); // Nashorn has no runtime context
 
         final Object self = request.getReceiver();
-        final GlobalObject global = (GlobalObject) Context.getGlobal();
+        final Global global = Context.getGlobal();
         final NashornCallSiteDescriptor desc = (NashornCallSiteDescriptor) request.getCallSiteDescriptor();
 
         return Bootstrap.asType(global.primitiveLookup(request, self), linkerServices, desc);
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/PrimitiveLookup.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/PrimitiveLookup.java	Wed Jul 05 19:33:51 2017 +0200
@@ -35,6 +35,7 @@
 import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
 import jdk.internal.dynalink.support.Guards;
 import jdk.nashorn.internal.lookup.Lookup;
+import jdk.nashorn.internal.runtime.FindProperty;
 import jdk.nashorn.internal.runtime.ScriptObject;
 
 /**
@@ -61,8 +62,9 @@
      * type {@code receiverClass}.
      */
     public static GuardedInvocation lookupPrimitive(final LinkRequest request, final Class<?> receiverClass,
-                                                    final ScriptObject wrappedReceiver, final MethodHandle wrapFilter) {
-        return lookupPrimitive(request, Guards.getInstanceOfGuard(receiverClass), wrappedReceiver, wrapFilter);
+                                                    final ScriptObject wrappedReceiver, final MethodHandle wrapFilter,
+                                                    final MethodHandle protoFilter) {
+        return lookupPrimitive(request, Guards.getInstanceOfGuard(receiverClass), wrappedReceiver, wrapFilter, protoFilter);
     }
 
     /**
@@ -79,7 +81,8 @@
      * type (that is implied by both {@code guard} and {@code wrappedReceiver}).
      */
     public static GuardedInvocation lookupPrimitive(final LinkRequest request, final MethodHandle guard,
-                                                    final ScriptObject wrappedReceiver, final MethodHandle wrapFilter) {
+                                                    final ScriptObject wrappedReceiver, final MethodHandle wrapFilter,
+                                                    final MethodHandle protoFilter) {
         final CallSiteDescriptor desc = request.getCallSiteDescriptor();
         final String operator = CallSiteDescriptorFactory.tokenizeOperators(desc).get(0);
         if ("setProp".equals(operator) || "setElem".equals(operator)) {
@@ -93,9 +96,23 @@
 
         if(desc.getNameTokenCount() > 2) {
             final String name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
-            if(wrappedReceiver.findProperty(name, true) == null) {
+            final FindProperty find = wrappedReceiver.findProperty(name, true);
+            if(find == null) {
                 // Give up early, give chance to BeanLinker and NashornBottomLinker to deal with it.
                 return null;
+            } else if (find.isInherited() && !find.getProperty().hasGetterFunction(find.getOwner())) {
+                // If property is found in the prototype object bind the method handle directly to
+                // the proto filter instead of going through wrapper instantiation below.
+                final ScriptObject proto = wrappedReceiver.getProto();
+                final GuardedInvocation link = proto.lookup(desc, request);
+
+                if (link != null) {
+                    final MethodHandle invocation = link.getInvocation();
+                    final MethodHandle adaptedInvocation = MH.asType(invocation, invocation.type().changeParameterType(0, Object.class));
+                    final MethodHandle method = MH.filterArguments(adaptedInvocation, 0, protoFilter);
+                    final MethodHandle protoGuard = MH.filterArguments(link.getGuard(), 0, protoFilter);
+                    return new GuardedInvocation(method, NashornGuards.combineGuards(guard, protoGuard));
+                }
             }
         }
         final GuardedInvocation link = wrappedReceiver.lookup(desc, request);
--- a/nashorn/src/jdk/nashorn/internal/runtime/resources/Messages.properties	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/internal/runtime/resources/Messages.properties	Wed Jul 05 19:33:51 2017 +0200
@@ -79,6 +79,7 @@
 type.error.not.a.constructor={0} is not a constructor function
 type.error.not.a.file={0} is not a File
 type.error.not.a.bytebuffer={0} is not a java.nio.ByteBuffer
+type.error.not.an.arraybuffer.in.dataview=First arg to DataView constructor must be an ArrayBuffer
 
 # operations not permitted on undefined
 type.error.cant.call.undefined=Cannot call undefined
@@ -137,6 +138,9 @@
 type.error.method.not.constructor=Java method {0} can't be used as a constructor.
 type.error.env.not.object=$ENV must be an Object.
 type.error.unsupported.java.to.type=Unsupported Java.to target type {0}.
+
+range.error.dataview.constructor.offset=Wrong offset or length in DataView constructor
+range.error.dataview.offset=Offset is outside the bounds of the DataView
 range.error.inappropriate.array.length=inappropriate array length: {0}
 range.error.inappropriate.array.buffer.length=inappropriate array buffer length: {0}
 range.error.invalid.fraction.digits=fractionDigits argument to {0} must be in [0, 20]
--- a/nashorn/src/jdk/nashorn/tools/Shell.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/src/jdk/nashorn/tools/Shell.java	Wed Jul 05 19:33:51 2017 +0200
@@ -42,6 +42,7 @@
 import jdk.nashorn.internal.ir.FunctionNode;
 import jdk.nashorn.internal.ir.debug.ASTWriter;
 import jdk.nashorn.internal.ir.debug.PrintVisitor;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.parser.Parser;
 import jdk.nashorn.internal.runtime.Context;
 import jdk.nashorn.internal.runtime.ErrorManager;
@@ -148,7 +149,7 @@
             return COMMANDLINE_ERROR;
         }
 
-        final ScriptObject global = context.createGlobal();
+        final Global global = context.createGlobal();
         final ScriptEnvironment env = context.getEnv();
         final List<String> files = env.getFiles();
         if (files.isEmpty()) {
@@ -231,8 +232,8 @@
      * @return error code
      * @throws IOException when any script file read results in I/O error
      */
-    private static int compileScripts(final Context context, final ScriptObject global, final List<String> files) throws IOException {
-        final ScriptObject oldGlobal = Context.getGlobal();
+    private static int compileScripts(final Context context, final Global global, final List<String> files) throws IOException {
+        final Global oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
         final ScriptEnvironment env = context.getEnv();
         try {
@@ -281,8 +282,8 @@
      * @return error code
      * @throws IOException when any script file read results in I/O error
      */
-    private int runScripts(final Context context, final ScriptObject global, final List<String> files) throws IOException {
-        final ScriptObject oldGlobal = Context.getGlobal();
+    private int runScripts(final Context context, final Global global, final List<String> files) throws IOException {
+        final Global oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
         try {
             if (globalChanged) {
@@ -339,8 +340,8 @@
      * @return error code
      * @throws IOException when any script file read results in I/O error
      */
-    private static int runFXScripts(final Context context, final ScriptObject global, final List<String> files) throws IOException {
-        final ScriptObject oldGlobal = Context.getGlobal();
+    private static int runFXScripts(final Context context, final Global global, final List<String> files) throws IOException {
+        final Global oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
         try {
             if (globalChanged) {
@@ -389,11 +390,11 @@
      * @return return code
      */
     @SuppressWarnings("resource")
-    private static int readEvalPrint(final Context context, final ScriptObject global) {
+    private static int readEvalPrint(final Context context, final Global global) {
         final String prompt = bundle.getString("shell.prompt");
         final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
         final PrintWriter err = context.getErr();
-        final ScriptObject oldGlobal = Context.getGlobal();
+        final Global oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
         final ScriptEnvironment env = context.getEnv();
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/JDK-8034055.js	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.
+ */
+
+/**
+ * JDK-8034055: delete on global object not properly guarded
+ *
+ * @test
+ * @run
+ */
+
+
+var global = this;
+var x;
+
+function test(defineGlobals) {
+    if (defineGlobals) {
+        global.x = 1;
+        global.y = 2;
+    }
+    try {
+        print(x);
+        print(y);
+    } catch (e) {
+        print(e);
+    } finally {
+        print(delete global.x);
+        print(delete global.y);
+    }
+}
+
+// Repeatedly set and delete global variables
+test(true);
+test(false);
+test(true);
+test(false);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/JDK-8034055.js.EXPECTED	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,16 @@
+1
+2
+false
+true
+1
+ReferenceError: "y" is not defined
+false
+true
+1
+2
+false
+true
+1
+ReferenceError: "y" is not defined
+false
+true
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/dataview_endian.js	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.
+ */
+
+/**
+ * JDK-8015958: DataView constructor is not defined
+ *
+ * @test
+ * @run
+ */
+
+// set/get endianess checks
+
+var buffer = new ArrayBuffer(4);
+var dv = new DataView(buffer);
+
+// write (default) big endian, read big/little endian
+dv.setUint16(0, 0xABCD);
+Assert.assertEquals(dv.getUint16(0), 0xABCD);
+Assert.assertEquals(dv.getUint16(0, false), 0xABCD);
+Assert.assertEquals(dv.getUint16(0, true), 0xCDAB);
+
+// write little endian, read big/little endian
+dv.setUint16(0, 0xABCD, true);
+Assert.assertEquals(dv.getUint16(0), 0xCDAB);
+Assert.assertEquals(dv.getUint16(0, false), 0xCDAB);
+Assert.assertEquals(dv.getUint16(0, true), 0xABCD);
+
+// write explicit big endian, read big/little endian
+dv.setUint16(0, 0xABCD, false);
+Assert.assertEquals(dv.getUint16(0), 0xABCD);
+Assert.assertEquals(dv.getUint16(0, false), 0xABCD);
+Assert.assertEquals(dv.getUint16(0, true), 0xCDAB);
+
+// write (default) big endian, read big/little endian
+dv.setUint32(0, 0xABCDEF89);
+Assert.assertEquals(dv.getUint32(0), 0xABCDEF89);
+Assert.assertEquals(dv.getUint32(0, false), 0xABCDEF89);
+Assert.assertEquals(dv.getUint32(0, true), 0x89EFCDAB);
+
+// write little endian, read big/little endian
+dv.setUint32(0, 0xABCDEF89, true);
+Assert.assertEquals(dv.getUint32(0), 0x89EFCDAB);
+Assert.assertEquals(dv.getUint32(0, false), 0x89EFCDAB);
+Assert.assertEquals(dv.getUint32(0, true), 0xABCDEF89);
+
+// write explicit big endian, read big/little endian
+dv.setUint32(0, 0xABCDEF89, false);
+Assert.assertEquals(dv.getUint32(0), 0xABCDEF89);
+Assert.assertEquals(dv.getUint32(0, false), 0xABCDEF89);
+Assert.assertEquals(dv.getUint32(0, true), 0x89EFCDAB);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/dataview_getset.js	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.
+ */
+
+/**
+ * JDK-8015958: DataView constructor is not defined
+ *
+ * @test
+ * @run
+ */
+
+// checking get/set of values of various types
+// Also basic endianess check.
+
+var Float = Java.type("java.lang.Float");
+var Double = Java.type("java.lang.Double");
+
+var DOUBLE_MIN = Double.MIN_VALUE;
+var DOUBLE_MIN_NORMAL = Double.MIN_NORMAL;
+var FLOAT_MIN = Float.MIN_VALUE;
+var FLOAT_MIN_NORMAL = Float.MIN_NORMAL;
+
+var buffer = new ArrayBuffer(12);
+var dv = new DataView(buffer);
+
+dv.setInt8(1, 123);
+Assert.assertEquals(dv.getInt8(1), 123);
+dv.setInt8(1, 123, true);
+Assert.assertEquals(dv.getInt8(1, true), 123);
+
+dv.setUint8(1, 255);
+Assert.assertEquals(dv.getUint8(1), 255);
+dv.setUint8(1, 255, true);
+Assert.assertEquals(dv.getUint8(1, true), 255);
+
+dv.setInt16(1, 1234);
+Assert.assertEquals(dv.getInt16(1), 1234);
+dv.setInt16(1, 1234, true);
+Assert.assertEquals(dv.getInt16(1, true), 1234);
+
+dv.setUint16(1, 65535);
+Assert.assertEquals(dv.getUint16(1), 65535);
+dv.setUint16(1, 65535, true);
+Assert.assertEquals(dv.getUint16(1, true), 65535);
+
+dv.setInt32(1, 1234);
+Assert.assertEquals(dv.getInt32(1), 1234);
+dv.setInt32(1, 1234, true);
+Assert.assertEquals(dv.getInt32(1, true), 1234);
+
+dv.setUint32(1, 4294967295);
+Assert.assertEquals(dv.getUint32(1), 4294967295);
+dv.setUint32(1, 4294967295, true);
+Assert.assertEquals(dv.getUint32(1, true), 4294967295);
+
+dv.setFloat64(1, Math.PI);
+Assert.assertEquals(dv.getFloat64(1), Math.PI, DOUBLE_MIN);
+dv.setFloat64(1, Math.PI, true);
+Assert.assertEquals(dv.getFloat64(1, true), Math.PI, DOUBLE_MIN);
+
+dv.setFloat64(1, DOUBLE_MIN_NORMAL);
+Assert.assertEquals(dv.getFloat64(1), DOUBLE_MIN_NORMAL, DOUBLE_MIN);
+dv.setFloat64(1, DOUBLE_MIN_NORMAL, true);
+Assert.assertEquals(dv.getFloat64(1, true), DOUBLE_MIN_NORMAL, DOUBLE_MIN);
+
+dv.setFloat32(1, 1.414);
+Assert["assertEquals(float, float, float)"](dv.getFloat32(1), 1.414, FLOAT_MIN);
+dv.setFloat32(1, 1.414, true);
+Assert["assertEquals(float, float, float)"](dv.getFloat32(1, true), 1.414, FLOAT_MIN);
+
+dv.setFloat32(1, FLOAT_MIN_NORMAL);
+Assert["assertEquals(float, float, float)"](dv.getFloat32(1), FLOAT_MIN_NORMAL, FLOAT_MIN);
+dv.setFloat32(1, FLOAT_MIN_NORMAL, true);
+Assert["assertEquals(float, float, float)"](dv.getFloat32(1, true), FLOAT_MIN_NORMAL, FLOAT_MIN);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/dataview_new.js	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.
+ */
+
+/**
+ * JDK-8015958: DataView constructor is not defined
+ *
+ * @test
+ * @run
+ */
+
+// basic DataView constructor checks.
+
+// check ArrayBufferView property values of DataView instance
+function check(dv, buf, offset, length) {
+    if (dv.buffer !== buf) {
+        fail("DataView.buffer is wrong");
+    }
+
+    if (dv.byteOffset != offset) {
+        fail("DataView.byteOffset = " + dv.byteOffset + ", expected " + offset);
+    }
+
+    if (dv.byteLength != length) {
+        fail("DataView.byteLength = " + dv.byteLength + ", expected " + length);
+    }
+}
+
+var buffer = new ArrayBuffer(12);
+check(new DataView(buffer), buffer, 0, 12);
+check(new DataView(buffer, 2), buffer, 2, 10);
+check(new DataView(buffer, 4, 8), buffer, 4, 8);
+
+// make sure expected error is thrown
+function checkError(callback, ErrorType) {
+    try {
+        callback();
+        fail("Should have thrown " + ErrorType.name);
+    } catch (e) {
+        if (! (e instanceof ErrorType)) {
+            fail("Expected " + ErrorType.name + " got " + e);
+        }
+    }
+}
+
+// non ArrayBuffer as first arg
+checkError(function() { new DataView(344) }, TypeError);
+
+// illegal offset/length values
+checkError(function() { new DataView(buffer, -1) }, RangeError);
+checkError(function() { new DataView(buffer, 15) }, RangeError);
+checkError(function() { new DataView(buffer, 1, 32) }, RangeError);
--- a/nashorn/test/src/jdk/nashorn/api/scripting/ScopeTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/test/src/jdk/nashorn/api/scripting/ScopeTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -245,4 +245,320 @@
         sb.put("x", "newX");
         assertTrue(e.eval("x", ctx).equals("newX"));
     }
+
+    /**
+     * Test multi-threaded access to defined global variables for shared script classes with multiple globals.
+     */
+    @Test
+    public static void multiThreadedVarTest() throws ScriptException, InterruptedException {
+        final ScriptEngineManager m = new ScriptEngineManager();
+        final ScriptEngine e = m.getEngineByName("nashorn");
+        final Bindings b = e.createBindings();
+        final ScriptContext origContext = e.getContext();
+        final ScriptContext newCtxt = new SimpleScriptContext();
+        newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
+        final String sharedScript = "foo";
+
+        assertEquals(e.eval("var foo = 'original context';", origContext), null);
+        assertEquals(e.eval("var foo = 'new context';", newCtxt), null);
+
+        final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
+        final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "new context", 1000));
+        t1.start();
+        t2.start();
+        t1.join();
+        t2.join();
+
+        assertEquals(e.eval("var foo = 'newer context';", newCtxt), null);
+        final Thread t3 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
+        final Thread t4 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "newer context", 1000));
+
+        t3.start();
+        t4.start();
+        t3.join();
+        t4.join();
+
+        assertEquals(e.eval(sharedScript), "original context");
+        assertEquals(e.eval(sharedScript, newCtxt), "newer context");
+    }
+
+    /**
+     * Test multi-threaded access to undefined global variables for shared script classes with multiple globals.
+     */
+    @Test
+    public static void multiThreadedGlobalTest() throws ScriptException, InterruptedException {
+        final ScriptEngineManager m = new ScriptEngineManager();
+        final ScriptEngine e = m.getEngineByName("nashorn");
+        final Bindings b = e.createBindings();
+        final ScriptContext origContext = e.getContext();
+        final ScriptContext newCtxt = new SimpleScriptContext();
+        newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
+
+        assertEquals(e.eval("foo = 'original context';", origContext), "original context");
+        assertEquals(e.eval("foo = 'new context';", newCtxt), "new context");
+        final String sharedScript = "foo";
+
+        final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
+        final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "new context", 1000));
+        t1.start();
+        t2.start();
+        t1.join();
+        t2.join();
+
+        Object obj3 = e.eval("delete foo; foo = 'newer context';", newCtxt);
+        assertEquals(obj3, "newer context");
+        final Thread t3 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
+        final Thread t4 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "newer context", 1000));
+
+        t3.start();
+        t4.start();
+        t3.join();
+        t4.join();
+
+        Assert.assertEquals(e.eval(sharedScript), "original context");
+        Assert.assertEquals(e.eval(sharedScript, newCtxt), "newer context");
+    }
+
+    /**
+     * Test multi-threaded access using the postfix ++ operator for shared script classes with multiple globals.
+     */
+    @Test
+    public static void multiThreadedIncTest() throws ScriptException, InterruptedException {
+        final ScriptEngineManager m = new ScriptEngineManager();
+        final ScriptEngine e = m.getEngineByName("nashorn");
+        final Bindings b = e.createBindings();
+        final ScriptContext origContext = e.getContext();
+        final ScriptContext newCtxt = new SimpleScriptContext();
+        newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
+
+        assertEquals(e.eval("var x = 0;", origContext), null);
+        assertEquals(e.eval("var x = 2;", newCtxt), null);
+        final String sharedScript = "x++;";
+
+        final Thread t1 = new Thread(new Runnable() {
+            @Override
+            public void run() {
+                try {
+                    for (int i = 0; i < 1000; i++) {
+                        assertEquals(e.eval(sharedScript, origContext), (double)i);
+                    }
+                } catch (ScriptException se) {
+                    fail(se.toString());
+                }
+            }
+        });
+        final Thread t2 = new Thread(new Runnable() {
+            @Override
+            public void run() {
+                try {
+                    for (int i = 2; i < 1000; i++) {
+                        assertEquals(e.eval(sharedScript, newCtxt), (double)i);
+                    }
+                } catch (ScriptException se) {
+                    fail(se.toString());
+                }
+            }
+        });
+        t1.start();
+        t2.start();
+        t1.join();
+        t2.join();
+    }
+
+    /**
+     * Test multi-threaded access to primitive prototype properties for shared script classes with multiple globals.
+     */
+    @Test
+    public static void multiThreadedPrimitiveTest() throws ScriptException, InterruptedException {
+        final ScriptEngineManager m = new ScriptEngineManager();
+        final ScriptEngine e = m.getEngineByName("nashorn");
+        final Bindings b = e.createBindings();
+        final ScriptContext origContext = e.getContext();
+        final ScriptContext newCtxt = new SimpleScriptContext();
+        newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
+
+        Object obj1 = e.eval("String.prototype.foo = 'original context';", origContext);
+        Object obj2 = e.eval("String.prototype.foo = 'new context';", newCtxt);
+        assertEquals(obj1, "original context");
+        assertEquals(obj2, "new context");
+        final String sharedScript = "''.foo";
+
+        final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
+        final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "new context", 1000));
+        t1.start();
+        t2.start();
+        t1.join();
+        t2.join();
+
+        Object obj3 = e.eval("delete String.prototype.foo; Object.prototype.foo = 'newer context';", newCtxt);
+        assertEquals(obj3, "newer context");
+        final Thread t3 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
+        final Thread t4 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "newer context", 1000));
+
+        t3.start();
+        t4.start();
+        t3.join();
+        t4.join();
+
+        Assert.assertEquals(e.eval(sharedScript), "original context");
+        Assert.assertEquals(e.eval(sharedScript, newCtxt), "newer context");
+    }
+
+    /**
+     * Test multi-threaded scope function invocation for shared script classes with multiple globals.
+     */
+    @Test
+    public static void multiThreadedFunctionTest() throws ScriptException, InterruptedException {
+        final ScriptEngineManager m = new ScriptEngineManager();
+        final ScriptEngine e = m.getEngineByName("nashorn");
+        final Bindings b = e.createBindings();
+        final ScriptContext origContext = e.getContext();
+        final ScriptContext newCtxt = new SimpleScriptContext();
+        newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
+
+        e.eval(new URLReader(ScopeTest.class.getResource("resources/func.js")), origContext);
+        assertEquals(origContext.getAttribute("scopeVar"), 1);
+        assertEquals(e.eval("scopeTest()"), 1);
+
+        e.eval(new URLReader(ScopeTest.class.getResource("resources/func.js")), newCtxt);
+        assertEquals(newCtxt.getAttribute("scopeVar"), 1);
+        assertEquals(e.eval("scopeTest();", newCtxt), 1);
+
+        assertEquals(e.eval("scopeVar = 3;", newCtxt), 3);
+        assertEquals(newCtxt.getAttribute("scopeVar"), 3);
+
+
+        final Thread t1 = new Thread(new ScriptRunner(e, origContext, "scopeTest()", 1, 1000));
+        final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, "scopeTest()", 3, 1000));
+
+        t1.start();
+        t2.start();
+        t1.join();
+        t2.join();
+
+    }
+
+    /**
+     * Test multi-threaded access to global getters and setters for shared script classes with multiple globals.
+     */
+    @Test
+    public static void getterSetterTest() throws ScriptException, InterruptedException {
+        final ScriptEngineManager m = new ScriptEngineManager();
+        final ScriptEngine e = m.getEngineByName("nashorn");
+        final Bindings b = e.createBindings();
+        final ScriptContext origContext = e.getContext();
+        final ScriptContext newCtxt = new SimpleScriptContext();
+        newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
+        final String sharedScript = "accessor1";
+
+        e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), origContext);
+        assertEquals(e.eval("accessor1 = 1;"), 1);
+        assertEquals(e.eval(sharedScript), 1);
+
+        e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), newCtxt);
+        assertEquals(e.eval("accessor1 = 2;", newCtxt), 2);
+        assertEquals(e.eval(sharedScript, newCtxt), 2);
+
+
+        final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, 1, 1000));
+        final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, 2, 1000));
+
+        t1.start();
+        t2.start();
+        t1.join();
+        t2.join();
+
+        assertEquals(e.eval(sharedScript), 1);
+        assertEquals(e.eval(sharedScript, newCtxt), 2);
+        assertEquals(e.eval("v"), 1);
+        assertEquals(e.eval("v", newCtxt), 2);
+    }
+
+    /**
+     * Test multi-threaded access to global getters and setters for shared script classes with multiple globals.
+     */
+    @Test
+    public static void getterSetter2Test() throws ScriptException, InterruptedException {
+        final ScriptEngineManager m = new ScriptEngineManager();
+        final ScriptEngine e = m.getEngineByName("nashorn");
+        final Bindings b = e.createBindings();
+        final ScriptContext origContext = e.getContext();
+        final ScriptContext newCtxt = new SimpleScriptContext();
+        newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
+        final String sharedScript = "accessor2";
+
+        e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), origContext);
+        assertEquals(e.eval("accessor2 = 1;"), 1);
+        assertEquals(e.eval(sharedScript), 1);
+
+        e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), newCtxt);
+        assertEquals(e.eval("accessor2 = 2;", newCtxt), 2);
+        assertEquals(e.eval(sharedScript, newCtxt), 2);
+
+
+        final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, 1, 1000));
+        final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, 2, 1000));
+
+        t1.start();
+        t2.start();
+        t1.join();
+        t2.join();
+
+        assertEquals(e.eval(sharedScript), 1);
+        assertEquals(e.eval(sharedScript, newCtxt), 2);
+        assertEquals(e.eval("x"), 1);
+        assertEquals(e.eval("x", newCtxt), 2);
+    }
+
+    /**
+     * Test "slow" scopes involving {@code with} and {@code eval} statements for shared script classes with multiple globals.
+     */
+    @Test
+    public static void testSlowScope() throws ScriptException, InterruptedException {
+        final ScriptEngineManager m = new ScriptEngineManager();
+        final ScriptEngine e = m.getEngineByName("nashorn");
+
+        for (int i = 0; i < 100; i++) {
+            final Bindings b = e.createBindings();
+            final ScriptContext ctxt = new SimpleScriptContext();
+            ctxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
+
+            e.eval(new URLReader(ScopeTest.class.getResource("resources/witheval.js")), ctxt);
+            assertEquals(e.eval("a", ctxt), 1);
+            assertEquals(b.get("a"), 1);
+            assertEquals(e.eval("b", ctxt), 3);
+            assertEquals(b.get("b"), 3);
+            assertEquals(e.eval("c", ctxt), 10);
+            assertEquals(b.get("c"), 10);
+        }
+    }
+
+    private static class ScriptRunner implements Runnable {
+
+        final ScriptEngine engine;
+        final ScriptContext context;
+        final String source;
+        final Object expected;
+        final int iterations;
+
+        ScriptRunner(final ScriptEngine engine, final ScriptContext context, final String source, final Object expected, final int iterations) {
+            this.engine = engine;
+            this.context = context;
+            this.source = source;
+            this.expected = expected;
+            this.iterations = iterations;
+        }
+
+        @Override
+        public void run() {
+            try {
+                for (int i = 0; i < iterations; i++) {
+                    assertEquals(engine.eval(source, context), expected);
+                }
+            } catch (ScriptException se) {
+                throw new RuntimeException(se);
+            }
+        }
+    }
+
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/src/jdk/nashorn/api/scripting/resources/func.js	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 script is loaded from jdk.nashorn.api.scripting.ScopeTest to test script class sharing and reuse.
+
+var scopeVar = 1;
+var global = this;
+undefGlobal = this;
+
+function scopeTest() {
+    if (this !== global) {
+        throw new Error("this !== global");
+    }
+    if (this !== undefGlobal) {
+        throw new Error("this !== undefinedGlobal")
+    }
+    return scopeVar;
+}
+
+scopeTest();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/src/jdk/nashorn/api/scripting/resources/gettersetter.js	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 script is loaded from jdk.nashorn.api.scripting.ScopeTest to test script class sharing and reuse.
+
+var v;
+
+Object.defineProperty(this, "accessor1", {
+    get: function() { return v; },
+    set: function(n) { v = n; }
+});
+
+Object.defineProperty(this, "accessor2", {
+    get: function() { return x; },
+    set: function(n) { x = n; }
+});
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/src/jdk/nashorn/api/scripting/resources/witheval.js	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 script is loaded from jdk.nashorn.api.scripting.ScopeTest to test script class sharing and reuse.
+
+var a;
+
+function outer(p, e) {
+    eval(e);
+    with(p) {
+        function inner() {
+            a = 1;
+            c = 10;
+            if (a !== 1) {
+                throw new Error("a !== 1");
+            }
+            if (b !== 3) {
+                throw new Error("b !== 3");
+            }
+            if (c !== 10) {
+                throw new Error("c !== 10");
+            }
+        }
+        inner();
+    }
+}
+
+outer({}, "b = 3;");
+
+if (a !== 1) {
+    throw new Error("a !== 1");
+}
+if (b !== 3) {
+    throw new Error("b !== 3");
+}
+if (c !== 10) {
+    throw new Error("c !== 10");
+}
--- a/nashorn/test/src/jdk/nashorn/internal/codegen/CompilerTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/test/src/jdk/nashorn/internal/codegen/CompilerTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -28,6 +28,7 @@
 import java.io.File;
 import java.io.PrintWriter;
 import java.io.StringWriter;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.Context;
 import jdk.nashorn.internal.runtime.ErrorManager;
 import jdk.nashorn.internal.runtime.ScriptFunction;
@@ -58,7 +59,7 @@
     }
 
     private Context context;
-    private ScriptObject global;
+    private Global  global;
 
     @BeforeClass
     public void setupTest() {
@@ -146,7 +147,7 @@
             log("Begin compiling " + file.getAbsolutePath());
         }
 
-        final ScriptObject oldGlobal = Context.getGlobal();
+        final Global oldGlobal = Context.getGlobal();
         final boolean globalChanged = (oldGlobal != global);
 
         try {
--- a/nashorn/test/src/jdk/nashorn/internal/performance/PerformanceWrapper.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/test/src/jdk/nashorn/internal/performance/PerformanceWrapper.java	Wed Jul 05 19:33:51 2017 +0200
@@ -31,9 +31,9 @@
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.Context;
 import jdk.nashorn.internal.runtime.ScriptFunction;
-import jdk.nashorn.internal.runtime.ScriptObject;
 import jdk.nashorn.internal.runtime.ScriptRuntime;
 
 /**
@@ -89,7 +89,7 @@
     @Override
     protected Object apply(final ScriptFunction target, final Object self) {
         if (_runsPerIteration == 0 && _numberOfIterations == 0) {
-            final ScriptObject global = jdk.nashorn.internal.runtime.Context.getGlobal();
+            final Global global = jdk.nashorn.internal.runtime.Context.getGlobal();
             final ScriptFunction _target = target;
             final Object _self = self;
 
--- a/nashorn/test/src/jdk/nashorn/internal/runtime/ContextTest.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/test/src/jdk/nashorn/internal/runtime/ContextTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -29,6 +29,7 @@
 import static org.testng.Assert.assertTrue;
 
 import java.util.Map;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.options.Options;
 import org.testng.annotations.Test;
 
@@ -45,7 +46,7 @@
         final Options options = new Options("");
         final ErrorManager errors = new ErrorManager();
         final Context cx = new Context(options, errors, Thread.currentThread().getContextClassLoader());
-        final ScriptObject oldGlobal = Context.getGlobal();
+        final Global oldGlobal = Context.getGlobal();
         Context.setGlobal(cx.createGlobal());
         try {
             String code = "22 + 10";
@@ -65,7 +66,7 @@
         final ErrorManager errors = new ErrorManager();
         final Context cx = new Context(options, errors, Thread.currentThread().getContextClassLoader());
         final boolean strict = cx.getEnv()._strict;
-        final ScriptObject oldGlobal = Context.getGlobal();
+        final Global oldGlobal = Context.getGlobal();
         Context.setGlobal(cx.createGlobal());
 
         try {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/src/jdk/nashorn/internal/runtime/NoPersistenceCachingTest.java	Wed Jul 05 19:33:51 2017 +0200
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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 jdk.nashorn.internal.runtime;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import static org.testng.Assert.fail;
+import org.testng.annotations.Test;
+
+import javax.script.ScriptContext;
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineFactory;
+import javax.script.ScriptEngineManager;
+import javax.script.SimpleScriptContext;
+import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
+
+/**
+ * @test
+ * @bug 8037378
+ * @summary Sanity tests for no persistence caching
+ * @run testng/othervm jdk.nashorn.internal.runtime.NoPersistenceCachingTest
+ */
+public class NoPersistenceCachingTest {
+
+   private ScriptEngine engine;
+   private ScriptContext context1, context2, context3;
+   private ByteArrayOutputStream stderr;
+   private PrintStream prevStderr;
+   private final String script = "print('Hello')";
+
+   public void setupTest() {
+      stderr = new ByteArrayOutputStream();
+      prevStderr = System.err;
+      System.setErr(new PrintStream(stderr));
+      NashornScriptEngineFactory nashornFactory = null;
+      ScriptEngineManager sm = new ScriptEngineManager();
+      for (ScriptEngineFactory fac : sm.getEngineFactories()) {
+         if (fac instanceof NashornScriptEngineFactory) {
+            nashornFactory = (NashornScriptEngineFactory) fac;
+            break;
+         }
+      }
+      if (nashornFactory == null) {
+         fail("Cannot find nashorn factory!");
+      }
+      String[] options = new String[]{"--log=compiler:finest"};
+      engine = nashornFactory.getScriptEngine(options);
+   }
+
+   public void setErrTest() {
+      System.setErr(prevStderr);
+   }
+
+   public void runTest(int numberOfContext, String expectedOutputPattern,
+                       int expectedPatternOccurrence) {
+      setupTest();
+      try {
+         switch (numberOfContext) {
+         case 2:
+            context1 = engine.getContext();
+            context2 = new SimpleScriptContext();
+            context2.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
+            engine.eval(script, context1);
+            engine.eval(script, context2);
+            break;
+         case 3:
+            context1 = engine.getContext();
+            context2 = new SimpleScriptContext();
+            context2.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
+            context3 = new SimpleScriptContext();
+            context3.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
+            engine.eval(script, context1);
+            engine.eval(script, context2);
+            engine.eval(script, context3);
+            break;
+         }
+      } catch (final Exception se) {
+         se.printStackTrace();
+         fail(se.getMessage());
+      }
+      Pattern deoptimizing = Pattern.compile(expectedOutputPattern);
+      Matcher matcher = deoptimizing.matcher(stderr.toString());
+      int matches = 0;
+      while (matcher.find()) {
+         matches++;
+      }
+      if (matches != expectedPatternOccurrence) {
+         fail("Number of cache hit is not correct, expected: "
+                    + expectedPatternOccurrence + " and found: " + matches + "\n"
+              + stderr);
+      }
+      setErrTest();
+   }
+
+   private static String getCodeCachePattern() {
+      return ("\\[compiler\\]\\sCode\\scache\\shit\\sfor\\s<eval>\\savoiding\\srecompile.");
+   }
+
+    @Test
+    public void twoContextTest() {
+       runTest(2, getCodeCachePattern(), 1);
+
+    }
+
+    @Test
+    public void threeContextTest() {
+       runTest(3, getCodeCachePattern(), 2);
+    }
+}
--- a/nashorn/test/src/jdk/nashorn/internal/test/framework/SharedContextEvaluator.java	Tue Mar 25 12:31:49 2014 -0700
+++ b/nashorn/test/src/jdk/nashorn/internal/test/framework/SharedContextEvaluator.java	Wed Jul 05 19:33:51 2017 +0200
@@ -34,10 +34,10 @@
 import java.io.OutputStream;
 import java.io.PrintWriter;
 import jdk.nashorn.api.scripting.NashornException;
+import jdk.nashorn.internal.objects.Global;
 import jdk.nashorn.internal.runtime.Context;
 import jdk.nashorn.internal.runtime.ErrorManager;
 import jdk.nashorn.internal.runtime.ScriptFunction;
-import jdk.nashorn.internal.runtime.ScriptObject;
 import jdk.nashorn.internal.runtime.ScriptRuntime;
 import jdk.nashorn.internal.runtime.Source;
 import jdk.nashorn.internal.runtime.options.Options;
@@ -110,12 +110,12 @@
 
     @Override
     public int run(final OutputStream out, final OutputStream err, final String[] args) throws IOException {
-        final ScriptObject oldGlobal = Context.getGlobal();
+        final Global oldGlobal = Context.getGlobal();
         try {
             ctxOut.setDelegatee(out);
             ctxErr.setDelegatee(err);
             final ErrorManager errors = context.getErrorManager();
-            final ScriptObject global = context.createGlobal();
+            final Global global = context.createGlobal();
             Context.setGlobal(global);
 
             // For each file on the command line.