JDK-8161245 : Enums should be fully optimized
  • Type: Enhancement
  • Component: hotspot
  • Sub-Component: compiler
  • Affected Version: 9,10
  • Priority: P3
  • Status: Closed
  • Resolution: Duplicate
  • Submitted: 2016-07-13
  • Updated: 2022-11-29
  • Resolved: 2022-11-29
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
Other
tbdResolved
Related Reports
Duplicate :  
Relates :  
Relates :  
Relates :  
Relates :  
Relates :  
Relates :  
Description
Enums are the recommended way to express abstract named singleton values.  But they do not optimize well, because the JIT does not trust their ordinal and name fields.

(Another problem is that the current translation strategy for switch-on-enum uses a mutable array (for locally indexing enums) when a constant or stable one will work  better.  Fixing this will require a change to the translation strategy for switches, which is a separate bug.  But the present fix is valuable standing alone, because a determined library writer can switch or if/else on the raw ordinal of an enum, getting full performance.  The cost of this hack is a tight coupling between the enum structure and the library, but this is sometimes acceptable, such as in Java SE platform code.)

Suggested fix for constant folding ordinal and name fields:

diff --git a/src/share/vm/ci/ciField.cpp b/src/share/vm/ci/ciField.cpp
--- a/src/share/vm/ci/ciField.cpp
+++ b/src/share/vm/ci/ciField.cpp
@@ -219,6 +219,9 @@
   // Trust final fields in String
   if (holder->name() == ciSymbol::java_lang_String())
     return true;
+  // Trust standard enum fields, such as Enum.ordinal and Enum.name.
+  if (holder->name() == ciSymbol::java_lang_Enum())
+    return true;
   // Trust Atomic*FieldUpdaters: they are very important for performance, and make up one
   // more reason not to use Unsafe, if their final fields are trusted. See more in JDK-8140483.
   if (holder->name() == ciSymbol::java_util_concurrent_atomic_AtomicIntegerFieldUpdater_Impl() ||

Comments
Added the test in JDK-8286190, to guard from accidental regression. Otherwise, I think this issue can be closed as (weird) duplicate of JDK-8234049.
05-05-2022

Weirdly, JDK-8234049 added the wildcard trust for everything in java/lang, which implicitly implements this: https://github.com/openjdk/jdk/blob/c5a0687f80367a3a284dfd56781c371826264d3b/src/hotspot/share/ci/ciField.cpp#L230 I checked a few adhoc benchmarks to see that ordinal() and name() are constant-folded.
04-05-2022