1 /*
   2  * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/macroAssembler.hpp"
  27 #include "ci/ciFlatArrayKlass.hpp"
  28 #include "ci/ciUtilities.inline.hpp"
  29 #include "classfile/vmIntrinsics.hpp"
  30 #include "compiler/compileBroker.hpp"
  31 #include "compiler/compileLog.hpp"
  32 #include "gc/shared/barrierSet.hpp"
  33 #include "jfr/support/jfrIntrinsics.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "oops/klass.inline.hpp"
  36 #include "oops/objArrayKlass.hpp"
  37 #include "opto/addnode.hpp"
  38 #include "opto/arraycopynode.hpp"
  39 #include "opto/c2compiler.hpp"
  40 #include "opto/castnode.hpp"
  41 #include "opto/cfgnode.hpp"
  42 #include "opto/convertnode.hpp"
  43 #include "opto/countbitsnode.hpp"
  44 #include "opto/idealKit.hpp"
  45 #include "opto/library_call.hpp"
  46 #include "opto/mathexactnode.hpp"
  47 #include "opto/mulnode.hpp"
  48 #include "opto/narrowptrnode.hpp"
  49 #include "opto/opaquenode.hpp"
  50 #include "opto/parse.hpp"
  51 #include "opto/runtime.hpp"
  52 #include "opto/rootnode.hpp"
  53 #include "opto/subnode.hpp"
  54 #include "prims/unsafe.hpp"
  55 #include "runtime/objectMonitor.hpp"
  56 #include "runtime/sharedRuntime.hpp"
  57 #include "runtime/stubRoutines.hpp"
  58 #include "utilities/macros.hpp"
  59 #include "utilities/powerOfTwo.hpp"
  60 
  61 #if INCLUDE_JFR
  62 #include "jfr/jfr.hpp"
  63 #endif
  64 
  65 //---------------------------make_vm_intrinsic----------------------------
  66 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  67   vmIntrinsicID id = m->intrinsic_id();
  68   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  69 
  70   if (!m->is_loaded()) {
  71     // Do not attempt to inline unloaded methods.
  72     return NULL;
  73   }
  74 
  75   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  76   bool is_available = false;
  77 
  78   {
  79     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  80     // the compiler must transition to '_thread_in_vm' state because both
  81     // methods access VM-internal data.
  82     VM_ENTRY_MARK;
  83     methodHandle mh(THREAD, m->get_Method());
  84     is_available = compiler != NULL && compiler->is_intrinsic_supported(mh, is_virtual) &&
  85                    !C->directive()->is_intrinsic_disabled(mh) &&
  86                    !vmIntrinsics::is_disabled_by_flags(mh);
  87 
  88   }
  89 
  90   if (is_available) {
  91     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
  92     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
  93     return new LibraryIntrinsic(m, is_virtual,
  94                                 vmIntrinsics::predicates_needed(id),
  95                                 vmIntrinsics::does_virtual_dispatch(id),
  96                                 id);
  97   } else {
  98     return NULL;
  99   }
 100 }
 101 
 102 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 103   LibraryCallKit kit(jvms, this);
 104   Compile* C = kit.C;
 105   int nodes = C->unique();
 106 #ifndef PRODUCT
 107   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 108     char buf[1000];
 109     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 110     tty->print_cr("Intrinsic %s", str);
 111   }
 112 #endif
 113   ciMethod* callee = kit.callee();
 114   const int bci    = kit.bci();
 115 #ifdef ASSERT
 116   Node* ctrl = kit.control();
 117 #endif
 118   // Try to inline the intrinsic.
 119   if (callee->check_intrinsic_candidate() &&
 120       kit.try_to_inline(_last_predicate)) {
 121     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 122                                           : "(intrinsic)";
 123     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, inline_msg);
 124     if (C->print_intrinsics() || C->print_inlining()) {
 125       C->print_inlining(callee, jvms->depth() - 1, bci, inline_msg);
 126     }
 127     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 128     if (C->log()) {
 129       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 130                      vmIntrinsics::name_at(intrinsic_id()),
 131                      (is_virtual() ? " virtual='1'" : ""),
 132                      C->unique() - nodes);
 133     }
 134     // Push the result from the inlined method onto the stack.
 135     kit.push_result();
 136     C->print_inlining_update(this);
 137     return kit.transfer_exceptions_into_jvms();
 138   }
 139 
 140   // The intrinsic bailed out
 141   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 142   if (jvms->has_method()) {
 143     // Not a root compile.
 144     const char* msg;
 145     if (callee->intrinsic_candidate()) {
 146       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 147     } else {
 148       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 149                          : "failed to inline (intrinsic), method not annotated";
 150     }
 151     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, msg);
 152     if (C->print_intrinsics() || C->print_inlining()) {
 153       C->print_inlining(callee, jvms->depth() - 1, bci, msg);
 154     }
 155   } else {
 156     // Root compile
 157     ResourceMark rm;
 158     stringStream msg_stream;
 159     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 160                      vmIntrinsics::name_at(intrinsic_id()),
 161                      is_virtual() ? " (virtual)" : "", bci);
 162     const char *msg = msg_stream.as_string();
 163     log_debug(jit, inlining)("%s", msg);
 164     if (C->print_intrinsics() || C->print_inlining()) {
 165       tty->print("%s", msg);
 166     }
 167   }
 168   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 169   C->print_inlining_update(this);
 170 
 171   return NULL;
 172 }
 173 
 174 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 175   LibraryCallKit kit(jvms, this);
 176   Compile* C = kit.C;
 177   int nodes = C->unique();
 178   _last_predicate = predicate;
 179 #ifndef PRODUCT
 180   assert(is_predicated() && predicate < predicates_count(), "sanity");
 181   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 182     char buf[1000];
 183     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 184     tty->print_cr("Predicate for intrinsic %s", str);
 185   }
 186 #endif
 187   ciMethod* callee = kit.callee();
 188   const int bci    = kit.bci();
 189 
 190   Node* slow_ctl = kit.try_to_predicate(predicate);
 191   if (!kit.failing()) {
 192     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 193                                           : "(intrinsic, predicate)";
 194     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, inline_msg);
 195     if (C->print_intrinsics() || C->print_inlining()) {
 196       C->print_inlining(callee, jvms->depth() - 1, bci, inline_msg);
 197     }
 198     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 199     if (C->log()) {
 200       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 201                      vmIntrinsics::name_at(intrinsic_id()),
 202                      (is_virtual() ? " virtual='1'" : ""),
 203                      C->unique() - nodes);
 204     }
 205     return slow_ctl; // Could be NULL if the check folds.
 206   }
 207 
 208   // The intrinsic bailed out
 209   if (jvms->has_method()) {
 210     // Not a root compile.
 211     const char* msg = "failed to generate predicate for intrinsic";
 212     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, msg);
 213     if (C->print_intrinsics() || C->print_inlining()) {
 214       C->print_inlining(kit.callee(), jvms->depth() - 1, bci, msg);
 215     }
 216   } else {
 217     // Root compile
 218     ResourceMark rm;
 219     stringStream msg_stream;
 220     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 221                      vmIntrinsics::name_at(intrinsic_id()),
 222                      is_virtual() ? " (virtual)" : "", bci);
 223     const char *msg = msg_stream.as_string();
 224     log_debug(jit, inlining)("%s", msg);
 225     if (C->print_intrinsics() || C->print_inlining()) {
 226       C->print_inlining_stream()->print("%s", msg);
 227     }
 228   }
 229   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 230   return NULL;
 231 }
 232 
 233 bool LibraryCallKit::try_to_inline(int predicate) {
 234   // Handle symbolic names for otherwise undistinguished boolean switches:
 235   const bool is_store       = true;
 236   const bool is_compress    = true;
 237   const bool is_static      = true;
 238   const bool is_volatile    = true;
 239 
 240   if (!jvms()->has_method()) {
 241     // Root JVMState has a null method.
 242     assert(map()->memory()->Opcode() == Op_Parm, "");
 243     // Insert the memory aliasing node
 244     set_all_memory(reset_memory());
 245   }
 246   assert(merged_memory(), "");
 247 
 248   switch (intrinsic_id()) {
 249   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 250   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 251   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 252 
 253   case vmIntrinsics::_ceil:
 254   case vmIntrinsics::_floor:
 255   case vmIntrinsics::_rint:
 256   case vmIntrinsics::_dsin:
 257   case vmIntrinsics::_dcos:
 258   case vmIntrinsics::_dtan:
 259   case vmIntrinsics::_dabs:
 260   case vmIntrinsics::_fabs:
 261   case vmIntrinsics::_iabs:
 262   case vmIntrinsics::_labs:
 263   case vmIntrinsics::_datan2:
 264   case vmIntrinsics::_dsqrt:
 265   case vmIntrinsics::_dexp:
 266   case vmIntrinsics::_dlog:
 267   case vmIntrinsics::_dlog10:
 268   case vmIntrinsics::_dpow:
 269   case vmIntrinsics::_dcopySign:
 270   case vmIntrinsics::_fcopySign:
 271   case vmIntrinsics::_dsignum:
 272   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 273 
 274   case vmIntrinsics::_min:
 275   case vmIntrinsics::_max:                      return inline_min_max(intrinsic_id());
 276 
 277   case vmIntrinsics::_notify:
 278   case vmIntrinsics::_notifyAll:
 279     return inline_notify(intrinsic_id());
 280 
 281   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 282   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 283   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 284   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 285   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 286   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 287   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 288   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 289   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 290   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 291   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 292   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 293   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 294 
 295   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 296 
 297   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 298   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 299   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 300   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 301 
 302   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 303   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 304   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 305   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 306   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 307   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 308   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 309   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 310 
 311   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 312   case vmIntrinsics::_equalsU:                  return inline_string_equals(StrIntrinsicNode::UU);
 313 
 314   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 315   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 316   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 317   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 318 
 319   case vmIntrinsics::_compressStringC:
 320   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 321   case vmIntrinsics::_inflateStringC:
 322   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 323 
 324   case vmIntrinsics::_makePrivateBuffer:        return inline_unsafe_make_private_buffer();
 325   case vmIntrinsics::_finishPrivateBuffer:      return inline_unsafe_finish_private_buffer();
 326   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 327   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 328   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 329   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 330   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 331   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 332   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 333   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 334   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 335   case vmIntrinsics::_getValue:                 return inline_unsafe_access(!is_store, T_INLINE_TYPE,Relaxed, false);
 336 
 337   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 338   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 339   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 340   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 341   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 342   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 343   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 344   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 345   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 346   case vmIntrinsics::_putValue:                 return inline_unsafe_access( is_store, T_INLINE_TYPE,Relaxed, false);
 347 
 348   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 349   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 350   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 351   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 352   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 353   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 354   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 355   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 356   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 357 
 358   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 359   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 360   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 361   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 362   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 363   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 364   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 365   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 366   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 367 
 368   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 369   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 370   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 371   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 372 
 373   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 374   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 375   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 376   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 377 
 378   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 379   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 380   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 381   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 382   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 383   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 384   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 385   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 386   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 387 
 388   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 389   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 390   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 391   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 392   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 393   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 394   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 395   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 396   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 397 
 398   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 399   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 400   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 401   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 402   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 403   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 404   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 405   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 406   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 407 
 408   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 409   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 410   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 411   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 412   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 413   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 414   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 415   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 416   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 417 
 418   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 419   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 420   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 421   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 422   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 423 
 424   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 425   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 426   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 427   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 428   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 429   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 430   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 431   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 432   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 433   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 434   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 435   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 436   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 437   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 438   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 439   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 440   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 441   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 442   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 443   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 444 
 445   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 446   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 447   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 448   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 449   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 450   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 451   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 452   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 453   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 454   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 455   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 456   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 457   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 458   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 459   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 460 
 461   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 462   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 463   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 464   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 465 
 466   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 467   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 468   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 469   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 470   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 471 
 472   case vmIntrinsics::_loadFence:
 473   case vmIntrinsics::_storeFence:
 474   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 475 
 476   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 477 
 478   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 479 
 480 #ifdef JFR_HAVE_INTRINSICS
 481   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JFR_TIME_FUNCTION), "counterTime");
 482   case vmIntrinsics::_getClassId:               return inline_native_classID();
 483   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 484 #endif
 485   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 486   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 487   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 488   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 489   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 490   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 491   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 492   case vmIntrinsics::_getLength:                return inline_native_getLength();
 493   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 494   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 495   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 496   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 497   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 498   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 499   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 500 
 501   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 502   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 503 
 504   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 505 
 506   case vmIntrinsics::_isInstance:
 507   case vmIntrinsics::_getModifiers:
 508   case vmIntrinsics::_isInterface:
 509   case vmIntrinsics::_isArray:
 510   case vmIntrinsics::_isPrimitive:
 511   case vmIntrinsics::_isHidden:
 512   case vmIntrinsics::_getSuperclass:
 513   case vmIntrinsics::_getClassAccessFlags:      return inline_native_Class_query(intrinsic_id());
 514 
 515   case vmIntrinsics::_asPrimaryType:
 516   case vmIntrinsics::_asValueType:              return inline_primitive_Class_conversion(intrinsic_id());
 517 
 518   case vmIntrinsics::_floatToRawIntBits:
 519   case vmIntrinsics::_floatToIntBits:
 520   case vmIntrinsics::_intBitsToFloat:
 521   case vmIntrinsics::_doubleToRawLongBits:
 522   case vmIntrinsics::_doubleToLongBits:
 523   case vmIntrinsics::_longBitsToDouble:         return inline_fp_conversions(intrinsic_id());
 524 
 525   case vmIntrinsics::_numberOfLeadingZeros_i:
 526   case vmIntrinsics::_numberOfLeadingZeros_l:
 527   case vmIntrinsics::_numberOfTrailingZeros_i:
 528   case vmIntrinsics::_numberOfTrailingZeros_l:
 529   case vmIntrinsics::_bitCount_i:
 530   case vmIntrinsics::_bitCount_l:
 531   case vmIntrinsics::_reverseBytes_i:
 532   case vmIntrinsics::_reverseBytes_l:
 533   case vmIntrinsics::_reverseBytes_s:
 534   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 535 
 536   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 537 
 538   case vmIntrinsics::_Reference_get:            return inline_reference_get();
 539   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 540   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 541 
 542   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 543 
 544   case vmIntrinsics::_aescrypt_encryptBlock:
 545   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 546 
 547   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 548   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 549     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 550 
 551   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 552   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 553     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 554 
 555   case vmIntrinsics::_counterMode_AESCrypt:
 556     return inline_counterMode_AESCrypt(intrinsic_id());
 557 
 558   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 559     return inline_galoisCounterMode_AESCrypt();
 560 
 561   case vmIntrinsics::_md5_implCompress:
 562   case vmIntrinsics::_sha_implCompress:
 563   case vmIntrinsics::_sha2_implCompress:
 564   case vmIntrinsics::_sha5_implCompress:
 565   case vmIntrinsics::_sha3_implCompress:
 566     return inline_digestBase_implCompress(intrinsic_id());
 567 
 568   case vmIntrinsics::_digestBase_implCompressMB:
 569     return inline_digestBase_implCompressMB(predicate);
 570 
 571   case vmIntrinsics::_multiplyToLen:
 572     return inline_multiplyToLen();
 573 
 574   case vmIntrinsics::_squareToLen:
 575     return inline_squareToLen();
 576 
 577   case vmIntrinsics::_mulAdd:
 578     return inline_mulAdd();
 579 
 580   case vmIntrinsics::_montgomeryMultiply:
 581     return inline_montgomeryMultiply();
 582   case vmIntrinsics::_montgomerySquare:
 583     return inline_montgomerySquare();
 584 
 585   case vmIntrinsics::_bigIntegerRightShiftWorker:
 586     return inline_bigIntegerShift(true);
 587   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 588     return inline_bigIntegerShift(false);
 589 
 590   case vmIntrinsics::_vectorizedMismatch:
 591     return inline_vectorizedMismatch();
 592 
 593   case vmIntrinsics::_ghash_processBlocks:
 594     return inline_ghash_processBlocks();
 595   case vmIntrinsics::_base64_encodeBlock:
 596     return inline_base64_encodeBlock();
 597   case vmIntrinsics::_base64_decodeBlock:
 598     return inline_base64_decodeBlock();
 599 
 600   case vmIntrinsics::_encodeISOArray:
 601   case vmIntrinsics::_encodeByteISOArray:
 602     return inline_encodeISOArray(false);
 603   case vmIntrinsics::_encodeAsciiArray:
 604     return inline_encodeISOArray(true);
 605 
 606   case vmIntrinsics::_updateCRC32:
 607     return inline_updateCRC32();
 608   case vmIntrinsics::_updateBytesCRC32:
 609     return inline_updateBytesCRC32();
 610   case vmIntrinsics::_updateByteBufferCRC32:
 611     return inline_updateByteBufferCRC32();
 612 
 613   case vmIntrinsics::_updateBytesCRC32C:
 614     return inline_updateBytesCRC32C();
 615   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 616     return inline_updateDirectByteBufferCRC32C();
 617 
 618   case vmIntrinsics::_updateBytesAdler32:
 619     return inline_updateBytesAdler32();
 620   case vmIntrinsics::_updateByteBufferAdler32:
 621     return inline_updateByteBufferAdler32();
 622 
 623   case vmIntrinsics::_profileBoolean:
 624     return inline_profileBoolean();
 625   case vmIntrinsics::_isCompileConstant:
 626     return inline_isCompileConstant();
 627 
 628   case vmIntrinsics::_hasNegatives:
 629     return inline_hasNegatives();
 630 
 631   case vmIntrinsics::_fmaD:
 632   case vmIntrinsics::_fmaF:
 633     return inline_fma(intrinsic_id());
 634 
 635   case vmIntrinsics::_isDigit:
 636   case vmIntrinsics::_isLowerCase:
 637   case vmIntrinsics::_isUpperCase:
 638   case vmIntrinsics::_isWhitespace:
 639     return inline_character_compare(intrinsic_id());
 640 
 641   case vmIntrinsics::_maxF:
 642   case vmIntrinsics::_minF:
 643   case vmIntrinsics::_maxD:
 644   case vmIntrinsics::_minD:
 645     return inline_fp_min_max(intrinsic_id());
 646 
 647   case vmIntrinsics::_VectorUnaryOp:
 648     return inline_vector_nary_operation(1);
 649   case vmIntrinsics::_VectorBinaryOp:
 650     return inline_vector_nary_operation(2);
 651   case vmIntrinsics::_VectorTernaryOp:
 652     return inline_vector_nary_operation(3);
 653   case vmIntrinsics::_VectorBroadcastCoerced:
 654     return inline_vector_broadcast_coerced();
 655   case vmIntrinsics::_VectorShuffleIota:
 656     return inline_vector_shuffle_iota();
 657   case vmIntrinsics::_VectorMaskOp:
 658     return inline_vector_mask_operation();
 659   case vmIntrinsics::_VectorShuffleToVector:
 660     return inline_vector_shuffle_to_vector();
 661   case vmIntrinsics::_VectorLoadOp:
 662     return inline_vector_mem_operation(/*is_store=*/false);
 663   case vmIntrinsics::_VectorStoreOp:
 664     return inline_vector_mem_operation(/*is_store=*/true);
 665   case vmIntrinsics::_VectorGatherOp:
 666     return inline_vector_gather_scatter(/*is_scatter*/ false);
 667   case vmIntrinsics::_VectorScatterOp:
 668     return inline_vector_gather_scatter(/*is_scatter*/ true);
 669   case vmIntrinsics::_VectorReductionCoerced:
 670     return inline_vector_reduction();
 671   case vmIntrinsics::_VectorTest:
 672     return inline_vector_test();
 673   case vmIntrinsics::_VectorBlend:
 674     return inline_vector_blend();
 675   case vmIntrinsics::_VectorRearrange:
 676     return inline_vector_rearrange();
 677   case vmIntrinsics::_VectorCompare:
 678     return inline_vector_compare();
 679   case vmIntrinsics::_VectorBroadcastInt:
 680     return inline_vector_broadcast_int();
 681   case vmIntrinsics::_VectorConvert:
 682     return inline_vector_convert();
 683   case vmIntrinsics::_VectorInsert:
 684     return inline_vector_insert();
 685   case vmIntrinsics::_VectorExtract:
 686     return inline_vector_extract();
 687 
 688   case vmIntrinsics::_getObjectSize:
 689     return inline_getObjectSize();
 690 
 691   case vmIntrinsics::_blackhole:
 692     return inline_blackhole();
 693 
 694   default:
 695     // If you get here, it may be that someone has added a new intrinsic
 696     // to the list in vmIntrinsics.hpp without implementing it here.
 697 #ifndef PRODUCT
 698     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 699       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 700                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 701     }
 702 #endif
 703     return false;
 704   }
 705 }
 706 
 707 Node* LibraryCallKit::try_to_predicate(int predicate) {
 708   if (!jvms()->has_method()) {
 709     // Root JVMState has a null method.
 710     assert(map()->memory()->Opcode() == Op_Parm, "");
 711     // Insert the memory aliasing node
 712     set_all_memory(reset_memory());
 713   }
 714   assert(merged_memory(), "");
 715 
 716   switch (intrinsic_id()) {
 717   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 718     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 719   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 720     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 721   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 722     return inline_electronicCodeBook_AESCrypt_predicate(false);
 723   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 724     return inline_electronicCodeBook_AESCrypt_predicate(true);
 725   case vmIntrinsics::_counterMode_AESCrypt:
 726     return inline_counterMode_AESCrypt_predicate();
 727   case vmIntrinsics::_digestBase_implCompressMB:
 728     return inline_digestBase_implCompressMB_predicate(predicate);
 729   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 730     return inline_galoisCounterMode_AESCrypt_predicate();
 731 
 732   default:
 733     // If you get here, it may be that someone has added a new intrinsic
 734     // to the list in vmIntrinsics.hpp without implementing it here.
 735 #ifndef PRODUCT
 736     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 737       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 738                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 739     }
 740 #endif
 741     Node* slow_ctl = control();
 742     set_control(top()); // No fast path instrinsic
 743     return slow_ctl;
 744   }
 745 }
 746 
 747 //------------------------------set_result-------------------------------
 748 // Helper function for finishing intrinsics.
 749 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 750   record_for_igvn(region);
 751   set_control(_gvn.transform(region));
 752   set_result( _gvn.transform(value));
 753   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 754 }
 755 
 756 //------------------------------generate_guard---------------------------
 757 // Helper function for generating guarded fast-slow graph structures.
 758 // The given 'test', if true, guards a slow path.  If the test fails
 759 // then a fast path can be taken.  (We generally hope it fails.)
 760 // In all cases, GraphKit::control() is updated to the fast path.
 761 // The returned value represents the control for the slow path.
 762 // The return value is never 'top'; it is either a valid control
 763 // or NULL if it is obvious that the slow path can never be taken.
 764 // Also, if region and the slow control are not NULL, the slow edge
 765 // is appended to the region.
 766 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 767   if (stopped()) {
 768     // Already short circuited.
 769     return NULL;
 770   }
 771 
 772   // Build an if node and its projections.
 773   // If test is true we take the slow path, which we assume is uncommon.
 774   if (_gvn.type(test) == TypeInt::ZERO) {
 775     // The slow branch is never taken.  No need to build this guard.
 776     return NULL;
 777   }
 778 
 779   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 780 
 781   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 782   if (if_slow == top()) {
 783     // The slow branch is never taken.  No need to build this guard.
 784     return NULL;
 785   }
 786 
 787   if (region != NULL)
 788     region->add_req(if_slow);
 789 
 790   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 791   set_control(if_fast);
 792 
 793   return if_slow;
 794 }
 795 
 796 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 797   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 798 }
 799 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 800   return generate_guard(test, region, PROB_FAIR);
 801 }
 802 
 803 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 804                                                      Node* *pos_index) {
 805   if (stopped())
 806     return NULL;                // already stopped
 807   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 808     return NULL;                // index is already adequately typed
 809   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 810   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 811   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 812   if (is_neg != NULL && pos_index != NULL) {
 813     // Emulate effect of Parse::adjust_map_after_if.
 814     Node* ccast = new CastIINode(index, TypeInt::POS);
 815     ccast->set_req(0, control());
 816     (*pos_index) = _gvn.transform(ccast);
 817   }
 818   return is_neg;
 819 }
 820 
 821 // Make sure that 'position' is a valid limit index, in [0..length].
 822 // There are two equivalent plans for checking this:
 823 //   A. (offset + copyLength)  unsigned<=  arrayLength
 824 //   B. offset  <=  (arrayLength - copyLength)
 825 // We require that all of the values above, except for the sum and
 826 // difference, are already known to be non-negative.
 827 // Plan A is robust in the face of overflow, if offset and copyLength
 828 // are both hugely positive.
 829 //
 830 // Plan B is less direct and intuitive, but it does not overflow at
 831 // all, since the difference of two non-negatives is always
 832 // representable.  Whenever Java methods must perform the equivalent
 833 // check they generally use Plan B instead of Plan A.
 834 // For the moment we use Plan A.
 835 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 836                                                   Node* subseq_length,
 837                                                   Node* array_length,
 838                                                   RegionNode* region) {
 839   if (stopped())
 840     return NULL;                // already stopped
 841   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 842   if (zero_offset && subseq_length->eqv_uncast(array_length))
 843     return NULL;                // common case of whole-array copy
 844   Node* last = subseq_length;
 845   if (!zero_offset)             // last += offset
 846     last = _gvn.transform(new AddINode(last, offset));
 847   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 848   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 849   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 850   return is_over;
 851 }
 852 
 853 // Emit range checks for the given String.value byte array
 854 void LibraryCallKit::generate_string_range_check(Node* array, Node* offset, Node* count, bool char_count) {
 855   if (stopped()) {
 856     return; // already stopped
 857   }
 858   RegionNode* bailout = new RegionNode(1);
 859   record_for_igvn(bailout);
 860   if (char_count) {
 861     // Convert char count to byte count
 862     count = _gvn.transform(new LShiftINode(count, intcon(1)));
 863   }
 864 
 865   // Offset and count must not be negative
 866   generate_negative_guard(offset, bailout);
 867   generate_negative_guard(count, bailout);
 868   // Offset + count must not exceed length of array
 869   generate_limit_guard(offset, count, load_array_length(array), bailout);
 870 
 871   if (bailout->req() > 1) {
 872     PreserveJVMState pjvms(this);
 873     set_control(_gvn.transform(bailout));
 874     uncommon_trap(Deoptimization::Reason_intrinsic,
 875                   Deoptimization::Action_maybe_recompile);
 876   }
 877 }
 878 
 879 //--------------------------generate_current_thread--------------------
 880 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
 881   ciKlass*    thread_klass = env()->Thread_klass();
 882   const Type* thread_type  = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
 883   Node* thread = _gvn.transform(new ThreadLocalNode());
 884   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::threadObj_offset()));
 885   tls_output = thread;
 886   Node* thread_obj_handle = LoadNode::make(_gvn, NULL, immutable_memory(), p, p->bottom_type()->is_ptr(), TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
 887   thread_obj_handle = _gvn.transform(thread_obj_handle);
 888   return access_load(thread_obj_handle, thread_type, T_OBJECT, IN_NATIVE | C2_IMMUTABLE_MEMORY);
 889 }
 890 
 891 
 892 //------------------------------make_string_method_node------------------------
 893 // Helper method for String intrinsic functions. This version is called with
 894 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
 895 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
 896 // containing the lengths of str1 and str2.
 897 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
 898   Node* result = NULL;
 899   switch (opcode) {
 900   case Op_StrIndexOf:
 901     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
 902                                 str1_start, cnt1, str2_start, cnt2, ae);
 903     break;
 904   case Op_StrComp:
 905     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
 906                              str1_start, cnt1, str2_start, cnt2, ae);
 907     break;
 908   case Op_StrEquals:
 909     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
 910     // Use the constant length if there is one because optimized match rule may exist.
 911     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
 912                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
 913     break;
 914   default:
 915     ShouldNotReachHere();
 916     return NULL;
 917   }
 918 
 919   // All these intrinsics have checks.
 920   C->set_has_split_ifs(true); // Has chance for split-if optimization
 921   clear_upper_avx();
 922 
 923   return _gvn.transform(result);
 924 }
 925 
 926 //------------------------------inline_string_compareTo------------------------
 927 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
 928   Node* arg1 = argument(0);
 929   Node* arg2 = argument(1);
 930 
 931   arg1 = must_be_not_null(arg1, true);
 932   arg2 = must_be_not_null(arg2, true);
 933 
 934   // Get start addr and length of first argument
 935   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
 936   Node* arg1_cnt    = load_array_length(arg1);
 937 
 938   // Get start addr and length of second argument
 939   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
 940   Node* arg2_cnt    = load_array_length(arg2);
 941 
 942   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
 943   set_result(result);
 944   return true;
 945 }
 946 
 947 //------------------------------inline_string_equals------------------------
 948 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
 949   Node* arg1 = argument(0);
 950   Node* arg2 = argument(1);
 951 
 952   // paths (plus control) merge
 953   RegionNode* region = new RegionNode(3);
 954   Node* phi = new PhiNode(region, TypeInt::BOOL);
 955 
 956   if (!stopped()) {
 957 
 958     arg1 = must_be_not_null(arg1, true);
 959     arg2 = must_be_not_null(arg2, true);
 960 
 961     // Get start addr and length of first argument
 962     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
 963     Node* arg1_cnt    = load_array_length(arg1);
 964 
 965     // Get start addr and length of second argument
 966     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
 967     Node* arg2_cnt    = load_array_length(arg2);
 968 
 969     // Check for arg1_cnt != arg2_cnt
 970     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
 971     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
 972     Node* if_ne = generate_slow_guard(bol, NULL);
 973     if (if_ne != NULL) {
 974       phi->init_req(2, intcon(0));
 975       region->init_req(2, if_ne);
 976     }
 977 
 978     // Check for count == 0 is done by assembler code for StrEquals.
 979 
 980     if (!stopped()) {
 981       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
 982       phi->init_req(1, equals);
 983       region->init_req(1, control());
 984     }
 985   }
 986 
 987   // post merge
 988   set_control(_gvn.transform(region));
 989   record_for_igvn(region);
 990 
 991   set_result(_gvn.transform(phi));
 992   return true;
 993 }
 994 
 995 //------------------------------inline_array_equals----------------------------
 996 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
 997   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
 998   Node* arg1 = argument(0);
 999   Node* arg2 = argument(1);
1000 
1001   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1002   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1003   clear_upper_avx();
1004 
1005   return true;
1006 }
1007 
1008 //------------------------------inline_hasNegatives------------------------------
1009 bool LibraryCallKit::inline_hasNegatives() {
1010   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1011     return false;
1012   }
1013 
1014   assert(callee()->signature()->size() == 3, "hasNegatives has 3 parameters");
1015   // no receiver since it is static method
1016   Node* ba         = argument(0);
1017   Node* offset     = argument(1);
1018   Node* len        = argument(2);
1019 
1020   ba = must_be_not_null(ba, true);
1021 
1022   // Range checks
1023   generate_string_range_check(ba, offset, len, false);
1024   if (stopped()) {
1025     return true;
1026   }
1027   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1028   Node* result = new HasNegativesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1029   set_result(_gvn.transform(result));
1030   return true;
1031 }
1032 
1033 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1034   Node* index = argument(0);
1035   Node* length = bt == T_INT ? argument(1) : argument(2);
1036   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1037     return false;
1038   }
1039 
1040   // check that length is positive
1041   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1042   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1043 
1044   {
1045     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1046     uncommon_trap(Deoptimization::Reason_intrinsic,
1047                   Deoptimization::Action_make_not_entrant);
1048   }
1049 
1050   if (stopped()) {
1051     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1052     return true;
1053   }
1054 
1055   // length is now known postive, add a cast node to make this explicit
1056   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1057   Node* casted_length = ConstraintCastNode::make(control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt), bt);
1058   casted_length = _gvn.transform(casted_length);
1059   replace_in_map(length, casted_length);
1060   length = casted_length;
1061 
1062   // Use an unsigned comparison for the range check itself
1063   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1064   BoolTest::mask btest = BoolTest::lt;
1065   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1066   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1067   _gvn.set_type(rc, rc->Value(&_gvn));
1068   if (!rc_bool->is_Con()) {
1069     record_for_igvn(rc);
1070   }
1071   set_control(_gvn.transform(new IfTrueNode(rc)));
1072   {
1073     PreserveJVMState pjvms(this);
1074     set_control(_gvn.transform(new IfFalseNode(rc)));
1075     uncommon_trap(Deoptimization::Reason_range_check,
1076                   Deoptimization::Action_make_not_entrant);
1077   }
1078 
1079   if (stopped()) {
1080     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1081     return true;
1082   }
1083 
1084   // index is now known to be >= 0 and < length, cast it
1085   Node* result = ConstraintCastNode::make(control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt), bt);
1086   result = _gvn.transform(result);
1087   set_result(result);
1088   replace_in_map(index, result);
1089   clear_upper_avx();
1090   return true;
1091 }
1092 
1093 //------------------------------inline_string_indexOf------------------------
1094 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1095   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1096     return false;
1097   }
1098   Node* src = argument(0);
1099   Node* tgt = argument(1);
1100 
1101   // Make the merge point
1102   RegionNode* result_rgn = new RegionNode(4);
1103   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1104 
1105   src = must_be_not_null(src, true);
1106   tgt = must_be_not_null(tgt, true);
1107 
1108   // Get start addr and length of source string
1109   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1110   Node* src_count = load_array_length(src);
1111 
1112   // Get start addr and length of substring
1113   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1114   Node* tgt_count = load_array_length(tgt);
1115 
1116   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1117     // Divide src size by 2 if String is UTF16 encoded
1118     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1119   }
1120   if (ae == StrIntrinsicNode::UU) {
1121     // Divide substring size by 2 if String is UTF16 encoded
1122     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1123   }
1124 
1125   Node* result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count, result_rgn, result_phi, ae);
1126   if (result != NULL) {
1127     result_phi->init_req(3, result);
1128     result_rgn->init_req(3, control());
1129   }
1130   set_control(_gvn.transform(result_rgn));
1131   record_for_igvn(result_rgn);
1132   set_result(_gvn.transform(result_phi));
1133 
1134   return true;
1135 }
1136 
1137 //-----------------------------inline_string_indexOf-----------------------
1138 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1139   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1140     return false;
1141   }
1142   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1143     return false;
1144   }
1145   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1146   Node* src         = argument(0); // byte[]
1147   Node* src_count   = argument(1); // char count
1148   Node* tgt         = argument(2); // byte[]
1149   Node* tgt_count   = argument(3); // char count
1150   Node* from_index  = argument(4); // char index
1151 
1152   src = must_be_not_null(src, true);
1153   tgt = must_be_not_null(tgt, true);
1154 
1155   // Multiply byte array index by 2 if String is UTF16 encoded
1156   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1157   src_count = _gvn.transform(new SubINode(src_count, from_index));
1158   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1159   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1160 
1161   // Range checks
1162   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1163   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1164   if (stopped()) {
1165     return true;
1166   }
1167 
1168   RegionNode* region = new RegionNode(5);
1169   Node* phi = new PhiNode(region, TypeInt::INT);
1170 
1171   Node* result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count, region, phi, ae);
1172   if (result != NULL) {
1173     // The result is index relative to from_index if substring was found, -1 otherwise.
1174     // Generate code which will fold into cmove.
1175     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1176     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1177 
1178     Node* if_lt = generate_slow_guard(bol, NULL);
1179     if (if_lt != NULL) {
1180       // result == -1
1181       phi->init_req(3, result);
1182       region->init_req(3, if_lt);
1183     }
1184     if (!stopped()) {
1185       result = _gvn.transform(new AddINode(result, from_index));
1186       phi->init_req(4, result);
1187       region->init_req(4, control());
1188     }
1189   }
1190 
1191   set_control(_gvn.transform(region));
1192   record_for_igvn(region);
1193   set_result(_gvn.transform(phi));
1194   clear_upper_avx();
1195 
1196   return true;
1197 }
1198 
1199 // Create StrIndexOfNode with fast path checks
1200 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1201                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1202   // Check for substr count > string count
1203   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1204   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1205   Node* if_gt = generate_slow_guard(bol, NULL);
1206   if (if_gt != NULL) {
1207     phi->init_req(1, intcon(-1));
1208     region->init_req(1, if_gt);
1209   }
1210   if (!stopped()) {
1211     // Check for substr count == 0
1212     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1213     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1214     Node* if_zero = generate_slow_guard(bol, NULL);
1215     if (if_zero != NULL) {
1216       phi->init_req(2, intcon(0));
1217       region->init_req(2, if_zero);
1218     }
1219   }
1220   if (!stopped()) {
1221     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1222   }
1223   return NULL;
1224 }
1225 
1226 //-----------------------------inline_string_indexOfChar-----------------------
1227 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1228   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1229     return false;
1230   }
1231   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1232     return false;
1233   }
1234   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1235   Node* src         = argument(0); // byte[]
1236   Node* tgt         = argument(1); // tgt is int ch
1237   Node* from_index  = argument(2);
1238   Node* max         = argument(3);
1239 
1240   src = must_be_not_null(src, true);
1241 
1242   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1243   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1244   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1245 
1246   // Range checks
1247   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U);
1248   if (stopped()) {
1249     return true;
1250   }
1251 
1252   RegionNode* region = new RegionNode(3);
1253   Node* phi = new PhiNode(region, TypeInt::INT);
1254 
1255   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, tgt, ae);
1256   C->set_has_split_ifs(true); // Has chance for split-if optimization
1257   _gvn.transform(result);
1258 
1259   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1260   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1261 
1262   Node* if_lt = generate_slow_guard(bol, NULL);
1263   if (if_lt != NULL) {
1264     // result == -1
1265     phi->init_req(2, result);
1266     region->init_req(2, if_lt);
1267   }
1268   if (!stopped()) {
1269     result = _gvn.transform(new AddINode(result, from_index));
1270     phi->init_req(1, result);
1271     region->init_req(1, control());
1272   }
1273   set_control(_gvn.transform(region));
1274   record_for_igvn(region);
1275   set_result(_gvn.transform(phi));
1276 
1277   return true;
1278 }
1279 //---------------------------inline_string_copy---------------------
1280 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1281 //   int StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1282 //   int StringUTF16.compress(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1283 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1284 //   void StringLatin1.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1285 //   void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1286 bool LibraryCallKit::inline_string_copy(bool compress) {
1287   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1288     return false;
1289   }
1290   int nargs = 5;  // 2 oops, 3 ints
1291   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1292 
1293   Node* src         = argument(0);
1294   Node* src_offset  = argument(1);
1295   Node* dst         = argument(2);
1296   Node* dst_offset  = argument(3);
1297   Node* length      = argument(4);
1298 
1299   // Check for allocation before we add nodes that would confuse
1300   // tightly_coupled_allocation()
1301   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1302 
1303   // Figure out the size and type of the elements we will be copying.
1304   const Type* src_type = src->Value(&_gvn);
1305   const Type* dst_type = dst->Value(&_gvn);
1306   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
1307   BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
1308   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1309          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1310          "Unsupported array types for inline_string_copy");
1311 
1312   src = must_be_not_null(src, true);
1313   dst = must_be_not_null(dst, true);
1314 
1315   // Convert char[] offsets to byte[] offsets
1316   bool convert_src = (compress && src_elem == T_BYTE);
1317   bool convert_dst = (!compress && dst_elem == T_BYTE);
1318   if (convert_src) {
1319     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1320   } else if (convert_dst) {
1321     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1322   }
1323 
1324   // Range checks
1325   generate_string_range_check(src, src_offset, length, convert_src);
1326   generate_string_range_check(dst, dst_offset, length, convert_dst);
1327   if (stopped()) {
1328     return true;
1329   }
1330 
1331   Node* src_start = array_element_address(src, src_offset, src_elem);
1332   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1333   // 'src_start' points to src array + scaled offset
1334   // 'dst_start' points to dst array + scaled offset
1335   Node* count = NULL;
1336   if (compress) {
1337     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1338   } else {
1339     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1340   }
1341 
1342   if (alloc != NULL) {
1343     if (alloc->maybe_set_complete(&_gvn)) {
1344       // "You break it, you buy it."
1345       InitializeNode* init = alloc->initialization();
1346       assert(init->is_complete(), "we just did this");
1347       init->set_complete_with_arraycopy();
1348       assert(dst->is_CheckCastPP(), "sanity");
1349       assert(dst->in(0)->in(0) == init, "dest pinned");
1350     }
1351     // Do not let stores that initialize this object be reordered with
1352     // a subsequent store that would make this object accessible by
1353     // other threads.
1354     // Record what AllocateNode this StoreStore protects so that
1355     // escape analysis can go from the MemBarStoreStoreNode to the
1356     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1357     // based on the escape status of the AllocateNode.
1358     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1359   }
1360   if (compress) {
1361     set_result(_gvn.transform(count));
1362   }
1363   clear_upper_avx();
1364 
1365   return true;
1366 }
1367 
1368 #ifdef _LP64
1369 #define XTOP ,top() /*additional argument*/
1370 #else  //_LP64
1371 #define XTOP        /*no additional argument*/
1372 #endif //_LP64
1373 
1374 //------------------------inline_string_toBytesU--------------------------
1375 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
1376 bool LibraryCallKit::inline_string_toBytesU() {
1377   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1378     return false;
1379   }
1380   // Get the arguments.
1381   Node* value     = argument(0);
1382   Node* offset    = argument(1);
1383   Node* length    = argument(2);
1384 
1385   Node* newcopy = NULL;
1386 
1387   // Set the original stack and the reexecute bit for the interpreter to reexecute
1388   // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1389   { PreserveReexecuteState preexecs(this);
1390     jvms()->set_should_reexecute(true);
1391 
1392     // Check if a null path was taken unconditionally.
1393     value = null_check(value);
1394 
1395     RegionNode* bailout = new RegionNode(1);
1396     record_for_igvn(bailout);
1397 
1398     // Range checks
1399     generate_negative_guard(offset, bailout);
1400     generate_negative_guard(length, bailout);
1401     generate_limit_guard(offset, length, load_array_length(value), bailout);
1402     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1403     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1404 
1405     if (bailout->req() > 1) {
1406       PreserveJVMState pjvms(this);
1407       set_control(_gvn.transform(bailout));
1408       uncommon_trap(Deoptimization::Reason_intrinsic,
1409                     Deoptimization::Action_maybe_recompile);
1410     }
1411     if (stopped()) {
1412       return true;
1413     }
1414 
1415     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1416     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1417     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1418     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1419     guarantee(alloc != NULL, "created above");
1420 
1421     // Calculate starting addresses.
1422     Node* src_start = array_element_address(value, offset, T_CHAR);
1423     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1424 
1425     // Check if src array address is aligned to HeapWordSize (dst is always aligned)
1426     const TypeInt* toffset = gvn().type(offset)->is_int();
1427     bool aligned = toffset->is_con() && ((toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1428 
1429     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1430     const char* copyfunc_name = "arraycopy";
1431     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1432     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1433                       OptoRuntime::fast_arraycopy_Type(),
1434                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1435                       src_start, dst_start, ConvI2X(length) XTOP);
1436     // Do not let reads from the cloned object float above the arraycopy.
1437     if (alloc->maybe_set_complete(&_gvn)) {
1438       // "You break it, you buy it."
1439       InitializeNode* init = alloc->initialization();
1440       assert(init->is_complete(), "we just did this");
1441       init->set_complete_with_arraycopy();
1442       assert(newcopy->is_CheckCastPP(), "sanity");
1443       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1444     }
1445     // Do not let stores that initialize this object be reordered with
1446     // a subsequent store that would make this object accessible by
1447     // other threads.
1448     // Record what AllocateNode this StoreStore protects so that
1449     // escape analysis can go from the MemBarStoreStoreNode to the
1450     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1451     // based on the escape status of the AllocateNode.
1452     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1453   } // original reexecute is set back here
1454 
1455   C->set_has_split_ifs(true); // Has chance for split-if optimization
1456   if (!stopped()) {
1457     set_result(newcopy);
1458   }
1459   clear_upper_avx();
1460 
1461   return true;
1462 }
1463 
1464 //------------------------inline_string_getCharsU--------------------------
1465 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1466 bool LibraryCallKit::inline_string_getCharsU() {
1467   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1468     return false;
1469   }
1470 
1471   // Get the arguments.
1472   Node* src       = argument(0);
1473   Node* src_begin = argument(1);
1474   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1475   Node* dst       = argument(3);
1476   Node* dst_begin = argument(4);
1477 
1478   // Check for allocation before we add nodes that would confuse
1479   // tightly_coupled_allocation()
1480   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1481 
1482   // Check if a null path was taken unconditionally.
1483   src = null_check(src);
1484   dst = null_check(dst);
1485   if (stopped()) {
1486     return true;
1487   }
1488 
1489   // Get length and convert char[] offset to byte[] offset
1490   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1491   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1492 
1493   // Range checks
1494   generate_string_range_check(src, src_begin, length, true);
1495   generate_string_range_check(dst, dst_begin, length, false);
1496   if (stopped()) {
1497     return true;
1498   }
1499 
1500   if (!stopped()) {
1501     // Calculate starting addresses.
1502     Node* src_start = array_element_address(src, src_begin, T_BYTE);
1503     Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1504 
1505     // Check if array addresses are aligned to HeapWordSize
1506     const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1507     const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1508     bool aligned = tsrc->is_con() && ((tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1509                    tdst->is_con() && ((tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1510 
1511     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1512     const char* copyfunc_name = "arraycopy";
1513     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1514     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1515                       OptoRuntime::fast_arraycopy_Type(),
1516                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1517                       src_start, dst_start, ConvI2X(length) XTOP);
1518     // Do not let reads from the cloned object float above the arraycopy.
1519     if (alloc != NULL) {
1520       if (alloc->maybe_set_complete(&_gvn)) {
1521         // "You break it, you buy it."
1522         InitializeNode* init = alloc->initialization();
1523         assert(init->is_complete(), "we just did this");
1524         init->set_complete_with_arraycopy();
1525         assert(dst->is_CheckCastPP(), "sanity");
1526         assert(dst->in(0)->in(0) == init, "dest pinned");
1527       }
1528       // Do not let stores that initialize this object be reordered with
1529       // a subsequent store that would make this object accessible by
1530       // other threads.
1531       // Record what AllocateNode this StoreStore protects so that
1532       // escape analysis can go from the MemBarStoreStoreNode to the
1533       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1534       // based on the escape status of the AllocateNode.
1535       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1536     } else {
1537       insert_mem_bar(Op_MemBarCPUOrder);
1538     }
1539   }
1540 
1541   C->set_has_split_ifs(true); // Has chance for split-if optimization
1542   return true;
1543 }
1544 
1545 //----------------------inline_string_char_access----------------------------
1546 // Store/Load char to/from byte[] array.
1547 // static void StringUTF16.putChar(byte[] val, int index, int c)
1548 // static char StringUTF16.getChar(byte[] val, int index)
1549 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1550   Node* value  = argument(0);
1551   Node* index  = argument(1);
1552   Node* ch = is_store ? argument(2) : NULL;
1553 
1554   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1555   // correctly requires matched array shapes.
1556   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1557           "sanity: byte[] and char[] bases agree");
1558   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1559           "sanity: byte[] and char[] scales agree");
1560 
1561   // Bail when getChar over constants is requested: constant folding would
1562   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1563   // Java method would constant fold nicely instead.
1564   if (!is_store && value->is_Con() && index->is_Con()) {
1565     return false;
1566   }
1567 
1568   value = must_be_not_null(value, true);
1569 
1570   Node* adr = array_element_address(value, index, T_CHAR);
1571   if (adr->is_top()) {
1572     return false;
1573   }
1574   if (is_store) {
1575     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1576   } else {
1577     ch = access_load_at(value, adr, TypeAryPtr::BYTES, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
1578     set_result(ch);
1579   }
1580   return true;
1581 }
1582 
1583 //--------------------------round_double_node--------------------------------
1584 // Round a double node if necessary.
1585 Node* LibraryCallKit::round_double_node(Node* n) {
1586   if (Matcher::strict_fp_requires_explicit_rounding) {
1587 #ifdef IA32
1588     if (UseSSE < 2) {
1589       n = _gvn.transform(new RoundDoubleNode(NULL, n));
1590     }
1591 #else
1592     Unimplemented();
1593 #endif // IA32
1594   }
1595   return n;
1596 }
1597 
1598 //------------------------------inline_math-----------------------------------
1599 // public static double Math.abs(double)
1600 // public static double Math.sqrt(double)
1601 // public static double Math.log(double)
1602 // public static double Math.log10(double)
1603 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1604   Node* arg = round_double_node(argument(0));
1605   Node* n = NULL;
1606   switch (id) {
1607   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1608   case vmIntrinsics::_dsqrt:  n = new SqrtDNode(C, control(),  arg);  break;
1609   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1610   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1611   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1612   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, round_double_node(argument(2))); break;
1613   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1614   default:  fatal_unexpected_iid(id);  break;
1615   }
1616   set_result(_gvn.transform(n));
1617   return true;
1618 }
1619 
1620 //------------------------------inline_math-----------------------------------
1621 // public static float Math.abs(float)
1622 // public static int Math.abs(int)
1623 // public static long Math.abs(long)
1624 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1625   Node* arg = argument(0);
1626   Node* n = NULL;
1627   switch (id) {
1628   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1629   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1630   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1631   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1632   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1633   default:  fatal_unexpected_iid(id);  break;
1634   }
1635   set_result(_gvn.transform(n));
1636   return true;
1637 }
1638 
1639 //------------------------------runtime_math-----------------------------
1640 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1641   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1642          "must be (DD)D or (D)D type");
1643 
1644   // Inputs
1645   Node* a = round_double_node(argument(0));
1646   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? round_double_node(argument(2)) : NULL;
1647 
1648   const TypePtr* no_memory_effects = NULL;
1649   Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
1650                                  no_memory_effects,
1651                                  a, top(), b, b ? top() : NULL);
1652   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1653 #ifdef ASSERT
1654   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1655   assert(value_top == top(), "second value must be top");
1656 #endif
1657 
1658   set_result(value);
1659   return true;
1660 }
1661 
1662 //------------------------------inline_math_pow-----------------------------
1663 bool LibraryCallKit::inline_math_pow() {
1664   Node* exp = round_double_node(argument(2));
1665   const TypeD* d = _gvn.type(exp)->isa_double_constant();
1666   if (d != NULL) {
1667     if (d->getd() == 2.0) {
1668       // Special case: pow(x, 2.0) => x * x
1669       Node* base = round_double_node(argument(0));
1670       set_result(_gvn.transform(new MulDNode(base, base)));
1671       return true;
1672     } else if (d->getd() == 0.5 && Matcher::match_rule_supported(Op_SqrtD)) {
1673       // Special case: pow(x, 0.5) => sqrt(x)
1674       Node* base = round_double_node(argument(0));
1675       Node* zero = _gvn.zerocon(T_DOUBLE);
1676 
1677       RegionNode* region = new RegionNode(3);
1678       Node* phi = new PhiNode(region, Type::DOUBLE);
1679 
1680       Node* cmp  = _gvn.transform(new CmpDNode(base, zero));
1681       // According to the API specs, pow(-0.0, 0.5) = 0.0 and sqrt(-0.0) = -0.0.
1682       // So pow(-0.0, 0.5) shouldn't be replaced with sqrt(-0.0).
1683       // -0.0/+0.0 are both excluded since floating-point comparison doesn't distinguish -0.0 from +0.0.
1684       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1685 
1686       Node* if_pow = generate_slow_guard(test, NULL);
1687       Node* value_sqrt = _gvn.transform(new SqrtDNode(C, control(), base));
1688       phi->init_req(1, value_sqrt);
1689       region->init_req(1, control());
1690 
1691       if (if_pow != NULL) {
1692         set_control(if_pow);
1693         address target = StubRoutines::dpow() != NULL ? StubRoutines::dpow() :
1694                                                         CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
1695         const TypePtr* no_memory_effects = NULL;
1696         Node* trig = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(), target, "POW",
1697                                        no_memory_effects, base, top(), exp, top());
1698         Node* value_pow = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1699 #ifdef ASSERT
1700         Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1701         assert(value_top == top(), "second value must be top");
1702 #endif
1703         phi->init_req(2, value_pow);
1704         region->init_req(2, _gvn.transform(new ProjNode(trig, TypeFunc::Control)));
1705       }
1706 
1707       C->set_has_split_ifs(true); // Has chance for split-if optimization
1708       set_control(_gvn.transform(region));
1709       record_for_igvn(region);
1710       set_result(_gvn.transform(phi));
1711 
1712       return true;
1713     }
1714   }
1715 
1716   return StubRoutines::dpow() != NULL ?
1717     runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(),  "dpow") :
1718     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow),  "POW");
1719 }
1720 
1721 //------------------------------inline_math_native-----------------------------
1722 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1723 #define FN_PTR(f) CAST_FROM_FN_PTR(address, f)
1724   switch (id) {
1725     // These intrinsics are not properly supported on all hardware
1726   case vmIntrinsics::_dsin:
1727     return StubRoutines::dsin() != NULL ?
1728       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1729       runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dsin),   "SIN");
1730   case vmIntrinsics::_dcos:
1731     return StubRoutines::dcos() != NULL ?
1732       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1733       runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dcos),   "COS");
1734   case vmIntrinsics::_dtan:
1735     return StubRoutines::dtan() != NULL ?
1736       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1737       runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dtan), "TAN");
1738   case vmIntrinsics::_dlog:
1739     return StubRoutines::dlog() != NULL ?
1740       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1741       runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog),   "LOG");
1742   case vmIntrinsics::_dlog10:
1743     return StubRoutines::dlog10() != NULL ?
1744       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1745       runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog10), "LOG10");
1746 
1747     // These intrinsics are supported on all hardware
1748   case vmIntrinsics::_ceil:
1749   case vmIntrinsics::_floor:
1750   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1751   case vmIntrinsics::_dsqrt:  return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1752   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1753   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1754   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1755   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1756 
1757   case vmIntrinsics::_dexp:
1758     return StubRoutines::dexp() != NULL ?
1759       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1760       runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dexp),  "EXP");
1761 #undef FN_PTR
1762 
1763   case vmIntrinsics::_dpow:      return inline_math_pow();
1764   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1765   case vmIntrinsics::_fcopySign: return inline_math(id);
1766   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1767   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1768 
1769    // These intrinsics are not yet correctly implemented
1770   case vmIntrinsics::_datan2:
1771     return false;
1772 
1773   default:
1774     fatal_unexpected_iid(id);
1775     return false;
1776   }
1777 }
1778 
1779 static bool is_simple_name(Node* n) {
1780   return (n->req() == 1         // constant
1781           || (n->is_Type() && n->as_Type()->type()->singleton())
1782           || n->is_Proj()       // parameter or return value
1783           || n->is_Phi()        // local of some sort
1784           );
1785 }
1786 
1787 //----------------------------inline_notify-----------------------------------*
1788 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1789   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1790   address func;
1791   if (id == vmIntrinsics::_notify) {
1792     func = OptoRuntime::monitor_notify_Java();
1793   } else {
1794     func = OptoRuntime::monitor_notifyAll_Java();
1795   }
1796   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, NULL, TypeRawPtr::BOTTOM, argument(0));
1797   make_slow_call_ex(call, env()->Throwable_klass(), false);
1798   return true;
1799 }
1800 
1801 
1802 //----------------------------inline_min_max-----------------------------------
1803 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1804   set_result(generate_min_max(id, argument(0), argument(1)));
1805   return true;
1806 }
1807 
1808 void LibraryCallKit::inline_math_mathExact(Node* math, Node *test) {
1809   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
1810   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
1811   Node* fast_path = _gvn.transform( new IfFalseNode(check));
1812   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
1813 
1814   {
1815     PreserveJVMState pjvms(this);
1816     PreserveReexecuteState preexecs(this);
1817     jvms()->set_should_reexecute(true);
1818 
1819     set_control(slow_path);
1820     set_i_o(i_o());
1821 
1822     uncommon_trap(Deoptimization::Reason_intrinsic,
1823                   Deoptimization::Action_none);
1824   }
1825 
1826   set_control(fast_path);
1827   set_result(math);
1828 }
1829 
1830 template <typename OverflowOp>
1831 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
1832   typedef typename OverflowOp::MathOp MathOp;
1833 
1834   MathOp* mathOp = new MathOp(arg1, arg2);
1835   Node* operation = _gvn.transform( mathOp );
1836   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
1837   inline_math_mathExact(operation, ofcheck);
1838   return true;
1839 }
1840 
1841 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
1842   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
1843 }
1844 
1845 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
1846   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
1847 }
1848 
1849 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
1850   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
1851 }
1852 
1853 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
1854   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
1855 }
1856 
1857 bool LibraryCallKit::inline_math_negateExactI() {
1858   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
1859 }
1860 
1861 bool LibraryCallKit::inline_math_negateExactL() {
1862   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
1863 }
1864 
1865 bool LibraryCallKit::inline_math_multiplyExactI() {
1866   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
1867 }
1868 
1869 bool LibraryCallKit::inline_math_multiplyExactL() {
1870   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
1871 }
1872 
1873 bool LibraryCallKit::inline_math_multiplyHigh() {
1874   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
1875   return true;
1876 }
1877 
1878 Node*
1879 LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {
1880   // These are the candidate return value:
1881   Node* xvalue = x0;
1882   Node* yvalue = y0;
1883 
1884   if (xvalue == yvalue) {
1885     return xvalue;
1886   }
1887 
1888   bool want_max = (id == vmIntrinsics::_max);
1889 
1890   const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();
1891   const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();
1892   if (txvalue == NULL || tyvalue == NULL)  return top();
1893   // This is not really necessary, but it is consistent with a
1894   // hypothetical MaxINode::Value method:
1895   int widen = MAX2(txvalue->_widen, tyvalue->_widen);
1896 
1897   // %%% This folding logic should (ideally) be in a different place.
1898   // Some should be inside IfNode, and there to be a more reliable
1899   // transformation of ?: style patterns into cmoves.  We also want
1900   // more powerful optimizations around cmove and min/max.
1901 
1902   // Try to find a dominating comparison of these guys.
1903   // It can simplify the index computation for Arrays.copyOf
1904   // and similar uses of System.arraycopy.
1905   // First, compute the normalized version of CmpI(x, y).
1906   int   cmp_op = Op_CmpI;
1907   Node* xkey = xvalue;
1908   Node* ykey = yvalue;
1909   Node* ideal_cmpxy = _gvn.transform(new CmpINode(xkey, ykey));
1910   if (ideal_cmpxy->is_Cmp()) {
1911     // E.g., if we have CmpI(length - offset, count),
1912     // it might idealize to CmpI(length, count + offset)
1913     cmp_op = ideal_cmpxy->Opcode();
1914     xkey = ideal_cmpxy->in(1);
1915     ykey = ideal_cmpxy->in(2);
1916   }
1917 
1918   // Start by locating any relevant comparisons.
1919   Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;
1920   Node* cmpxy = NULL;
1921   Node* cmpyx = NULL;
1922   for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {
1923     Node* cmp = start_from->fast_out(k);
1924     if (cmp->outcnt() > 0 &&            // must have prior uses
1925         cmp->in(0) == NULL &&           // must be context-independent
1926         cmp->Opcode() == cmp_op) {      // right kind of compare
1927       if (cmp->in(1) == xkey && cmp->in(2) == ykey)  cmpxy = cmp;
1928       if (cmp->in(1) == ykey && cmp->in(2) == xkey)  cmpyx = cmp;
1929     }
1930   }
1931 
1932   const int NCMPS = 2;
1933   Node* cmps[NCMPS] = { cmpxy, cmpyx };
1934   int cmpn;
1935   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
1936     if (cmps[cmpn] != NULL)  break;     // find a result
1937   }
1938   if (cmpn < NCMPS) {
1939     // Look for a dominating test that tells us the min and max.
1940     int depth = 0;                // Limit search depth for speed
1941     Node* dom = control();
1942     for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {
1943       if (++depth >= 100)  break;
1944       Node* ifproj = dom;
1945       if (!ifproj->is_Proj())  continue;
1946       Node* iff = ifproj->in(0);
1947       if (!iff->is_If())  continue;
1948       Node* bol = iff->in(1);
1949       if (!bol->is_Bool())  continue;
1950       Node* cmp = bol->in(1);
1951       if (cmp == NULL)  continue;
1952       for (cmpn = 0; cmpn < NCMPS; cmpn++)
1953         if (cmps[cmpn] == cmp)  break;
1954       if (cmpn == NCMPS)  continue;
1955       BoolTest::mask btest = bol->as_Bool()->_test._test;
1956       if (ifproj->is_IfFalse())  btest = BoolTest(btest).negate();
1957       if (cmp->in(1) == ykey)    btest = BoolTest(btest).commute();
1958       // At this point, we know that 'x btest y' is true.
1959       switch (btest) {
1960       case BoolTest::eq:
1961         // They are proven equal, so we can collapse the min/max.
1962         // Either value is the answer.  Choose the simpler.
1963         if (is_simple_name(yvalue) && !is_simple_name(xvalue))
1964           return yvalue;
1965         return xvalue;
1966       case BoolTest::lt:          // x < y
1967       case BoolTest::le:          // x <= y
1968         return (want_max ? yvalue : xvalue);
1969       case BoolTest::gt:          // x > y
1970       case BoolTest::ge:          // x >= y
1971         return (want_max ? xvalue : yvalue);
1972       default:
1973         break;
1974       }
1975     }
1976   }
1977 
1978   // We failed to find a dominating test.
1979   // Let's pick a test that might GVN with prior tests.
1980   Node*          best_bol   = NULL;
1981   BoolTest::mask best_btest = BoolTest::illegal;
1982   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
1983     Node* cmp = cmps[cmpn];
1984     if (cmp == NULL)  continue;
1985     for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {
1986       Node* bol = cmp->fast_out(j);
1987       if (!bol->is_Bool())  continue;
1988       BoolTest::mask btest = bol->as_Bool()->_test._test;
1989       if (btest == BoolTest::eq || btest == BoolTest::ne)  continue;
1990       if (cmp->in(1) == ykey)   btest = BoolTest(btest).commute();
1991       if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {
1992         best_bol   = bol->as_Bool();
1993         best_btest = btest;
1994       }
1995     }
1996   }
1997 
1998   Node* answer_if_true  = NULL;
1999   Node* answer_if_false = NULL;
2000   switch (best_btest) {
2001   default:
2002     if (cmpxy == NULL)
2003       cmpxy = ideal_cmpxy;
2004     best_bol = _gvn.transform(new BoolNode(cmpxy, BoolTest::lt));
2005     // and fall through:
2006   case BoolTest::lt:          // x < y
2007   case BoolTest::le:          // x <= y
2008     answer_if_true  = (want_max ? yvalue : xvalue);
2009     answer_if_false = (want_max ? xvalue : yvalue);
2010     break;
2011   case BoolTest::gt:          // x > y
2012   case BoolTest::ge:          // x >= y
2013     answer_if_true  = (want_max ? xvalue : yvalue);
2014     answer_if_false = (want_max ? yvalue : xvalue);
2015     break;
2016   }
2017 
2018   jint hi, lo;
2019   if (want_max) {
2020     // We can sharpen the minimum.
2021     hi = MAX2(txvalue->_hi, tyvalue->_hi);
2022     lo = MAX2(txvalue->_lo, tyvalue->_lo);
2023   } else {
2024     // We can sharpen the maximum.
2025     hi = MIN2(txvalue->_hi, tyvalue->_hi);
2026     lo = MIN2(txvalue->_lo, tyvalue->_lo);
2027   }
2028 
2029   // Use a flow-free graph structure, to avoid creating excess control edges
2030   // which could hinder other optimizations.
2031   // Since Math.min/max is often used with arraycopy, we want
2032   // tightly_coupled_allocation to be able to see beyond min/max expressions.
2033   Node* cmov = CMoveNode::make(NULL, best_bol,
2034                                answer_if_false, answer_if_true,
2035                                TypeInt::make(lo, hi, widen));
2036 
2037   return _gvn.transform(cmov);
2038 
2039   /*
2040   // This is not as desirable as it may seem, since Min and Max
2041   // nodes do not have a full set of optimizations.
2042   // And they would interfere, anyway, with 'if' optimizations
2043   // and with CMoveI canonical forms.
2044   switch (id) {
2045   case vmIntrinsics::_min:
2046     result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;
2047   case vmIntrinsics::_max:
2048     result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;
2049   default:
2050     ShouldNotReachHere();
2051   }
2052   */
2053 }
2054 
2055 inline int
2056 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2057   const TypePtr* base_type = TypePtr::NULL_PTR;
2058   if (base != NULL)  base_type = _gvn.type(base)->isa_ptr();
2059   if (base_type == NULL) {
2060     // Unknown type.
2061     return Type::AnyPtr;
2062   } else if (base_type == TypePtr::NULL_PTR) {
2063     // Since this is a NULL+long form, we have to switch to a rawptr.
2064     base   = _gvn.transform(new CastX2PNode(offset));
2065     offset = MakeConX(0);
2066     return Type::RawPtr;
2067   } else if (base_type->base() == Type::RawPtr) {
2068     return Type::RawPtr;
2069   } else if (base_type->isa_oopptr()) {
2070     // Base is never null => always a heap address.
2071     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2072       return Type::OopPtr;
2073     }
2074     // Offset is small => always a heap address.
2075     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2076     if (offset_type != NULL &&
2077         base_type->offset() == 0 &&     // (should always be?)
2078         offset_type->_lo >= 0 &&
2079         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2080       return Type::OopPtr;
2081     } else if (type == T_OBJECT) {
2082       // off heap access to an oop doesn't make any sense. Has to be on
2083       // heap.
2084       return Type::OopPtr;
2085     }
2086     // Otherwise, it might either be oop+off or NULL+addr.
2087     return Type::AnyPtr;
2088   } else {
2089     // No information:
2090     return Type::AnyPtr;
2091   }
2092 }
2093 
2094 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2095   Node* uncasted_base = base;
2096   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2097   if (kind == Type::RawPtr) {
2098     return basic_plus_adr(top(), uncasted_base, offset);
2099   } else if (kind == Type::AnyPtr) {
2100     assert(base == uncasted_base, "unexpected base change");
2101     if (can_cast) {
2102       if (!_gvn.type(base)->speculative_maybe_null() &&
2103           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2104         // According to profiling, this access is always on
2105         // heap. Casting the base to not null and thus avoiding membars
2106         // around the access should allow better optimizations
2107         Node* null_ctl = top();
2108         base = null_check_oop(base, &null_ctl, true, true, true);
2109         assert(null_ctl->is_top(), "no null control here");
2110         return basic_plus_adr(base, offset);
2111       } else if (_gvn.type(base)->speculative_always_null() &&
2112                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2113         // According to profiling, this access is always off
2114         // heap.
2115         base = null_assert(base);
2116         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2117         offset = MakeConX(0);
2118         return basic_plus_adr(top(), raw_base, offset);
2119       }
2120     }
2121     // We don't know if it's an on heap or off heap access. Fall back
2122     // to raw memory access.
2123     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2124     return basic_plus_adr(top(), raw, offset);
2125   } else {
2126     assert(base == uncasted_base, "unexpected base change");
2127     // We know it's an on heap access so base can't be null
2128     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2129       base = must_be_not_null(base, true);
2130     }
2131     return basic_plus_adr(base, offset);
2132   }
2133 }
2134 
2135 //--------------------------inline_number_methods-----------------------------
2136 // inline int     Integer.numberOfLeadingZeros(int)
2137 // inline int        Long.numberOfLeadingZeros(long)
2138 //
2139 // inline int     Integer.numberOfTrailingZeros(int)
2140 // inline int        Long.numberOfTrailingZeros(long)
2141 //
2142 // inline int     Integer.bitCount(int)
2143 // inline int        Long.bitCount(long)
2144 //
2145 // inline char  Character.reverseBytes(char)
2146 // inline short     Short.reverseBytes(short)
2147 // inline int     Integer.reverseBytes(int)
2148 // inline long       Long.reverseBytes(long)
2149 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2150   Node* arg = argument(0);
2151   Node* n = NULL;
2152   switch (id) {
2153   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg);  break;
2154   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg);  break;
2155   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg);  break;
2156   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg);  break;
2157   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg);  break;
2158   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg);  break;
2159   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(0,   arg);  break;
2160   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode( 0,   arg);  break;
2161   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode( 0,   arg);  break;
2162   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode( 0,   arg);  break;
2163   default:  fatal_unexpected_iid(id);  break;
2164   }
2165   set_result(_gvn.transform(n));
2166   return true;
2167 }
2168 
2169 //----------------------------inline_unsafe_access----------------------------
2170 
2171 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2172   // Attempt to infer a sharper value type from the offset and base type.
2173   ciKlass* sharpened_klass = NULL;
2174   bool null_free = false;
2175 
2176   // See if it is an instance field, with an object type.
2177   if (alias_type->field() != NULL) {
2178     if (alias_type->field()->type()->is_klass()) {
2179       sharpened_klass = alias_type->field()->type()->as_klass();
2180       null_free = alias_type->field()->is_null_free();
2181     }
2182   }
2183 
2184   // See if it is a narrow oop array.
2185   if (adr_type->isa_aryptr()) {
2186     if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2187       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2188       null_free = adr_type->is_aryptr()->is_null_free();
2189       if (elem_type != NULL) {
2190         sharpened_klass = elem_type->klass();
2191       }
2192     }
2193   }
2194 
2195   // The sharpened class might be unloaded if there is no class loader
2196   // contraint in place.
2197   if (sharpened_klass != NULL && sharpened_klass->is_loaded()) {
2198     const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);
2199     if (null_free) {
2200       tjp = tjp->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2201     }
2202 
2203 #ifndef PRODUCT
2204     if (C->print_intrinsics() || C->print_inlining()) {
2205       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2206       tty->print("  sharpened value: ");  tjp->dump();      tty->cr();
2207     }
2208 #endif
2209     // Sharpen the value type.
2210     return tjp;
2211   }
2212   return NULL;
2213 }
2214 
2215 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2216   switch (kind) {
2217       case Relaxed:
2218         return MO_UNORDERED;
2219       case Opaque:
2220         return MO_RELAXED;
2221       case Acquire:
2222         return MO_ACQUIRE;
2223       case Release:
2224         return MO_RELEASE;
2225       case Volatile:
2226         return MO_SEQ_CST;
2227       default:
2228         ShouldNotReachHere();
2229         return 0;
2230   }
2231 }
2232 
2233 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2234   if (callee()->is_static())  return false;  // caller must have the capability!
2235   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2236   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2237   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2238   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2239 
2240   if (is_reference_type(type)) {
2241     decorators |= ON_UNKNOWN_OOP_REF;
2242   }
2243 
2244   if (unaligned) {
2245     decorators |= C2_UNALIGNED;
2246   }
2247 
2248 #ifndef PRODUCT
2249   {
2250     ResourceMark rm;
2251     // Check the signatures.
2252     ciSignature* sig = callee()->signature();
2253 #ifdef ASSERT
2254     if (!is_store) {
2255       // Object getReference(Object base, int/long offset), etc.
2256       BasicType rtype = sig->return_type()->basic_type();
2257       assert(rtype == type || (rtype == T_OBJECT && type == T_INLINE_TYPE), "getter must return the expected value");
2258       assert(sig->count() == 2 || (type == T_INLINE_TYPE && sig->count() == 3), "oop getter has 2 or 3 arguments");
2259       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2260       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2261     } else {
2262       // void putReference(Object base, int/long offset, Object x), etc.
2263       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2264       assert(sig->count() == 3 || (type == T_INLINE_TYPE && sig->count() == 4), "oop putter has 3 arguments");
2265       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2266       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2267       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2268       assert(vtype == type || (type == T_INLINE_TYPE && vtype == T_OBJECT), "putter must accept the expected value");
2269     }
2270 #endif // ASSERT
2271  }
2272 #endif //PRODUCT
2273 
2274   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2275 
2276   Node* receiver = argument(0);  // type: oop
2277 
2278   // Build address expression.
2279   Node* heap_base_oop = top();
2280 
2281   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2282   Node* base = argument(1);  // type: oop
2283   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2284   Node* offset = argument(2);  // type: long
2285   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2286   // to be plain byte offsets, which are also the same as those accepted
2287   // by oopDesc::field_addr.
2288   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2289          "fieldOffset must be byte-scaled");
2290 
2291   ciInlineKlass* inline_klass = NULL;
2292   if (type == T_INLINE_TYPE) {
2293     const TypeInstPtr* cls = _gvn.type(argument(4))->isa_instptr();
2294     if (cls == NULL || cls->const_oop() == NULL) {
2295       return false;
2296     }
2297     ciType* mirror_type = cls->const_oop()->as_instance()->java_mirror_type();
2298     if (!mirror_type->is_inlinetype()) {
2299       return false;
2300     }
2301     inline_klass = mirror_type->as_inline_klass();
2302   }
2303 
2304   if (base->is_InlineTypeBase()) {
2305     InlineTypeBaseNode* vt = base->as_InlineTypeBase();
2306     if (is_store) {
2307       if (!vt->is_allocated(&_gvn) || !_gvn.type(vt)->isa_inlinetype() || !_gvn.type(vt)->is_inlinetype()->larval()) {
2308         return false;
2309       }
2310       base = vt->get_oop();
2311     } else {
2312       if (offset->is_Con()) {
2313         long off = find_long_con(offset, 0);
2314         ciInlineKlass* vk = vt->type()->inline_klass();
2315         if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2316           return false;
2317         }
2318 
2319         ciField* field = vk->get_non_flattened_field_by_offset(off);
2320         if (field != NULL) {
2321           BasicType bt = field->layout_type();
2322           if (bt == T_ARRAY || bt == T_NARROWOOP || (bt == T_INLINE_TYPE && !field->is_flattened())) {
2323             bt = T_OBJECT;
2324           }
2325           if (bt == type && (bt != T_INLINE_TYPE || field->type() == inline_klass)) {
2326             set_result(vt->field_value_by_offset(off, false));
2327             return true;
2328           }
2329         }
2330       }
2331       if (vt->is_InlineType()) {
2332         // Re-execute the unsafe access if allocation triggers deoptimization.
2333         PreserveReexecuteState preexecs(this);
2334         jvms()->set_should_reexecute(true);
2335         vt = vt->buffer(this);
2336       }
2337       base = vt->get_oop();
2338     }
2339   }
2340 
2341   // 32-bit machines ignore the high half!
2342   offset = ConvL2X(offset);
2343 
2344   // Save state and restore on bailout
2345   uint old_sp = sp();
2346   SafePointNode* old_map = clone_map();
2347 
2348   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2349 
2350   if (_gvn.type(base)->isa_ptr() == TypePtr::NULL_PTR) {
2351     if (type != T_OBJECT && (inline_klass == NULL || !inline_klass->has_object_fields())) {
2352       decorators |= IN_NATIVE; // off-heap primitive access
2353     } else {
2354       set_map(old_map);
2355       set_sp(old_sp);
2356       return false; // off-heap oop accesses are not supported
2357     }
2358   } else {
2359     heap_base_oop = base; // on-heap or mixed access
2360   }
2361 
2362   // Can base be NULL? Otherwise, always on-heap access.
2363   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2364 
2365   if (!can_access_non_heap) {
2366     decorators |= IN_HEAP;
2367   }
2368 
2369   Node* val = is_store ? argument(4 + (type == T_INLINE_TYPE ? 1 : 0)) : NULL;
2370 
2371   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2372   if (adr_type == TypePtr::NULL_PTR) {
2373     set_map(old_map);
2374     set_sp(old_sp);
2375     return false; // off-heap access with zero address
2376   }
2377 
2378   // Try to categorize the address.
2379   Compile::AliasType* alias_type = C->alias_type(adr_type);
2380   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2381 
2382   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2383       alias_type->adr_type() == TypeAryPtr::RANGE) {
2384     set_map(old_map);
2385     set_sp(old_sp);
2386     return false; // not supported
2387   }
2388 
2389   bool mismatched = false;
2390   BasicType bt = T_ILLEGAL;
2391   ciField* field = NULL;
2392   if (adr_type->isa_instptr()) {
2393     const TypeInstPtr* instptr = adr_type->is_instptr();
2394     ciInstanceKlass* k = instptr->klass()->as_instance_klass();
2395     int off = instptr->offset();
2396     if (instptr->const_oop() != NULL &&
2397         instptr->klass() == ciEnv::current()->Class_klass() &&
2398         instptr->offset() >= (instptr->klass()->as_instance_klass()->size_helper() * wordSize)) {
2399       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2400       field = k->get_field_by_offset(off, true);
2401     } else {
2402       field = k->get_non_flattened_field_by_offset(off);
2403     }
2404     if (field != NULL) {
2405       bt = field->layout_type();
2406     }
2407     assert(bt == alias_type->basic_type() || bt == T_INLINE_TYPE, "should match");
2408     if (field != NULL && bt == T_INLINE_TYPE && !field->is_flattened()) {
2409       bt = T_OBJECT;
2410     }
2411   } else {
2412     bt = alias_type->basic_type();
2413   }
2414 
2415   if (bt != T_ILLEGAL) {
2416     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2417     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2418       // Alias type doesn't differentiate between byte[] and boolean[]).
2419       // Use address type to get the element type.
2420       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2421     }
2422     if (bt == T_ARRAY || bt == T_NARROWOOP) {
2423       // accessing an array field with getReference is not a mismatch
2424       bt = T_OBJECT;
2425     }
2426     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2427       // Don't intrinsify mismatched object accesses
2428       set_map(old_map);
2429       set_sp(old_sp);
2430       return false;
2431     }
2432     mismatched = (bt != type);
2433   } else if (alias_type->adr_type()->isa_oopptr()) {
2434     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2435   }
2436 
2437   if (type == T_INLINE_TYPE) {
2438     if (adr_type->isa_instptr()) {
2439       if (field == NULL || field->type() != inline_klass) {
2440         mismatched = true;
2441       }
2442     } else if (adr_type->isa_aryptr()) {
2443       const Type* elem = adr_type->is_aryptr()->elem();
2444       if (!elem->isa_inlinetype()) {
2445         mismatched = true;
2446       } else if (elem->inline_klass() != inline_klass) {
2447         mismatched = true;
2448       }
2449     } else {
2450       mismatched = true;
2451     }
2452     if (is_store) {
2453       const Type* val_t = _gvn.type(val);
2454       if (!val_t->isa_inlinetype() || val_t->inline_klass() != inline_klass) {
2455         set_map(old_map);
2456         set_sp(old_sp);
2457         return false;
2458       }
2459     }
2460   }
2461 
2462   old_map->destruct(&_gvn);
2463   assert(!mismatched || type == T_INLINE_TYPE || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2464 
2465   if (mismatched) {
2466     decorators |= C2_MISMATCHED;
2467   }
2468 
2469   // First guess at the value type.
2470   const Type *value_type = Type::get_const_basic_type(type);
2471 
2472   // Figure out the memory ordering.
2473   decorators |= mo_decorator_for_access_kind(kind);
2474 
2475   if (!is_store) {
2476     if (type == T_OBJECT) {
2477       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2478       if (tjp != NULL) {
2479         value_type = tjp;
2480       }
2481     } else if (type == T_INLINE_TYPE) {
2482       value_type = NULL;
2483     }
2484   }
2485 
2486   receiver = null_check(receiver);
2487   if (stopped()) {
2488     return true;
2489   }
2490   // Heap pointers get a null-check from the interpreter,
2491   // as a courtesy.  However, this is not guaranteed by Unsafe,
2492   // and it is not possible to fully distinguish unintended nulls
2493   // from intended ones in this API.
2494 
2495   if (!is_store) {
2496     Node* p = NULL;
2497     // Try to constant fold a load from a constant field
2498 
2499     if (heap_base_oop != top() && field != NULL && field->is_constant() && !field->is_flattened() && !mismatched) {
2500       // final or stable field
2501       p = make_constant_from_field(field, heap_base_oop);
2502     }
2503 
2504     if (p == NULL) { // Could not constant fold the load
2505       if (type == T_INLINE_TYPE) {
2506         if (adr_type->isa_instptr() && !mismatched) {
2507           ciInstanceKlass* holder = adr_type->is_instptr()->klass()->as_instance_klass();
2508           int offset = adr_type->is_instptr()->offset();
2509           p = InlineTypeNode::make_from_flattened(this, inline_klass, base, base, holder, offset, decorators);
2510         } else {
2511           p = InlineTypeNode::make_from_flattened(this, inline_klass, base, adr, NULL, 0, decorators);
2512         }
2513       } else {
2514         p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2515         const TypeOopPtr* ptr = value_type->make_oopptr();
2516         if (ptr != NULL && ptr->is_inlinetypeptr()) {
2517           // Load a non-flattened inline type from memory
2518           p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass(), !ptr->maybe_null());
2519         }
2520       }
2521       // Normalize the value returned by getBoolean in the following cases
2522       if (type == T_BOOLEAN &&
2523           (mismatched ||
2524            heap_base_oop == top() ||                  // - heap_base_oop is NULL or
2525            (can_access_non_heap && field == NULL))    // - heap_base_oop is potentially NULL
2526                                                       //   and the unsafe access is made to large offset
2527                                                       //   (i.e., larger than the maximum offset necessary for any
2528                                                       //   field access)
2529             ) {
2530           IdealKit ideal = IdealKit(this);
2531 #define __ ideal.
2532           IdealVariable normalized_result(ideal);
2533           __ declarations_done();
2534           __ set(normalized_result, p);
2535           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2536           __ set(normalized_result, ideal.ConI(1));
2537           ideal.end_if();
2538           final_sync(ideal);
2539           p = __ value(normalized_result);
2540 #undef __
2541       }
2542     }
2543     if (type == T_ADDRESS) {
2544       p = gvn().transform(new CastP2XNode(NULL, p));
2545       p = ConvX2UL(p);
2546     }
2547     // The load node has the control of the preceding MemBarCPUOrder.  All
2548     // following nodes will have the control of the MemBarCPUOrder inserted at
2549     // the end of this method.  So, pushing the load onto the stack at a later
2550     // point is fine.
2551     set_result(p);
2552   } else {
2553     if (bt == T_ADDRESS) {
2554       // Repackage the long as a pointer.
2555       val = ConvL2X(val);
2556       val = gvn().transform(new CastX2PNode(val));
2557     }
2558     if (type == T_INLINE_TYPE) {
2559       if (adr_type->isa_instptr() && !mismatched) {
2560         ciInstanceKlass* holder = adr_type->is_instptr()->klass()->as_instance_klass();
2561         int offset = adr_type->is_instptr()->offset();
2562         val->as_InlineTypeBase()->store_flattened(this, base, base, holder, offset, decorators);
2563       } else {
2564         val->as_InlineTypeBase()->store_flattened(this, base, adr, NULL, 0, decorators);
2565       }
2566     } else {
2567       access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2568     }
2569   }
2570 
2571   if (argument(1)->is_InlineType() && is_store) {
2572     Node* value = InlineTypeNode::make_from_oop(this, base, _gvn.type(base)->inline_klass());
2573     value = value->as_InlineType()->make_larval(this, false);
2574     replace_in_map(argument(1), value);
2575   }
2576 
2577   return true;
2578 }
2579 
2580 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2581   Node* receiver = argument(0);
2582   Node* value = argument(1);
2583   if (!value->is_InlineType()) {
2584     return false;
2585   }
2586 
2587   receiver = null_check(receiver);
2588   if (stopped()) {
2589     return true;
2590   }
2591 
2592   set_result(value->as_InlineType()->make_larval(this, true));
2593   return true;
2594 }
2595 
2596 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2597   Node* receiver = argument(0);
2598   Node* buffer = argument(1);
2599   if (!buffer->is_InlineType()) {
2600     return false;
2601   }
2602   InlineTypeNode* vt = buffer->as_InlineType();
2603   if (!vt->is_allocated(&_gvn) || !_gvn.type(vt)->is_inlinetype()->larval()) {
2604     return false;
2605   }
2606 
2607   receiver = null_check(receiver);
2608   if (stopped()) {
2609     return true;
2610   }
2611 
2612   set_result(vt->finish_larval(this));
2613   return true;
2614 }
2615 
2616 //----------------------------inline_unsafe_load_store----------------------------
2617 // This method serves a couple of different customers (depending on LoadStoreKind):
2618 //
2619 // LS_cmp_swap:
2620 //
2621 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2622 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2623 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2624 //
2625 // LS_cmp_swap_weak:
2626 //
2627 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2628 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2629 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2630 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2631 //
2632 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2633 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2634 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2635 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2636 //
2637 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2638 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2639 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
2640 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
2641 //
2642 // LS_cmp_exchange:
2643 //
2644 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2645 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2646 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2647 //
2648 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2649 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2650 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2651 //
2652 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
2653 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
2654 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
2655 //
2656 // LS_get_add:
2657 //
2658 //   int  getAndAddInt( Object o, long offset, int  delta)
2659 //   long getAndAddLong(Object o, long offset, long delta)
2660 //
2661 // LS_get_set:
2662 //
2663 //   int    getAndSet(Object o, long offset, int    newValue)
2664 //   long   getAndSet(Object o, long offset, long   newValue)
2665 //   Object getAndSet(Object o, long offset, Object newValue)
2666 //
2667 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2668   // This basic scheme here is the same as inline_unsafe_access, but
2669   // differs in enough details that combining them would make the code
2670   // overly confusing.  (This is a true fact! I originally combined
2671   // them, but even I was confused by it!) As much code/comments as
2672   // possible are retained from inline_unsafe_access though to make
2673   // the correspondences clearer. - dl
2674 
2675   if (callee()->is_static())  return false;  // caller must have the capability!
2676 
2677   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2678   decorators |= mo_decorator_for_access_kind(access_kind);
2679 
2680 #ifndef PRODUCT
2681   BasicType rtype;
2682   {
2683     ResourceMark rm;
2684     // Check the signatures.
2685     ciSignature* sig = callee()->signature();
2686     rtype = sig->return_type()->basic_type();
2687     switch(kind) {
2688       case LS_get_add:
2689       case LS_get_set: {
2690       // Check the signatures.
2691 #ifdef ASSERT
2692       assert(rtype == type, "get and set must return the expected type");
2693       assert(sig->count() == 3, "get and set has 3 arguments");
2694       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2695       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2696       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2697       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2698 #endif // ASSERT
2699         break;
2700       }
2701       case LS_cmp_swap:
2702       case LS_cmp_swap_weak: {
2703       // Check the signatures.
2704 #ifdef ASSERT
2705       assert(rtype == T_BOOLEAN, "CAS must return boolean");
2706       assert(sig->count() == 4, "CAS has 4 arguments");
2707       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2708       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2709 #endif // ASSERT
2710         break;
2711       }
2712       case LS_cmp_exchange: {
2713       // Check the signatures.
2714 #ifdef ASSERT
2715       assert(rtype == type, "CAS must return the expected type");
2716       assert(sig->count() == 4, "CAS has 4 arguments");
2717       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2718       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2719 #endif // ASSERT
2720         break;
2721       }
2722       default:
2723         ShouldNotReachHere();
2724     }
2725   }
2726 #endif //PRODUCT
2727 
2728   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2729 
2730   // Get arguments:
2731   Node* receiver = NULL;
2732   Node* base     = NULL;
2733   Node* offset   = NULL;
2734   Node* oldval   = NULL;
2735   Node* newval   = NULL;
2736   switch(kind) {
2737     case LS_cmp_swap:
2738     case LS_cmp_swap_weak:
2739     case LS_cmp_exchange: {
2740       const bool two_slot_type = type2size[type] == 2;
2741       receiver = argument(0);  // type: oop
2742       base     = argument(1);  // type: oop
2743       offset   = argument(2);  // type: long
2744       oldval   = argument(4);  // type: oop, int, or long
2745       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2746       break;
2747     }
2748     case LS_get_add:
2749     case LS_get_set: {
2750       receiver = argument(0);  // type: oop
2751       base     = argument(1);  // type: oop
2752       offset   = argument(2);  // type: long
2753       oldval   = NULL;
2754       newval   = argument(4);  // type: oop, int, or long
2755       break;
2756     }
2757     default:
2758       ShouldNotReachHere();
2759   }
2760 
2761   // Build field offset expression.
2762   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2763   // to be plain byte offsets, which are also the same as those accepted
2764   // by oopDesc::field_addr.
2765   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2766   // 32-bit machines ignore the high half of long offsets
2767   offset = ConvL2X(offset);
2768   // Save state and restore on bailout
2769   uint old_sp = sp();
2770   SafePointNode* old_map = clone_map();
2771   Node* adr = make_unsafe_address(base, offset,type, false);
2772   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2773 
2774   Compile::AliasType* alias_type = C->alias_type(adr_type);
2775   BasicType bt = alias_type->basic_type();
2776   if (bt != T_ILLEGAL &&
2777       (is_reference_type(bt) != (type == T_OBJECT))) {
2778     // Don't intrinsify mismatched object accesses.
2779     set_map(old_map);
2780     set_sp(old_sp);
2781     return false;
2782   }
2783 
2784   old_map->destruct(&_gvn);
2785 
2786   // For CAS, unlike inline_unsafe_access, there seems no point in
2787   // trying to refine types. Just use the coarse types here.
2788   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2789   const Type *value_type = Type::get_const_basic_type(type);
2790 
2791   switch (kind) {
2792     case LS_get_set:
2793     case LS_cmp_exchange: {
2794       if (type == T_OBJECT) {
2795         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2796         if (tjp != NULL) {
2797           value_type = tjp;
2798         }
2799       }
2800       break;
2801     }
2802     case LS_cmp_swap:
2803     case LS_cmp_swap_weak:
2804     case LS_get_add:
2805       break;
2806     default:
2807       ShouldNotReachHere();
2808   }
2809 
2810   // Null check receiver.
2811   receiver = null_check(receiver);
2812   if (stopped()) {
2813     return true;
2814   }
2815 
2816   int alias_idx = C->get_alias_index(adr_type);
2817 
2818   if (is_reference_type(type)) {
2819     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2820 
2821     if (oldval != NULL && oldval->is_InlineType()) {
2822       // Re-execute the unsafe access if allocation triggers deoptimization.
2823       PreserveReexecuteState preexecs(this);
2824       jvms()->set_should_reexecute(true);
2825       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
2826     }
2827     if (newval != NULL && newval->is_InlineType()) {
2828       // Re-execute the unsafe access if allocation triggers deoptimization.
2829       PreserveReexecuteState preexecs(this);
2830       jvms()->set_should_reexecute(true);
2831       newval = newval->as_InlineType()->buffer(this)->get_oop();
2832     }
2833 
2834     // Transformation of a value which could be NULL pointer (CastPP #NULL)
2835     // could be delayed during Parse (for example, in adjust_map_after_if()).
2836     // Execute transformation here to avoid barrier generation in such case.
2837     if (_gvn.type(newval) == TypePtr::NULL_PTR)
2838       newval = _gvn.makecon(TypePtr::NULL_PTR);
2839 
2840     if (oldval != NULL && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2841       // Refine the value to a null constant, when it is known to be null
2842       oldval = _gvn.makecon(TypePtr::NULL_PTR);
2843     }
2844   }
2845 
2846   Node* result = NULL;
2847   switch (kind) {
2848     case LS_cmp_exchange: {
2849       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2850                                             oldval, newval, value_type, type, decorators);
2851       break;
2852     }
2853     case LS_cmp_swap_weak:
2854       decorators |= C2_WEAK_CMPXCHG;
2855     case LS_cmp_swap: {
2856       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
2857                                              oldval, newval, value_type, type, decorators);
2858       break;
2859     }
2860     case LS_get_set: {
2861       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
2862                                      newval, value_type, type, decorators);
2863       break;
2864     }
2865     case LS_get_add: {
2866       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
2867                                     newval, value_type, type, decorators);
2868       break;
2869     }
2870     default:
2871       ShouldNotReachHere();
2872   }
2873 
2874   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
2875   set_result(result);
2876   return true;
2877 }
2878 
2879 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
2880   // Regardless of form, don't allow previous ld/st to move down,
2881   // then issue acquire, release, or volatile mem_bar.
2882   insert_mem_bar(Op_MemBarCPUOrder);
2883   switch(id) {
2884     case vmIntrinsics::_loadFence:
2885       insert_mem_bar(Op_LoadFence);
2886       return true;
2887     case vmIntrinsics::_storeFence:
2888       insert_mem_bar(Op_StoreFence);
2889       return true;
2890     case vmIntrinsics::_fullFence:
2891       insert_mem_bar(Op_MemBarVolatile);
2892       return true;
2893     default:
2894       fatal_unexpected_iid(id);
2895       return false;
2896   }
2897 }
2898 
2899 bool LibraryCallKit::inline_onspinwait() {
2900   insert_mem_bar(Op_OnSpinWait);
2901   return true;
2902 }
2903 
2904 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
2905   if (!kls->is_Con()) {
2906     return true;
2907   }
2908   const TypeKlassPtr* klsptr = kls->bottom_type()->isa_klassptr();
2909   if (klsptr == NULL) {
2910     return true;
2911   }
2912   ciInstanceKlass* ik = klsptr->klass()->as_instance_klass();
2913   // don't need a guard for a klass that is already initialized
2914   return !ik->is_initialized();
2915 }
2916 
2917 //----------------------------inline_unsafe_writeback0-------------------------
2918 // public native void Unsafe.writeback0(long address)
2919 bool LibraryCallKit::inline_unsafe_writeback0() {
2920   if (!Matcher::has_match_rule(Op_CacheWB)) {
2921     return false;
2922   }
2923 #ifndef PRODUCT
2924   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
2925   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
2926   ciSignature* sig = callee()->signature();
2927   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
2928 #endif
2929   null_check_receiver();  // null-check, then ignore
2930   Node *addr = argument(1);
2931   addr = new CastX2PNode(addr);
2932   addr = _gvn.transform(addr);
2933   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
2934   flush = _gvn.transform(flush);
2935   set_memory(flush, TypeRawPtr::BOTTOM);
2936   return true;
2937 }
2938 
2939 //----------------------------inline_unsafe_writeback0-------------------------
2940 // public native void Unsafe.writeback0(long address)
2941 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
2942   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
2943     return false;
2944   }
2945   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
2946     return false;
2947   }
2948 #ifndef PRODUCT
2949   assert(Matcher::has_match_rule(Op_CacheWB),
2950          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
2951                 : "found match rule for CacheWBPostSync but not CacheWB"));
2952 
2953 #endif
2954   null_check_receiver();  // null-check, then ignore
2955   Node *sync;
2956   if (is_pre) {
2957     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
2958   } else {
2959     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
2960   }
2961   sync = _gvn.transform(sync);
2962   set_memory(sync, TypeRawPtr::BOTTOM);
2963   return true;
2964 }
2965 
2966 //----------------------------inline_unsafe_allocate---------------------------
2967 // public native Object Unsafe.allocateInstance(Class<?> cls);
2968 bool LibraryCallKit::inline_unsafe_allocate() {
2969   if (callee()->is_static())  return false;  // caller must have the capability!
2970 
2971   null_check_receiver();  // null-check, then ignore
2972   Node* cls = null_check(argument(1));
2973   if (stopped())  return true;
2974 
2975   Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
2976   kls = null_check(kls);
2977   if (stopped())  return true;  // argument was like int.class
2978 
2979   Node* test = NULL;
2980   if (LibraryCallKit::klass_needs_init_guard(kls)) {
2981     // Note:  The argument might still be an illegal value like
2982     // Serializable.class or Object[].class.   The runtime will handle it.
2983     // But we must make an explicit check for initialization.
2984     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
2985     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
2986     // can generate code to load it as unsigned byte.
2987     Node* inst = make_load(NULL, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::unordered);
2988     Node* bits = intcon(InstanceKlass::fully_initialized);
2989     test = _gvn.transform(new SubINode(inst, bits));
2990     // The 'test' is non-zero if we need to take a slow path.
2991   }
2992   Node* obj = NULL;
2993   ciKlass* klass = _gvn.type(kls)->is_klassptr()->klass();
2994   if (klass->is_inlinetype()) {
2995     obj = InlineTypeNode::make_default(_gvn, klass->as_inline_klass());
2996   } else {
2997     obj = new_instance(kls, test);
2998   }
2999   set_result(obj);
3000   return true;
3001 }
3002 
3003 //------------------------inline_native_time_funcs--------------
3004 // inline code for System.currentTimeMillis() and System.nanoTime()
3005 // these have the same type and signature
3006 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3007   const TypeFunc* tf = OptoRuntime::void_long_Type();
3008   const TypePtr* no_memory_effects = NULL;
3009   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3010   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3011 #ifdef ASSERT
3012   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3013   assert(value_top == top(), "second value must be top");
3014 #endif
3015   set_result(value);
3016   return true;
3017 }
3018 
3019 #ifdef JFR_HAVE_INTRINSICS
3020 
3021 /**
3022  * if oop->klass != null
3023  *   // normal class
3024  *   epoch = _epoch_state ? 2 : 1
3025  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3026  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3027  *   }
3028  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3029  * else
3030  *   // primitive class
3031  *   if oop->array_klass != null
3032  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3033  *   else
3034  *     id = LAST_TYPE_ID + 1 // void class path
3035  *   if (!signaled)
3036  *     signaled = true
3037  */
3038 bool LibraryCallKit::inline_native_classID() {
3039   Node* cls = argument(0);
3040 
3041   IdealKit ideal(this);
3042 #define __ ideal.
3043   IdealVariable result(ideal); __ declarations_done();
3044   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(),
3045                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3046                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3047 
3048 
3049   __ if_then(kls, BoolTest::ne, null()); {
3050     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3051     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3052 
3053     Node* epoch_address = makecon(TypeRawPtr::make(Jfr::epoch_address()));
3054     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3055     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3056     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3057     mask = _gvn.transform(new OrLNode(mask, epoch));
3058     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3059 
3060     float unlikely  = PROB_UNLIKELY(0.999);
3061     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3062       sync_kit(ideal);
3063       make_runtime_call(RC_LEAF,
3064                         OptoRuntime::get_class_id_intrinsic_Type(),
3065                         CAST_FROM_FN_PTR(address, Jfr::get_class_id_intrinsic),
3066                         "get_class_id_intrinsic",
3067                         TypePtr::BOTTOM,
3068                         kls);
3069       ideal.sync_kit(this);
3070     } __ end_if();
3071 
3072     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3073   } __ else_(); {
3074     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(),
3075                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3076                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3077     __ if_then(array_kls, BoolTest::ne, null()); {
3078       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3079       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3080       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3081       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3082     } __ else_(); {
3083       // void class case
3084       ideal.set(result, _gvn.transform(longcon(LAST_TYPE_ID + 1)));
3085     } __ end_if();
3086 
3087     Node* signaled_flag_address = makecon(TypeRawPtr::make(Jfr::signal_address()));
3088     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3089     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3090       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3091     } __ end_if();
3092   } __ end_if();
3093 
3094   final_sync(ideal);
3095   set_result(ideal.value(result));
3096 #undef __
3097   return true;
3098 }
3099 
3100 bool LibraryCallKit::inline_native_getEventWriter() {
3101   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3102 
3103   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr,
3104                                   in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3105 
3106   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3107 
3108   Node* jobj_cmp_null = _gvn.transform( new CmpPNode(jobj, null()) );
3109   Node* test_jobj_eq_null  = _gvn.transform( new BoolNode(jobj_cmp_null, BoolTest::eq) );
3110 
3111   IfNode* iff_jobj_null =
3112     create_and_map_if(control(), test_jobj_eq_null, PROB_MIN, COUNT_UNKNOWN);
3113 
3114   enum { _normal_path = 1,
3115          _null_path = 2,
3116          PATH_LIMIT };
3117 
3118   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3119   PhiNode*    result_val = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
3120 
3121   Node* jobj_is_null = _gvn.transform(new IfTrueNode(iff_jobj_null));
3122   result_rgn->init_req(_null_path, jobj_is_null);
3123   result_val->init_req(_null_path, null());
3124 
3125   Node* jobj_is_not_null = _gvn.transform(new IfFalseNode(iff_jobj_null));
3126   set_control(jobj_is_not_null);
3127   Node* res = access_load(jobj, TypeInstPtr::NOTNULL, T_OBJECT,
3128                           IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3129   result_rgn->init_req(_normal_path, control());
3130   result_val->init_req(_normal_path, res);
3131 
3132   set_result(result_rgn, result_val);
3133 
3134   return true;
3135 }
3136 
3137 #endif // JFR_HAVE_INTRINSICS
3138 
3139 //------------------------inline_native_currentThread------------------
3140 bool LibraryCallKit::inline_native_currentThread() {
3141   Node* junk = NULL;
3142   set_result(generate_current_thread(junk));
3143   return true;
3144 }
3145 
3146 //-----------------------load_klass_from_mirror_common-------------------------
3147 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
3148 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
3149 // and branch to the given path on the region.
3150 // If never_see_null, take an uncommon trap on null, so we can optimistically
3151 // compile for the non-null case.
3152 // If the region is NULL, force never_see_null = true.
3153 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
3154                                                     bool never_see_null,
3155                                                     RegionNode* region,
3156                                                     int null_path,
3157                                                     int offset) {
3158   if (region == NULL)  never_see_null = true;
3159   Node* p = basic_plus_adr(mirror, offset);
3160   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
3161   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
3162   Node* null_ctl = top();
3163   kls = null_check_oop(kls, &null_ctl, never_see_null);
3164   if (region != NULL) {
3165     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
3166     region->init_req(null_path, null_ctl);
3167   } else {
3168     assert(null_ctl == top(), "no loose ends");
3169   }
3170   return kls;
3171 }
3172 
3173 //--------------------(inline_native_Class_query helpers)---------------------
3174 // Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE_FAST, JVM_ACC_HAS_FINALIZER.
3175 // Fall through if (mods & mask) == bits, take the guard otherwise.
3176 Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3177   // Branch around if the given klass has the given modifier bit set.
3178   // Like generate_guard, adds a new path onto the region.
3179   Node* modp = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3180   Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT, MemNode::unordered);
3181   Node* mask = intcon(modifier_mask);
3182   Node* bits = intcon(modifier_bits);
3183   Node* mbit = _gvn.transform(new AndINode(mods, mask));
3184   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
3185   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3186   return generate_fair_guard(bol, region);
3187 }
3188 
3189 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3190   return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);
3191 }
3192 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
3193   return generate_access_flags_guard(kls, JVM_ACC_IS_HIDDEN_CLASS, 0, region);
3194 }
3195 
3196 //-------------------------inline_native_Class_query-------------------
3197 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
3198   const Type* return_type = TypeInt::BOOL;
3199   Node* prim_return_value = top();  // what happens if it's a primitive class?
3200   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3201   bool expect_prim = false;     // most of these guys expect to work on refs
3202 
3203   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
3204 
3205   Node* mirror = argument(0);
3206   Node* obj    = top();
3207 
3208   switch (id) {
3209   case vmIntrinsics::_isInstance:
3210     // nothing is an instance of a primitive type
3211     prim_return_value = intcon(0);
3212     obj = argument(1);
3213     break;
3214   case vmIntrinsics::_getModifiers:
3215     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3216     assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");
3217     return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);
3218     break;
3219   case vmIntrinsics::_isInterface:
3220     prim_return_value = intcon(0);
3221     break;
3222   case vmIntrinsics::_isArray:
3223     prim_return_value = intcon(0);
3224     expect_prim = true;  // cf. ObjectStreamClass.getClassSignature
3225     break;
3226   case vmIntrinsics::_isPrimitive:
3227     prim_return_value = intcon(1);
3228     expect_prim = true;  // obviously
3229     break;
3230   case vmIntrinsics::_isHidden:
3231     prim_return_value = intcon(0);
3232     break;
3233   case vmIntrinsics::_getSuperclass:
3234     prim_return_value = null();
3235     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
3236     break;
3237   case vmIntrinsics::_getClassAccessFlags:
3238     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3239     return_type = TypeInt::INT;  // not bool!  6297094
3240     break;
3241   default:
3242     fatal_unexpected_iid(id);
3243     break;
3244   }
3245 
3246   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3247   if (mirror_con == NULL)  return false;  // cannot happen?
3248 
3249 #ifndef PRODUCT
3250   if (C->print_intrinsics() || C->print_inlining()) {
3251     ciType* k = mirror_con->java_mirror_type();
3252     if (k) {
3253       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
3254       k->print_name();
3255       tty->cr();
3256     }
3257   }
3258 #endif
3259 
3260   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
3261   RegionNode* region = new RegionNode(PATH_LIMIT);
3262   record_for_igvn(region);
3263   PhiNode* phi = new PhiNode(region, return_type);
3264 
3265   // The mirror will never be null of Reflection.getClassAccessFlags, however
3266   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
3267   // if it is. See bug 4774291.
3268 
3269   // For Reflection.getClassAccessFlags(), the null check occurs in
3270   // the wrong place; see inline_unsafe_access(), above, for a similar
3271   // situation.
3272   mirror = null_check(mirror);
3273   // If mirror or obj is dead, only null-path is taken.
3274   if (stopped())  return true;
3275 
3276   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
3277 
3278   // Now load the mirror's klass metaobject, and null-check it.
3279   // Side-effects region with the control path if the klass is null.
3280   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
3281   // If kls is null, we have a primitive mirror.
3282   phi->init_req(_prim_path, prim_return_value);
3283   if (stopped()) { set_result(region, phi); return true; }
3284   bool safe_for_replace = (region->in(_prim_path) == top());
3285 
3286   Node* p;  // handy temp
3287   Node* null_ctl;
3288 
3289   // Now that we have the non-null klass, we can perform the real query.
3290   // For constant classes, the query will constant-fold in LoadNode::Value.
3291   Node* query_value = top();
3292   switch (id) {
3293   case vmIntrinsics::_isInstance:
3294     // nothing is an instance of a primitive type
3295     query_value = gen_instanceof(obj, kls, safe_for_replace);
3296     break;
3297 
3298   case vmIntrinsics::_getModifiers:
3299     p = basic_plus_adr(kls, in_bytes(Klass::modifier_flags_offset()));
3300     query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
3301     break;
3302 
3303   case vmIntrinsics::_isInterface:
3304     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3305     if (generate_interface_guard(kls, region) != NULL)
3306       // A guard was added.  If the guard is taken, it was an interface.
3307       phi->add_req(intcon(1));
3308     // If we fall through, it's a plain class.
3309     query_value = intcon(0);
3310     break;
3311 
3312   case vmIntrinsics::_isArray:
3313     // (To verify this code sequence, check the asserts in JVM_IsArrayClass.)
3314     if (generate_array_guard(kls, region) != NULL)
3315       // A guard was added.  If the guard is taken, it was an array.
3316       phi->add_req(intcon(1));
3317     // If we fall through, it's a plain class.
3318     query_value = intcon(0);
3319     break;
3320 
3321   case vmIntrinsics::_isPrimitive:
3322     query_value = intcon(0); // "normal" path produces false
3323     break;
3324 
3325   case vmIntrinsics::_isHidden:
3326     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
3327     if (generate_hidden_class_guard(kls, region) != NULL)
3328       // A guard was added.  If the guard is taken, it was an hidden class.
3329       phi->add_req(intcon(1));
3330     // If we fall through, it's a plain class.
3331     query_value = intcon(0);
3332     break;
3333 
3334 
3335   case vmIntrinsics::_getSuperclass:
3336     // The rules here are somewhat unfortunate, but we can still do better
3337     // with random logic than with a JNI call.
3338     // Interfaces store null or Object as _super, but must report null.
3339     // Arrays store an intermediate super as _super, but must report Object.
3340     // Other types can report the actual _super.
3341     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3342     if (generate_interface_guard(kls, region) != NULL)
3343       // A guard was added.  If the guard is taken, it was an interface.
3344       phi->add_req(null());
3345     if (generate_array_guard(kls, region) != NULL)
3346       // A guard was added.  If the guard is taken, it was an array.
3347       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
3348     // If we fall through, it's a plain class.  Get its _super.
3349     p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
3350     kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3351     null_ctl = top();
3352     kls = null_check_oop(kls, &null_ctl);
3353     if (null_ctl != top()) {
3354       // If the guard is taken, Object.superClass is null (both klass and mirror).
3355       region->add_req(null_ctl);
3356       phi   ->add_req(null());
3357     }
3358     if (!stopped()) {
3359       query_value = load_mirror_from_klass(kls);
3360     }
3361     break;
3362 
3363   case vmIntrinsics::_getClassAccessFlags:
3364     p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3365     query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
3366     break;
3367 
3368   default:
3369     fatal_unexpected_iid(id);
3370     break;
3371   }
3372 
3373   // Fall-through is the normal case of a query to a real class.
3374   phi->init_req(1, query_value);
3375   region->init_req(1, control());
3376 
3377   C->set_has_split_ifs(true); // Has chance for split-if optimization
3378   set_result(region, phi);
3379   return true;
3380 }
3381 
3382 //-------------------------inline_primitive_Class_conversion-------------------
3383 // public Class<T> java.lang.Class.asPrimaryType();
3384 // public Class<T> java.lang.Class.asValueType()
3385 bool LibraryCallKit::inline_primitive_Class_conversion(vmIntrinsics::ID id) {
3386   Node* mirror = argument(0); // Receiver Class
3387   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3388   if (mirror_con == NULL) {
3389     return false;
3390   }
3391 
3392   bool is_val_mirror = true;
3393   ciType* tm = mirror_con->java_mirror_type(&is_val_mirror);
3394   if (tm != NULL) {
3395     Node* result = mirror;
3396     if (id == vmIntrinsics::_asPrimaryType && is_val_mirror) {
3397       result = _gvn.makecon(TypeInstPtr::make(tm->as_inline_klass()->ref_mirror()));
3398     } else if (id == vmIntrinsics::_asValueType) {
3399       if (!tm->is_inlinetype()) {
3400         return false; // Throw UnsupportedOperationException
3401       } else if (!is_val_mirror) {
3402         result = _gvn.makecon(TypeInstPtr::make(tm->as_inline_klass()->val_mirror()));
3403       }
3404     }
3405     set_result(result);
3406     return true;
3407   }
3408   return false;
3409 }
3410 
3411 //-------------------------inline_Class_cast-------------------
3412 bool LibraryCallKit::inline_Class_cast() {
3413   Node* mirror = argument(0); // Class
3414   Node* obj    = argument(1);
3415   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3416   if (mirror_con == NULL) {
3417     return false;  // dead path (mirror->is_top()).
3418   }
3419   if (obj == NULL || obj->is_top()) {
3420     return false;  // dead path
3421   }
3422   ciKlass* obj_klass = NULL;
3423   const Type* obj_t = _gvn.type(obj);
3424   if (obj->is_InlineType()) {
3425     obj_klass = obj_t->inline_klass();
3426   } else if (obj_t->isa_oopptr()) {
3427     obj_klass = obj_t->is_oopptr()->klass();
3428   }
3429 
3430   // First, see if Class.cast() can be folded statically.
3431   // java_mirror_type() returns non-null for compile-time Class constants.
3432   bool requires_null_check = false;
3433   ciType* tm = mirror_con->java_mirror_type(&requires_null_check);
3434   // Check for null if casting to QMyValue
3435   requires_null_check &= !obj->is_InlineType();
3436   if (tm != NULL && tm->is_klass() && obj_klass != NULL) {
3437     if (!obj_klass->is_loaded()) {
3438       // Don't use intrinsic when class is not loaded.
3439       return false;
3440     } else {
3441       int static_res = C->static_subtype_check(tm->as_klass(), obj_klass);
3442       if (static_res == Compile::SSC_always_true) {
3443         // isInstance() is true - fold the code.
3444         if (requires_null_check) {
3445           obj = null_check(obj);
3446         }
3447         set_result(obj);
3448         return true;
3449       } else if (static_res == Compile::SSC_always_false) {
3450         // Don't use intrinsic, have to throw ClassCastException.
3451         // If the reference is null, the non-intrinsic bytecode will
3452         // be optimized appropriately.
3453         return false;
3454       }
3455     }
3456   }
3457 
3458   // Bailout intrinsic and do normal inlining if exception path is frequent.
3459   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3460     return false;
3461   }
3462 
3463   // Generate dynamic checks.
3464   // Class.cast() is java implementation of _checkcast bytecode.
3465   // Do checkcast (Parse::do_checkcast()) optimizations here.
3466 
3467   if (requires_null_check) {
3468     obj = null_check(obj);
3469   }
3470   mirror = null_check(mirror);
3471   // If mirror is dead, only null-path is taken.
3472   if (stopped()) {
3473     return true;
3474   }
3475 
3476   // Not-subtype or the mirror's klass ptr is NULL (in case it is a primitive).
3477   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
3478   RegionNode* region = new RegionNode(PATH_LIMIT);
3479   record_for_igvn(region);
3480 
3481   // Now load the mirror's klass metaobject, and null-check it.
3482   // If kls is null, we have a primitive mirror and
3483   // nothing is an instance of a primitive type.
3484   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
3485 
3486   Node* res = top();
3487   if (!stopped()) {
3488     if (EnableValhalla && !obj->is_InlineType() && !requires_null_check) {
3489       // Check if we are casting to QMyValue
3490       Node* ctrl_val_mirror = generate_fair_guard(is_val_mirror(mirror), NULL);
3491       if (ctrl_val_mirror != NULL) {
3492         RegionNode* r = new RegionNode(3);
3493         record_for_igvn(r);
3494         r->init_req(1, control());
3495 
3496         // Casting to QMyValue, check for null
3497         set_control(ctrl_val_mirror);
3498         { // PreserveJVMState because null check replaces obj in map
3499           PreserveJVMState pjvms(this);
3500           Node* null_ctr = top();
3501           null_check_oop(obj, &null_ctr);
3502           region->init_req(_npe_path, null_ctr);
3503           r->init_req(2, control());
3504         }
3505         set_control(_gvn.transform(r));
3506       }
3507     }
3508 
3509     Node* bad_type_ctrl = top();
3510     // Do checkcast optimizations.
3511     res = gen_checkcast(obj, kls, &bad_type_ctrl);
3512     region->init_req(_bad_type_path, bad_type_ctrl);
3513   }
3514   if (region->in(_prim_path) != top() ||
3515       region->in(_bad_type_path) != top() ||
3516       region->in(_npe_path) != top()) {
3517     // Let Interpreter throw ClassCastException.
3518     PreserveJVMState pjvms(this);
3519     set_control(_gvn.transform(region));
3520     uncommon_trap(Deoptimization::Reason_intrinsic,
3521                   Deoptimization::Action_maybe_recompile);
3522   }
3523   if (!stopped()) {
3524     set_result(res);
3525   }
3526   return true;
3527 }
3528 
3529 
3530 //--------------------------inline_native_subtype_check------------------------
3531 // This intrinsic takes the JNI calls out of the heart of
3532 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
3533 bool LibraryCallKit::inline_native_subtype_check() {
3534   // Pull both arguments off the stack.
3535   Node* args[2];                // two java.lang.Class mirrors: superc, subc
3536   args[0] = argument(0);
3537   args[1] = argument(1);
3538   Node* klasses[2];             // corresponding Klasses: superk, subk
3539   klasses[0] = klasses[1] = top();
3540 
3541   enum {
3542     // A full decision tree on {superc is prim, subc is prim}:
3543     _prim_0_path = 1,           // {P,N} => false
3544                                 // {P,P} & superc!=subc => false
3545     _prim_same_path,            // {P,P} & superc==subc => true
3546     _prim_1_path,               // {N,P} => false
3547     _ref_subtype_path,          // {N,N} & subtype check wins => true
3548     _both_ref_path,             // {N,N} & subtype check loses => false
3549     PATH_LIMIT
3550   };
3551 
3552   RegionNode* region = new RegionNode(PATH_LIMIT);
3553   RegionNode* prim_region = new RegionNode(2);
3554   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
3555   record_for_igvn(region);
3556   record_for_igvn(prim_region);
3557 
3558   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
3559   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
3560   int class_klass_offset = java_lang_Class::klass_offset();
3561 
3562   // First null-check both mirrors and load each mirror's klass metaobject.
3563   int which_arg;
3564   for (which_arg = 0; which_arg <= 1; which_arg++) {
3565     Node* arg = args[which_arg];
3566     arg = null_check(arg);
3567     if (stopped())  break;
3568     args[which_arg] = arg;
3569 
3570     Node* p = basic_plus_adr(arg, class_klass_offset);
3571     Node* kls = LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, adr_type, kls_type);
3572     klasses[which_arg] = _gvn.transform(kls);
3573   }
3574 
3575   // Having loaded both klasses, test each for null.
3576   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3577   for (which_arg = 0; which_arg <= 1; which_arg++) {
3578     Node* kls = klasses[which_arg];
3579     Node* null_ctl = top();
3580     kls = null_check_oop(kls, &null_ctl, never_see_null);
3581     if (which_arg == 0) {
3582       prim_region->init_req(1, null_ctl);
3583     } else {
3584       region->init_req(_prim_1_path, null_ctl);
3585     }
3586     if (stopped())  break;
3587     klasses[which_arg] = kls;
3588   }
3589 
3590   if (!stopped()) {
3591     // now we have two reference types, in klasses[0..1]
3592     Node* subk   = klasses[1];  // the argument to isAssignableFrom
3593     Node* superk = klasses[0];  // the receiver
3594     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
3595     // If superc is an inline mirror, we also need to check if superc == subc because LMyValue
3596     // is not a subtype of QMyValue but due to subk == superk the subtype check will pass.
3597     generate_fair_guard(is_val_mirror(args[0]), prim_region);
3598     // now we have a successful reference subtype check
3599     region->set_req(_ref_subtype_path, control());
3600   }
3601 
3602   // If both operands are primitive (both klasses null), then
3603   // we must return true when they are identical primitives.
3604   // It is convenient to test this after the first null klass check.
3605   // This path is also used if superc is a value mirror.
3606   set_control(_gvn.transform(prim_region));
3607   if (!stopped()) {
3608     // Since superc is primitive, make a guard for the superc==subc case.
3609     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
3610     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
3611     generate_fair_guard(bol_eq, region);
3612     if (region->req() == PATH_LIMIT+1) {
3613       // A guard was added.  If the added guard is taken, superc==subc.
3614       region->swap_edges(PATH_LIMIT, _prim_same_path);
3615       region->del_req(PATH_LIMIT);
3616     }
3617     region->set_req(_prim_0_path, control()); // Not equal after all.
3618   }
3619 
3620   // these are the only paths that produce 'true':
3621   phi->set_req(_prim_same_path,   intcon(1));
3622   phi->set_req(_ref_subtype_path, intcon(1));
3623 
3624   // pull together the cases:
3625   assert(region->req() == PATH_LIMIT, "sane region");
3626   for (uint i = 1; i < region->req(); i++) {
3627     Node* ctl = region->in(i);
3628     if (ctl == NULL || ctl == top()) {
3629       region->set_req(i, top());
3630       phi   ->set_req(i, top());
3631     } else if (phi->in(i) == NULL) {
3632       phi->set_req(i, intcon(0)); // all other paths produce 'false'
3633     }
3634   }
3635 
3636   set_control(_gvn.transform(region));
3637   set_result(_gvn.transform(phi));
3638   return true;
3639 }
3640 
3641 //---------------------generate_array_guard_common------------------------
3642 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind) {
3643 
3644   if (stopped()) {
3645     return NULL;
3646   }
3647 
3648   // Like generate_guard, adds a new path onto the region.
3649   jint  layout_con = 0;
3650   Node* layout_val = get_layout_helper(kls, layout_con);
3651   if (layout_val == NULL) {
3652     bool query = 0;
3653     switch(kind) {
3654       case ObjectArray:    query = Klass::layout_helper_is_objArray(layout_con); break;
3655       case NonObjectArray: query = !Klass::layout_helper_is_objArray(layout_con); break;
3656       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
3657       case FlatArray:      query = Klass::layout_helper_is_flatArray(layout_con); break;
3658       case NonFlatArray:   query = !Klass::layout_helper_is_flatArray(layout_con); break;
3659       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
3660       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
3661       default:
3662         ShouldNotReachHere();
3663     }
3664     if (!query) {
3665       return NULL;                       // never a branch
3666     } else {                             // always a branch
3667       Node* always_branch = control();
3668       if (region != NULL)
3669         region->add_req(always_branch);
3670       set_control(top());
3671       return always_branch;
3672     }
3673   }
3674   unsigned int value = 0;
3675   BoolTest::mask btest = BoolTest::illegal;
3676   switch(kind) {
3677     case ObjectArray:
3678     case NonObjectArray: {
3679       value = Klass::_lh_array_tag_obj_value;
3680       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
3681       btest = (kind == ObjectArray) ? BoolTest::eq : BoolTest::ne;
3682       break;
3683     }
3684     case TypeArray: {
3685       value = Klass::_lh_array_tag_type_value;
3686       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
3687       btest = BoolTest::eq;
3688       break;
3689     }
3690     case FlatArray:
3691     case NonFlatArray: {
3692       value = 0;
3693       layout_val = _gvn.transform(new AndINode(layout_val, intcon(Klass::_lh_array_tag_vt_value_bit_inplace)));
3694       btest = (kind == FlatArray) ? BoolTest::ne : BoolTest::eq;
3695       break;
3696     }
3697     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
3698     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
3699     default:
3700       ShouldNotReachHere();
3701   }
3702   // Now test the correct condition.
3703   jint nval = (jint)value;
3704   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
3705   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
3706   return generate_fair_guard(bol, region);
3707 }
3708 
3709 
3710 //-----------------------inline_native_newArray--------------------------
3711 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
3712 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
3713 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
3714   Node* mirror;
3715   Node* count_val;
3716   if (uninitialized) {
3717     mirror    = argument(1);
3718     count_val = argument(2);
3719   } else {
3720     mirror    = argument(0);
3721     count_val = argument(1);
3722   }
3723 
3724   mirror = null_check(mirror);
3725   // If mirror or obj is dead, only null-path is taken.
3726   if (stopped())  return true;
3727 
3728   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
3729   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
3730   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
3731   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
3732   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
3733 
3734   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3735   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
3736                                                   result_reg, _slow_path);
3737   Node* normal_ctl   = control();
3738   Node* no_array_ctl = result_reg->in(_slow_path);
3739 
3740   // Generate code for the slow case.  We make a call to newArray().
3741   set_control(no_array_ctl);
3742   if (!stopped()) {
3743     // Either the input type is void.class, or else the
3744     // array klass has not yet been cached.  Either the
3745     // ensuing call will throw an exception, or else it
3746     // will cache the array klass for next time.
3747     PreserveJVMState pjvms(this);
3748     CallJavaNode* slow_call = NULL;
3749     if (uninitialized) {
3750       // Generate optimized virtual call (holder class 'Unsafe' is final)
3751       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false);
3752     } else {
3753       slow_call = generate_method_call_static(vmIntrinsics::_newArray);
3754     }
3755     Node* slow_result = set_results_for_java_call(slow_call);
3756     // this->control() comes from set_results_for_java_call
3757     result_reg->set_req(_slow_path, control());
3758     result_val->set_req(_slow_path, slow_result);
3759     result_io ->set_req(_slow_path, i_o());
3760     result_mem->set_req(_slow_path, reset_memory());
3761   }
3762 
3763   set_control(normal_ctl);
3764   if (!stopped()) {
3765     // Normal case:  The array type has been cached in the java.lang.Class.
3766     // The following call works fine even if the array type is polymorphic.
3767     // It could be a dynamic mix of int[], boolean[], Object[], etc.
3768     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
3769     result_reg->init_req(_normal_path, control());
3770     result_val->init_req(_normal_path, obj);
3771     result_io ->init_req(_normal_path, i_o());
3772     result_mem->init_req(_normal_path, reset_memory());
3773 
3774     if (uninitialized) {
3775       // Mark the allocation so that zeroing is skipped
3776       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj, &_gvn);
3777       alloc->maybe_set_complete(&_gvn);
3778     }
3779   }
3780 
3781   // Return the combined state.
3782   set_i_o(        _gvn.transform(result_io)  );
3783   set_all_memory( _gvn.transform(result_mem));
3784 
3785   C->set_has_split_ifs(true); // Has chance for split-if optimization
3786   set_result(result_reg, result_val);
3787   return true;
3788 }
3789 
3790 //----------------------inline_native_getLength--------------------------
3791 // public static native int java.lang.reflect.Array.getLength(Object array);
3792 bool LibraryCallKit::inline_native_getLength() {
3793   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3794 
3795   Node* array = null_check(argument(0));
3796   // If array is dead, only null-path is taken.
3797   if (stopped())  return true;
3798 
3799   // Deoptimize if it is a non-array.
3800   Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);
3801 
3802   if (non_array != NULL) {
3803     PreserveJVMState pjvms(this);
3804     set_control(non_array);
3805     uncommon_trap(Deoptimization::Reason_intrinsic,
3806                   Deoptimization::Action_maybe_recompile);
3807   }
3808 
3809   // If control is dead, only non-array-path is taken.
3810   if (stopped())  return true;
3811 
3812   // The works fine even if the array type is polymorphic.
3813   // It could be a dynamic mix of int[], boolean[], Object[], etc.
3814   Node* result = load_array_length(array);
3815 
3816   C->set_has_split_ifs(true);  // Has chance for split-if optimization
3817   set_result(result);
3818   return true;
3819 }
3820 
3821 //------------------------inline_array_copyOf----------------------------
3822 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
3823 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
3824 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
3825   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3826 
3827   // Get the arguments.
3828   Node* original          = argument(0);
3829   Node* start             = is_copyOfRange? argument(1): intcon(0);
3830   Node* end               = is_copyOfRange? argument(2): argument(1);
3831   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
3832 
3833   Node* newcopy = NULL;
3834 
3835   // Set the original stack and the reexecute bit for the interpreter to reexecute
3836   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
3837   { PreserveReexecuteState preexecs(this);
3838     jvms()->set_should_reexecute(true);
3839 
3840     array_type_mirror = null_check(array_type_mirror);
3841     original          = null_check(original);
3842 
3843     // Check if a null path was taken unconditionally.
3844     if (stopped())  return true;
3845 
3846     Node* orig_length = load_array_length(original);
3847 
3848     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, NULL, 0);
3849     klass_node = null_check(klass_node);
3850 
3851     RegionNode* bailout = new RegionNode(1);
3852     record_for_igvn(bailout);
3853 
3854     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
3855     // Bail out if that is so.
3856     // Inline type array may have object field that would require a
3857     // write barrier. Conservatively, go to slow path.
3858     // TODO 8251971: Optimize for the case when flat src/dst are later found
3859     // to not contain oops (i.e., move this check to the macro expansion phase).
3860     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
3861     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
3862     ciKlass* klass = _gvn.type(klass_node)->is_klassptr()->klass();
3863     bool exclude_flat = UseFlatArray && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
3864                         // Can src array be flat and contain oops?
3865                         (orig_t == NULL || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
3866                         // Can dest array be flat and contain oops?
3867                         klass->can_be_inline_array_klass() && (!klass->is_flat_array_klass() || klass->as_flat_array_klass()->element_klass()->as_inline_klass()->contains_oops());
3868     Node* not_objArray = exclude_flat ? generate_non_objArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
3869     if (not_objArray != NULL) {
3870       // Improve the klass node's type from the new optimistic assumption:
3871       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
3872       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0));
3873       Node* cast = new CastPPNode(klass_node, akls);
3874       cast->init_req(0, control());
3875       klass_node = _gvn.transform(cast);
3876     }
3877 
3878     Node* original_kls = load_object_klass(original);
3879     // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
3880     // loads/stores but it is legal only if we're sure the
3881     // Arrays.copyOf would succeed. So we need all input arguments
3882     // to the copyOf to be validated, including that the copy to the
3883     // new array won't trigger an ArrayStoreException. That subtype
3884     // check can be optimized if we know something on the type of
3885     // the input array from type speculation.
3886     if (_gvn.type(klass_node)->singleton() && !stopped()) {
3887       ciKlass* subk   = _gvn.type(original_kls)->is_klassptr()->klass();
3888       ciKlass* superk = _gvn.type(klass_node)->is_klassptr()->klass();
3889 
3890       int test = C->static_subtype_check(superk, subk);
3891       if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
3892         const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
3893         if (t_original->speculative_type() != NULL) {
3894           original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
3895           original_kls = load_object_klass(original);
3896         }
3897       }
3898     }
3899 
3900     // Bail out if either start or end is negative.
3901     generate_negative_guard(start, bailout, &start);
3902     generate_negative_guard(end,   bailout, &end);
3903 
3904     Node* length = end;
3905     if (_gvn.type(start) != TypeInt::ZERO) {
3906       length = _gvn.transform(new SubINode(end, start));
3907     }
3908 
3909     // Bail out if length is negative.
3910     // Without this the new_array would throw
3911     // NegativeArraySizeException but IllegalArgumentException is what
3912     // should be thrown
3913     generate_negative_guard(length, bailout, &length);
3914 
3915     // Handle inline type arrays
3916     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
3917     if (!stopped()) {
3918       orig_t = _gvn.type(original)->isa_aryptr();
3919       if (orig_t != NULL && orig_t->is_flat()) {
3920         // Src is flat, check that dest is flat as well
3921         if (exclude_flat) {
3922           // Dest can't be flat, bail out
3923           bailout->add_req(control());
3924           set_control(top());
3925         } else {
3926           generate_non_flatArray_guard(klass_node, bailout);
3927         }
3928       } else if (UseFlatArray && (orig_t == NULL || !orig_t->is_not_flat()) &&
3929                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
3930                  ((!klass->is_flat_array_klass() && klass->can_be_inline_array_klass()) || !can_validate)) {
3931         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
3932         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
3933         generate_flatArray_guard(original_kls, bailout);
3934         if (orig_t != NULL) {
3935           orig_t = orig_t->cast_to_not_flat();
3936           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
3937         }
3938       }
3939       if (!can_validate) {
3940         // No validation. The subtype check emitted at macro expansion time will not go to the slow
3941         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
3942         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
3943         generate_fair_guard(null_free_array_test(klass_node), bailout);
3944       }
3945     }
3946 
3947     if (bailout->req() > 1) {
3948       PreserveJVMState pjvms(this);
3949       set_control(_gvn.transform(bailout));
3950       uncommon_trap(Deoptimization::Reason_intrinsic,
3951                     Deoptimization::Action_maybe_recompile);
3952     }
3953 
3954     if (!stopped()) {
3955       // How many elements will we copy from the original?
3956       // The answer is MinI(orig_length - start, length).
3957       Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
3958       Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
3959 
3960       // Generate a direct call to the right arraycopy function(s).
3961       // We know the copy is disjoint but we might not know if the
3962       // oop stores need checking.
3963       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
3964       // This will fail a store-check if x contains any non-nulls.
3965 
3966       bool validated = false;
3967       // Reason_class_check rather than Reason_intrinsic because we
3968       // want to intrinsify even if this traps.
3969       if (can_validate) {
3970         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
3971 
3972         if (not_subtype_ctrl != top()) {
3973           PreserveJVMState pjvms(this);
3974           set_control(not_subtype_ctrl);
3975           uncommon_trap(Deoptimization::Reason_class_check,
3976                         Deoptimization::Action_make_not_entrant);
3977           assert(stopped(), "Should be stopped");
3978         }
3979         validated = true;
3980       }
3981 
3982       if (!stopped()) {
3983         newcopy = new_array(klass_node, length, 0);  // no arguments to push
3984 
3985         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, false,
3986                                                 original_kls, klass_node);
3987         if (!is_copyOfRange) {
3988           ac->set_copyof(validated);
3989         } else {
3990           ac->set_copyofrange(validated);
3991         }
3992         Node* n = _gvn.transform(ac);
3993         if (n == ac) {
3994           ac->connect_outputs(this);
3995         } else {
3996           assert(validated, "shouldn't transform if all arguments not validated");
3997           set_all_memory(n);
3998         }
3999       }
4000     }
4001   } // original reexecute is set back here
4002 
4003   C->set_has_split_ifs(true); // Has chance for split-if optimization
4004   if (!stopped()) {
4005     set_result(newcopy);
4006   }
4007   return true;
4008 }
4009 
4010 
4011 //----------------------generate_virtual_guard---------------------------
4012 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
4013 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
4014                                              RegionNode* slow_region) {
4015   ciMethod* method = callee();
4016   int vtable_index = method->vtable_index();
4017   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4018          "bad index %d", vtable_index);
4019   // Get the Method* out of the appropriate vtable entry.
4020   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
4021                      vtable_index*vtableEntry::size_in_bytes() +
4022                      vtableEntry::method_offset_in_bytes();
4023   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
4024   Node* target_call = make_load(NULL, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4025 
4026   // Compare the target method with the expected method (e.g., Object.hashCode).
4027   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
4028 
4029   Node* native_call = makecon(native_call_addr);
4030   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
4031   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
4032 
4033   return generate_slow_guard(test_native, slow_region);
4034 }
4035 
4036 //-----------------------generate_method_call----------------------------
4037 // Use generate_method_call to make a slow-call to the real
4038 // method if the fast path fails.  An alternative would be to
4039 // use a stub like OptoRuntime::slow_arraycopy_Java.
4040 // This only works for expanding the current library call,
4041 // not another intrinsic.  (E.g., don't use this for making an
4042 // arraycopy call inside of the copyOf intrinsic.)
4043 CallJavaNode*
4044 LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {
4045   // When compiling the intrinsic method itself, do not use this technique.
4046   guarantee(callee() != C->method(), "cannot make slow-call to self");
4047 
4048   ciMethod* method = callee();
4049   // ensure the JVMS we have will be correct for this call
4050   guarantee(method_id == method->intrinsic_id(), "must match");
4051 
4052   const TypeFunc* tf = TypeFunc::make(method);
4053   CallJavaNode* slow_call;
4054   if (is_static) {
4055     assert(!is_virtual, "");
4056     slow_call = new CallStaticJavaNode(C, tf,
4057                            SharedRuntime::get_resolve_static_call_stub(), method);
4058   } else if (is_virtual) {
4059     null_check_receiver();
4060     int vtable_index = Method::invalid_vtable_index;
4061     if (UseInlineCaches) {
4062       // Suppress the vtable call
4063     } else {
4064       // hashCode and clone are not a miranda methods,
4065       // so the vtable index is fixed.
4066       // No need to use the linkResolver to get it.
4067        vtable_index = method->vtable_index();
4068        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4069               "bad index %d", vtable_index);
4070     }
4071     slow_call = new CallDynamicJavaNode(tf,
4072                           SharedRuntime::get_resolve_virtual_call_stub(),
4073                           method, vtable_index);
4074   } else {  // neither virtual nor static:  opt_virtual
4075     null_check_receiver();
4076     slow_call = new CallStaticJavaNode(C, tf,
4077                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
4078     slow_call->set_optimized_virtual(true);
4079   }
4080   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
4081     // To be able to issue a direct call (optimized virtual or virtual)
4082     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
4083     // about the method being invoked should be attached to the call site to
4084     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
4085     slow_call->set_override_symbolic_info(true);
4086   }
4087   set_arguments_for_java_call(slow_call);
4088   set_edges_for_java_call(slow_call);
4089   return slow_call;
4090 }
4091 
4092 
4093 /**
4094  * Build special case code for calls to hashCode on an object. This call may
4095  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4096  * slightly different code.
4097  */
4098 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4099   assert(is_static == callee()->is_static(), "correct intrinsic selection");
4100   assert(!(is_virtual && is_static), "either virtual, special, or static");
4101 
4102   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4103 
4104   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4105   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
4106   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4107   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4108   Node* obj = argument(0);
4109 
4110   if (obj->is_InlineType() || gvn().type(obj)->is_inlinetypeptr()) {
4111     return false;
4112   }
4113 
4114   if (!is_static) {
4115     // Check for hashing null object
4116     obj = null_check_receiver();
4117     if (stopped())  return true;        // unconditionally null
4118     result_reg->init_req(_null_path, top());
4119     result_val->init_req(_null_path, top());
4120   } else {
4121     // Do a null check, and return zero if null.
4122     // System.identityHashCode(null) == 0
4123     Node* null_ctl = top();
4124     obj = null_check_oop(obj, &null_ctl);
4125     result_reg->init_req(_null_path, null_ctl);
4126     result_val->init_req(_null_path, _gvn.intcon(0));
4127   }
4128 
4129   // Unconditionally null?  Then return right away.
4130   if (stopped()) {
4131     set_control( result_reg->in(_null_path));
4132     if (!stopped())
4133       set_result(result_val->in(_null_path));
4134     return true;
4135   }
4136 
4137   // We only go to the fast case code if we pass a number of guards.  The
4138   // paths which do not pass are accumulated in the slow_region.
4139   RegionNode* slow_region = new RegionNode(1);
4140   record_for_igvn(slow_region);
4141 
4142   // If this is a virtual call, we generate a funny guard.  We pull out
4143   // the vtable entry corresponding to hashCode() from the target object.
4144   // If the target method which we are calling happens to be the native
4145   // Object hashCode() method, we pass the guard.  We do not need this
4146   // guard for non-virtual calls -- the caller is known to be the native
4147   // Object hashCode().
4148   if (is_virtual) {
4149     // After null check, get the object's klass.
4150     Node* obj_klass = load_object_klass(obj);
4151     generate_virtual_guard(obj_klass, slow_region);
4152   }
4153 
4154   // Get the header out of the object, use LoadMarkNode when available
4155   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4156   // The control of the load must be NULL. Otherwise, the load can move before
4157   // the null check after castPP removal.
4158   Node* no_ctrl = NULL;
4159   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4160 
4161   // Test the header to see if it is unlocked.
4162   // This also serves as guard against inline types
4163   Node *lock_mask      = _gvn.MakeConX(markWord::inline_type_mask_in_place);
4164   Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4165   Node *unlocked_val   = _gvn.MakeConX(markWord::unlocked_value);
4166   Node *chk_unlocked   = _gvn.transform(new CmpXNode( lmasked_header, unlocked_val));
4167   Node *test_unlocked  = _gvn.transform(new BoolNode( chk_unlocked, BoolTest::ne));
4168 
4169   generate_slow_guard(test_unlocked, slow_region);
4170 
4171   // Get the hash value and check to see that it has been properly assigned.
4172   // We depend on hash_mask being at most 32 bits and avoid the use of
4173   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4174   // vm: see markWord.hpp.
4175   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
4176   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
4177   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4178   // This hack lets the hash bits live anywhere in the mark object now, as long
4179   // as the shift drops the relevant bits into the low 32 bits.  Note that
4180   // Java spec says that HashCode is an int so there's no point in capturing
4181   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4182   hshifted_header      = ConvX2I(hshifted_header);
4183   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
4184 
4185   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
4186   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
4187   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
4188 
4189   generate_slow_guard(test_assigned, slow_region);
4190 
4191   Node* init_mem = reset_memory();
4192   // fill in the rest of the null path:
4193   result_io ->init_req(_null_path, i_o());
4194   result_mem->init_req(_null_path, init_mem);
4195 
4196   result_val->init_req(_fast_path, hash_val);
4197   result_reg->init_req(_fast_path, control());
4198   result_io ->init_req(_fast_path, i_o());
4199   result_mem->init_req(_fast_path, init_mem);
4200 
4201   // Generate code for the slow case.  We make a call to hashCode().
4202   set_control(_gvn.transform(slow_region));
4203   if (!stopped()) {
4204     // No need for PreserveJVMState, because we're using up the present state.
4205     set_all_memory(init_mem);
4206     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
4207     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);
4208     Node* slow_result = set_results_for_java_call(slow_call);
4209     // this->control() comes from set_results_for_java_call
4210     result_reg->init_req(_slow_path, control());
4211     result_val->init_req(_slow_path, slow_result);
4212     result_io  ->set_req(_slow_path, i_o());
4213     result_mem ->set_req(_slow_path, reset_memory());
4214   }
4215 
4216   // Return the combined state.
4217   set_i_o(        _gvn.transform(result_io)  );
4218   set_all_memory( _gvn.transform(result_mem));
4219 
4220   set_result(result_reg, result_val);
4221   return true;
4222 }
4223 
4224 //---------------------------inline_native_getClass----------------------------
4225 // public final native Class<?> java.lang.Object.getClass();
4226 //
4227 // Build special case code for calls to getClass on an object.
4228 bool LibraryCallKit::inline_native_getClass() {
4229   Node* obj = argument(0);
4230   if (obj->is_InlineTypeBase()) {
4231     const Type* t = _gvn.type(obj);
4232     if (t->maybe_null()) {
4233       null_check(obj);
4234     }
4235     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
4236     return true;
4237   }
4238   obj = null_check_receiver();
4239   if (stopped())  return true;
4240   set_result(load_mirror_from_klass(load_object_klass(obj)));
4241   return true;
4242 }
4243 
4244 //-----------------inline_native_Reflection_getCallerClass---------------------
4245 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4246 //
4247 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4248 //
4249 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4250 // in that it must skip particular security frames and checks for
4251 // caller sensitive methods.
4252 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4253 #ifndef PRODUCT
4254   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4255     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4256   }
4257 #endif
4258 
4259   if (!jvms()->has_method()) {
4260 #ifndef PRODUCT
4261     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4262       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
4263     }
4264 #endif
4265     return false;
4266   }
4267 
4268   // Walk back up the JVM state to find the caller at the required
4269   // depth.
4270   JVMState* caller_jvms = jvms();
4271 
4272   // Cf. JVM_GetCallerClass
4273   // NOTE: Start the loop at depth 1 because the current JVM state does
4274   // not include the Reflection.getCallerClass() frame.
4275   for (int n = 1; caller_jvms != NULL; caller_jvms = caller_jvms->caller(), n++) {
4276     ciMethod* m = caller_jvms->method();
4277     switch (n) {
4278     case 0:
4279       fatal("current JVM state does not include the Reflection.getCallerClass frame");
4280       break;
4281     case 1:
4282       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
4283       if (!m->caller_sensitive()) {
4284 #ifndef PRODUCT
4285         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4286           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
4287         }
4288 #endif
4289         return false;  // bail-out; let JVM_GetCallerClass do the work
4290       }
4291       break;
4292     default:
4293       if (!m->is_ignored_by_security_stack_walk()) {
4294         // We have reached the desired frame; return the holder class.
4295         // Acquire method holder as java.lang.Class and push as constant.
4296         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
4297         ciInstance* caller_mirror = caller_klass->java_mirror();
4298         set_result(makecon(TypeInstPtr::make(caller_mirror)));
4299 
4300 #ifndef PRODUCT
4301         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4302           tty->print_cr("  Succeeded: caller = %d) %s.%s, JVMS depth = %d", n, caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), jvms()->depth());
4303           tty->print_cr("  JVM state at this point:");
4304           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4305             ciMethod* m = jvms()->of_depth(i)->method();
4306             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4307           }
4308         }
4309 #endif
4310         return true;
4311       }
4312       break;
4313     }
4314   }
4315 
4316 #ifndef PRODUCT
4317   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4318     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
4319     tty->print_cr("  JVM state at this point:");
4320     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4321       ciMethod* m = jvms()->of_depth(i)->method();
4322       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4323     }
4324   }
4325 #endif
4326 
4327   return false;  // bail-out; let JVM_GetCallerClass do the work
4328 }
4329 
4330 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
4331   Node* arg = argument(0);
4332   Node* result = NULL;
4333 
4334   switch (id) {
4335   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
4336   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
4337   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
4338   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
4339 
4340   case vmIntrinsics::_doubleToLongBits: {
4341     // two paths (plus control) merge in a wood
4342     RegionNode *r = new RegionNode(3);
4343     Node *phi = new PhiNode(r, TypeLong::LONG);
4344 
4345     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
4346     // Build the boolean node
4347     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4348 
4349     // Branch either way.
4350     // NaN case is less traveled, which makes all the difference.
4351     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4352     Node *opt_isnan = _gvn.transform(ifisnan);
4353     assert( opt_isnan->is_If(), "Expect an IfNode");
4354     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4355     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4356 
4357     set_control(iftrue);
4358 
4359     static const jlong nan_bits = CONST64(0x7ff8000000000000);
4360     Node *slow_result = longcon(nan_bits); // return NaN
4361     phi->init_req(1, _gvn.transform( slow_result ));
4362     r->init_req(1, iftrue);
4363 
4364     // Else fall through
4365     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4366     set_control(iffalse);
4367 
4368     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
4369     r->init_req(2, iffalse);
4370 
4371     // Post merge
4372     set_control(_gvn.transform(r));
4373     record_for_igvn(r);
4374 
4375     C->set_has_split_ifs(true); // Has chance for split-if optimization
4376     result = phi;
4377     assert(result->bottom_type()->isa_long(), "must be");
4378     break;
4379   }
4380 
4381   case vmIntrinsics::_floatToIntBits: {
4382     // two paths (plus control) merge in a wood
4383     RegionNode *r = new RegionNode(3);
4384     Node *phi = new PhiNode(r, TypeInt::INT);
4385 
4386     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
4387     // Build the boolean node
4388     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4389 
4390     // Branch either way.
4391     // NaN case is less traveled, which makes all the difference.
4392     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4393     Node *opt_isnan = _gvn.transform(ifisnan);
4394     assert( opt_isnan->is_If(), "Expect an IfNode");
4395     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4396     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4397 
4398     set_control(iftrue);
4399 
4400     static const jint nan_bits = 0x7fc00000;
4401     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
4402     phi->init_req(1, _gvn.transform( slow_result ));
4403     r->init_req(1, iftrue);
4404 
4405     // Else fall through
4406     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4407     set_control(iffalse);
4408 
4409     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
4410     r->init_req(2, iffalse);
4411 
4412     // Post merge
4413     set_control(_gvn.transform(r));
4414     record_for_igvn(r);
4415 
4416     C->set_has_split_ifs(true); // Has chance for split-if optimization
4417     result = phi;
4418     assert(result->bottom_type()->isa_int(), "must be");
4419     break;
4420   }
4421 
4422   default:
4423     fatal_unexpected_iid(id);
4424     break;
4425   }
4426   set_result(_gvn.transform(result));
4427   return true;
4428 }
4429 
4430 //----------------------inline_unsafe_copyMemory-------------------------
4431 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
4432 
4433 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
4434   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
4435   const Type*       base_t = gvn.type(base);
4436 
4437   bool in_native = (base_t == TypePtr::NULL_PTR);
4438   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
4439   bool is_mixed  = !in_heap && !in_native;
4440 
4441   if (is_mixed) {
4442     return true; // mixed accesses can touch both on-heap and off-heap memory
4443   }
4444   if (in_heap) {
4445     bool is_prim_array = (addr_t != NULL) && (addr_t->elem() != Type::BOTTOM);
4446     if (!is_prim_array) {
4447       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
4448       // there's not enough type information available to determine proper memory slice for it.
4449       return true;
4450     }
4451   }
4452   return false;
4453 }
4454 
4455 bool LibraryCallKit::inline_unsafe_copyMemory() {
4456   if (callee()->is_static())  return false;  // caller must have the capability!
4457   null_check_receiver();  // null-check receiver
4458   if (stopped())  return true;
4459 
4460   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
4461 
4462   Node* src_base =         argument(1);  // type: oop
4463   Node* src_off  = ConvL2X(argument(2)); // type: long
4464   Node* dst_base =         argument(4);  // type: oop
4465   Node* dst_off  = ConvL2X(argument(5)); // type: long
4466   Node* size     = ConvL2X(argument(7)); // type: long
4467 
4468   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
4469          "fieldOffset must be byte-scaled");
4470 
4471   Node* src_addr = make_unsafe_address(src_base, src_off);
4472   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
4473 
4474   Node* thread = _gvn.transform(new ThreadLocalNode());
4475   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
4476   BasicType doing_unsafe_access_bt = T_BYTE;
4477   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
4478 
4479   // update volatile field
4480   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, Compile::AliasIdxRaw, MemNode::unordered);
4481 
4482   int flags = RC_LEAF | RC_NO_FP;
4483 
4484   const TypePtr* dst_type = TypePtr::BOTTOM;
4485 
4486   // Adjust memory effects of the runtime call based on input values.
4487   if (!has_wide_mem(_gvn, src_addr, src_base) &&
4488       !has_wide_mem(_gvn, dst_addr, dst_base)) {
4489     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
4490 
4491     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
4492     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
4493       flags |= RC_NARROW_MEM; // narrow in memory
4494     }
4495   }
4496 
4497   // Call it.  Note that the length argument is not scaled.
4498   make_runtime_call(flags,
4499                     OptoRuntime::fast_arraycopy_Type(),
4500                     StubRoutines::unsafe_arraycopy(),
4501                     "unsafe_arraycopy",
4502                     dst_type,
4503                     src_addr, dst_addr, size XTOP);
4504 
4505   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, Compile::AliasIdxRaw, MemNode::unordered);
4506 
4507   return true;
4508 }
4509 
4510 #undef XTOP
4511 
4512 //------------------------clone_coping-----------------------------------
4513 // Helper function for inline_native_clone.
4514 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
4515   assert(obj_size != NULL, "");
4516   Node* raw_obj = alloc_obj->in(1);
4517   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
4518 
4519   AllocateNode* alloc = NULL;
4520   if (ReduceBulkZeroing) {
4521     // We will be completely responsible for initializing this object -
4522     // mark Initialize node as complete.
4523     alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
4524     // The object was just allocated - there should be no any stores!
4525     guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");
4526     // Mark as complete_with_arraycopy so that on AllocateNode
4527     // expansion, we know this AllocateNode is initialized by an array
4528     // copy and a StoreStore barrier exists after the array copy.
4529     alloc->initialization()->set_complete_with_arraycopy();
4530   }
4531 
4532   Node* size = _gvn.transform(obj_size);
4533   access_clone(obj, alloc_obj, size, is_array);
4534 
4535   // Do not let reads from the cloned object float above the arraycopy.
4536   if (alloc != NULL) {
4537     // Do not let stores that initialize this object be reordered with
4538     // a subsequent store that would make this object accessible by
4539     // other threads.
4540     // Record what AllocateNode this StoreStore protects so that
4541     // escape analysis can go from the MemBarStoreStoreNode to the
4542     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
4543     // based on the escape status of the AllocateNode.
4544     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
4545   } else {
4546     insert_mem_bar(Op_MemBarCPUOrder);
4547   }
4548 }
4549 
4550 //------------------------inline_native_clone----------------------------
4551 // protected native Object java.lang.Object.clone();
4552 //
4553 // Here are the simple edge cases:
4554 //  null receiver => normal trap
4555 //  virtual and clone was overridden => slow path to out-of-line clone
4556 //  not cloneable or finalizer => slow path to out-of-line Object.clone
4557 //
4558 // The general case has two steps, allocation and copying.
4559 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
4560 //
4561 // Copying also has two cases, oop arrays and everything else.
4562 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
4563 // Everything else uses the tight inline loop supplied by CopyArrayNode.
4564 //
4565 // These steps fold up nicely if and when the cloned object's klass
4566 // can be sharply typed as an object array, a type array, or an instance.
4567 //
4568 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
4569   PhiNode* result_val;
4570 
4571   // Set the reexecute bit for the interpreter to reexecute
4572   // the bytecode that invokes Object.clone if deoptimization happens.
4573   { PreserveReexecuteState preexecs(this);
4574     jvms()->set_should_reexecute(true);
4575 
4576     Node* obj = argument(0);
4577     if (obj->is_InlineType()) {
4578       return false;
4579     }
4580 
4581     obj = null_check_receiver();
4582     if (stopped())  return true;
4583 
4584     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
4585 
4586     // If we are going to clone an instance, we need its exact type to
4587     // know the number and types of fields to convert the clone to
4588     // loads/stores. Maybe a speculative type can help us.
4589     if (!obj_type->klass_is_exact() &&
4590         obj_type->speculative_type() != NULL &&
4591         obj_type->speculative_type()->is_instance_klass() &&
4592         !obj_type->speculative_type()->is_inlinetype()) {
4593       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
4594       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
4595           !spec_ik->has_injected_fields()) {
4596         ciKlass* k = obj_type->klass();
4597         if (!k->is_instance_klass() ||
4598             k->as_instance_klass()->is_interface() ||
4599             k->as_instance_klass()->has_subklass()) {
4600           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
4601         }
4602       }
4603     }
4604 
4605     // Conservatively insert a memory barrier on all memory slices.
4606     // Do not let writes into the original float below the clone.
4607     insert_mem_bar(Op_MemBarCPUOrder);
4608 
4609     // paths into result_reg:
4610     enum {
4611       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
4612       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
4613       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
4614       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
4615       PATH_LIMIT
4616     };
4617     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4618     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4619     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
4620     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4621     record_for_igvn(result_reg);
4622 
4623     Node* obj_klass = load_object_klass(obj);
4624     // We only go to the fast case code if we pass a number of guards.
4625     // The paths which do not pass are accumulated in the slow_region.
4626     RegionNode* slow_region = new RegionNode(1);
4627     record_for_igvn(slow_region);
4628 
4629     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);
4630     if (array_ctl != NULL) {
4631       // It's an array.
4632       PreserveJVMState pjvms(this);
4633       set_control(array_ctl);
4634 
4635       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4636       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
4637       if (UseFlatArray && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
4638           obj_type->klass()->can_be_inline_array_klass() &&
4639           (ary_ptr == NULL || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
4640         // Flattened inline type array may have object field that would require a
4641         // write barrier. Conservatively, go to slow path.
4642         generate_flatArray_guard(obj_klass, slow_region);
4643       }
4644 
4645       if (!stopped()) {
4646         Node* obj_length = load_array_length(obj);
4647         Node* obj_size  = NULL;
4648         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &obj_size, /*deoptimize_on_exception=*/true);
4649 
4650         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4651         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
4652           // If it is an oop array, it requires very special treatment,
4653           // because gc barriers are required when accessing the array.
4654           Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);
4655           if (is_obja != NULL) {
4656             PreserveJVMState pjvms2(this);
4657             set_control(is_obja);
4658             // Generate a direct call to the right arraycopy function(s).
4659             // Clones are always tightly coupled.
4660             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
4661             ac->set_clone_oop_array();
4662             Node* n = _gvn.transform(ac);
4663             assert(n == ac, "cannot disappear");
4664             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
4665 
4666             result_reg->init_req(_objArray_path, control());
4667             result_val->init_req(_objArray_path, alloc_obj);
4668             result_i_o ->set_req(_objArray_path, i_o());
4669             result_mem ->set_req(_objArray_path, reset_memory());
4670           }
4671         }
4672         // Otherwise, there are no barriers to worry about.
4673         // (We can dispense with card marks if we know the allocation
4674         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
4675         //  causes the non-eden paths to take compensating steps to
4676         //  simulate a fresh allocation, so that no further
4677         //  card marks are required in compiled code to initialize
4678         //  the object.)
4679 
4680         if (!stopped()) {
4681           copy_to_clone(obj, alloc_obj, obj_size, true);
4682 
4683           // Present the results of the copy.
4684           result_reg->init_req(_array_path, control());
4685           result_val->init_req(_array_path, alloc_obj);
4686           result_i_o ->set_req(_array_path, i_o());
4687           result_mem ->set_req(_array_path, reset_memory());
4688         }
4689       }
4690     }
4691 
4692     if (!stopped()) {
4693       // It's an instance (we did array above).  Make the slow-path tests.
4694       // If this is a virtual call, we generate a funny guard.  We grab
4695       // the vtable entry corresponding to clone() from the target object.
4696       // If the target method which we are calling happens to be the
4697       // Object clone() method, we pass the guard.  We do not need this
4698       // guard for non-virtual calls; the caller is known to be the native
4699       // Object clone().
4700       if (is_virtual) {
4701         generate_virtual_guard(obj_klass, slow_region);
4702       }
4703 
4704       // The object must be easily cloneable and must not have a finalizer.
4705       // Both of these conditions may be checked in a single test.
4706       // We could optimize the test further, but we don't care.
4707       generate_access_flags_guard(obj_klass,
4708                                   // Test both conditions:
4709                                   JVM_ACC_IS_CLONEABLE_FAST | JVM_ACC_HAS_FINALIZER,
4710                                   // Must be cloneable but not finalizer:
4711                                   JVM_ACC_IS_CLONEABLE_FAST,
4712                                   slow_region);
4713     }
4714 
4715     if (!stopped()) {
4716       // It's an instance, and it passed the slow-path tests.
4717       PreserveJVMState pjvms(this);
4718       Node* obj_size  = NULL;
4719       // Need to deoptimize on exception from allocation since Object.clone intrinsic
4720       // is reexecuted if deoptimization occurs and there could be problems when merging
4721       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
4722       Node* alloc_obj = new_instance(obj_klass, NULL, &obj_size, /*deoptimize_on_exception=*/true);
4723 
4724       copy_to_clone(obj, alloc_obj, obj_size, false);
4725 
4726       // Present the results of the slow call.
4727       result_reg->init_req(_instance_path, control());
4728       result_val->init_req(_instance_path, alloc_obj);
4729       result_i_o ->set_req(_instance_path, i_o());
4730       result_mem ->set_req(_instance_path, reset_memory());
4731     }
4732 
4733     // Generate code for the slow case.  We make a call to clone().
4734     set_control(_gvn.transform(slow_region));
4735     if (!stopped()) {
4736       PreserveJVMState pjvms(this);
4737       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);
4738       // We need to deoptimize on exception (see comment above)
4739       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
4740       // this->control() comes from set_results_for_java_call
4741       result_reg->init_req(_slow_path, control());
4742       result_val->init_req(_slow_path, slow_result);
4743       result_i_o ->set_req(_slow_path, i_o());
4744       result_mem ->set_req(_slow_path, reset_memory());
4745     }
4746 
4747     // Return the combined state.
4748     set_control(    _gvn.transform(result_reg));
4749     set_i_o(        _gvn.transform(result_i_o));
4750     set_all_memory( _gvn.transform(result_mem));
4751   } // original reexecute is set back here
4752 
4753   set_result(_gvn.transform(result_val));
4754   return true;
4755 }
4756 
4757 // If we have a tightly coupled allocation, the arraycopy may take care
4758 // of the array initialization. If one of the guards we insert between
4759 // the allocation and the arraycopy causes a deoptimization, an
4760 // unitialized array will escape the compiled method. To prevent that
4761 // we set the JVM state for uncommon traps between the allocation and
4762 // the arraycopy to the state before the allocation so, in case of
4763 // deoptimization, we'll reexecute the allocation and the
4764 // initialization.
4765 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
4766   if (alloc != NULL) {
4767     ciMethod* trap_method = alloc->jvms()->method();
4768     int trap_bci = alloc->jvms()->bci();
4769 
4770     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
4771         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
4772       // Make sure there's no store between the allocation and the
4773       // arraycopy otherwise visible side effects could be rexecuted
4774       // in case of deoptimization and cause incorrect execution.
4775       bool no_interfering_store = true;
4776       Node* mem = alloc->in(TypeFunc::Memory);
4777       if (mem->is_MergeMem()) {
4778         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
4779           Node* n = mms.memory();
4780           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4781             assert(n->is_Store(), "what else?");
4782             no_interfering_store = false;
4783             break;
4784           }
4785         }
4786       } else {
4787         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
4788           Node* n = mms.memory();
4789           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4790             assert(n->is_Store(), "what else?");
4791             no_interfering_store = false;
4792             break;
4793           }
4794         }
4795       }
4796 
4797       if (no_interfering_store) {
4798         JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
4799         uint size = alloc->req();
4800         SafePointNode* sfpt = new SafePointNode(size, old_jvms);
4801         old_jvms->set_map(sfpt);
4802         for (uint i = 0; i < size; i++) {
4803           sfpt->init_req(i, alloc->in(i));
4804         }
4805         // re-push array length for deoptimization
4806         sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
4807         old_jvms->set_sp(old_jvms->sp()+1);
4808         old_jvms->set_monoff(old_jvms->monoff()+1);
4809         old_jvms->set_scloff(old_jvms->scloff()+1);
4810         old_jvms->set_endoff(old_jvms->endoff()+1);
4811         old_jvms->set_should_reexecute(true);
4812 
4813         sfpt->set_i_o(map()->i_o());
4814         sfpt->set_memory(map()->memory());
4815         sfpt->set_control(map()->control());
4816 
4817         JVMState* saved_jvms = jvms();
4818         saved_reexecute_sp = _reexecute_sp;
4819 
4820         set_jvms(sfpt->jvms());
4821         _reexecute_sp = jvms()->sp();
4822 
4823         return saved_jvms;
4824       }
4825     }
4826   }
4827   return NULL;
4828 }
4829 
4830 // In case of a deoptimization, we restart execution at the
4831 // allocation, allocating a new array. We would leave an uninitialized
4832 // array in the heap that GCs wouldn't expect. Move the allocation
4833 // after the traps so we don't allocate the array if we
4834 // deoptimize. This is possible because tightly_coupled_allocation()
4835 // guarantees there's no observer of the allocated array at this point
4836 // and the control flow is simple enough.
4837 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms,
4838                                                     int saved_reexecute_sp, uint new_idx) {
4839   if (saved_jvms != NULL && !stopped()) {
4840     assert(alloc != NULL, "only with a tightly coupled allocation");
4841     // restore JVM state to the state at the arraycopy
4842     saved_jvms->map()->set_control(map()->control());
4843     assert(saved_jvms->map()->memory() == map()->memory(), "memory state changed?");
4844     assert(saved_jvms->map()->i_o() == map()->i_o(), "IO state changed?");
4845     // If we've improved the types of some nodes (null check) while
4846     // emitting the guards, propagate them to the current state
4847     map()->replaced_nodes().apply(saved_jvms->map(), new_idx);
4848     set_jvms(saved_jvms);
4849     _reexecute_sp = saved_reexecute_sp;
4850 
4851     // Remove the allocation from above the guards
4852     CallProjections* callprojs = alloc->extract_projections(true);
4853     InitializeNode* init = alloc->initialization();
4854     Node* alloc_mem = alloc->in(TypeFunc::Memory);
4855     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
4856     C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
4857 
4858     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
4859     // the allocation (i.e. is only valid if the allocation succeeds):
4860     // 1) replace CastIINode with AllocateArrayNode's length here
4861     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
4862     //
4863     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
4864     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
4865     Node* init_control = init->proj_out(TypeFunc::Control);
4866     Node* alloc_length = alloc->Ideal_length();
4867 #ifdef ASSERT
4868     Node* prev_cast = NULL;
4869 #endif
4870     for (uint i = 0; i < init_control->outcnt(); i++) {
4871       Node* init_out = init_control->raw_out(i);
4872       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
4873 #ifdef ASSERT
4874         if (prev_cast == NULL) {
4875           prev_cast = init_out;
4876         } else {
4877           if (prev_cast->cmp(*init_out) == false) {
4878             prev_cast->dump();
4879             init_out->dump();
4880             assert(false, "not equal CastIINode");
4881           }
4882         }
4883 #endif
4884         C->gvn_replace_by(init_out, alloc_length);
4885       }
4886     }
4887     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
4888 
4889     // move the allocation here (after the guards)
4890     _gvn.hash_delete(alloc);
4891     alloc->set_req(TypeFunc::Control, control());
4892     alloc->set_req(TypeFunc::I_O, i_o());
4893     Node *mem = reset_memory();
4894     set_all_memory(mem);
4895     alloc->set_req(TypeFunc::Memory, mem);
4896     set_control(init->proj_out_or_null(TypeFunc::Control));
4897     set_i_o(callprojs->fallthrough_ioproj);
4898 
4899     // Update memory as done in GraphKit::set_output_for_allocation()
4900     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
4901     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
4902     if (ary_type->isa_aryptr() && length_type != NULL) {
4903       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4904     }
4905     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
4906     int            elemidx  = C->get_alias_index(telemref);
4907     set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
4908     set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
4909 
4910     Node* allocx = _gvn.transform(alloc);
4911     assert(allocx == alloc, "where has the allocation gone?");
4912     assert(dest->is_CheckCastPP(), "not an allocation result?");
4913 
4914     _gvn.hash_delete(dest);
4915     dest->set_req(0, control());
4916     Node* destx = _gvn.transform(dest);
4917     assert(destx == dest, "where has the allocation result gone?");
4918 
4919     array_ideal_length(alloc, ary_type, true);
4920   }
4921 }
4922 
4923 
4924 //------------------------------inline_arraycopy-----------------------
4925 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
4926 //                                                      Object dest, int destPos,
4927 //                                                      int length);
4928 bool LibraryCallKit::inline_arraycopy() {
4929   // Get the arguments.
4930   Node* src         = argument(0);  // type: oop
4931   Node* src_offset  = argument(1);  // type: int
4932   Node* dest        = argument(2);  // type: oop
4933   Node* dest_offset = argument(3);  // type: int
4934   Node* length      = argument(4);  // type: int
4935 
4936   uint new_idx = C->unique();
4937 
4938   // Check for allocation before we add nodes that would confuse
4939   // tightly_coupled_allocation()
4940   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
4941 
4942   int saved_reexecute_sp = -1;
4943   JVMState* saved_jvms = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
4944   // See arraycopy_restore_alloc_state() comment
4945   // if alloc == NULL we don't have to worry about a tightly coupled allocation so we can emit all needed guards
4946   // if saved_jvms != NULL (then alloc != NULL) then we can handle guards and a tightly coupled allocation
4947   // if saved_jvms == NULL and alloc != NULL, we can't emit any guards
4948   bool can_emit_guards = (alloc == NULL || saved_jvms != NULL);
4949 
4950   // The following tests must be performed
4951   // (1) src and dest are arrays.
4952   // (2) src and dest arrays must have elements of the same BasicType
4953   // (3) src and dest must not be null.
4954   // (4) src_offset must not be negative.
4955   // (5) dest_offset must not be negative.
4956   // (6) length must not be negative.
4957   // (7) src_offset + length must not exceed length of src.
4958   // (8) dest_offset + length must not exceed length of dest.
4959   // (9) each element of an oop array must be assignable
4960 
4961   // (3) src and dest must not be null.
4962   // always do this here because we need the JVM state for uncommon traps
4963   Node* null_ctl = top();
4964   src  = saved_jvms != NULL ? null_check_oop(src, &null_ctl, true, true) : null_check(src,  T_ARRAY);
4965   assert(null_ctl->is_top(), "no null control here");
4966   dest = null_check(dest, T_ARRAY);
4967 
4968   if (!can_emit_guards) {
4969     // if saved_jvms == NULL and alloc != NULL, we don't emit any
4970     // guards but the arraycopy node could still take advantage of a
4971     // tightly allocated allocation. tightly_coupled_allocation() is
4972     // called again to make sure it takes the null check above into
4973     // account: the null check is mandatory and if it caused an
4974     // uncommon trap to be emitted then the allocation can't be
4975     // considered tightly coupled in this context.
4976     alloc = tightly_coupled_allocation(dest);
4977   }
4978 
4979   bool validated = false;
4980 
4981   const Type* src_type  = _gvn.type(src);
4982   const Type* dest_type = _gvn.type(dest);
4983   const TypeAryPtr* top_src  = src_type->isa_aryptr();
4984   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
4985 
4986   // Do we have the type of src?
4987   bool has_src = (top_src != NULL && top_src->klass() != NULL);
4988   // Do we have the type of dest?
4989   bool has_dest = (top_dest != NULL && top_dest->klass() != NULL);
4990   // Is the type for src from speculation?
4991   bool src_spec = false;
4992   // Is the type for dest from speculation?
4993   bool dest_spec = false;
4994 
4995   if ((!has_src || !has_dest) && can_emit_guards) {
4996     // We don't have sufficient type information, let's see if
4997     // speculative types can help. We need to have types for both src
4998     // and dest so that it pays off.
4999 
5000     // Do we already have or could we have type information for src
5001     bool could_have_src = has_src;
5002     // Do we already have or could we have type information for dest
5003     bool could_have_dest = has_dest;
5004 
5005     ciKlass* src_k = NULL;
5006     if (!has_src) {
5007       src_k = src_type->speculative_type_not_null();
5008       if (src_k != NULL && src_k->is_array_klass()) {
5009         could_have_src = true;
5010       }
5011     }
5012 
5013     ciKlass* dest_k = NULL;
5014     if (!has_dest) {
5015       dest_k = dest_type->speculative_type_not_null();
5016       if (dest_k != NULL && dest_k->is_array_klass()) {
5017         could_have_dest = true;
5018       }
5019     }
5020 
5021     if (could_have_src && could_have_dest) {
5022       // This is going to pay off so emit the required guards
5023       if (!has_src) {
5024         src = maybe_cast_profiled_obj(src, src_k, true);
5025         src_type  = _gvn.type(src);
5026         top_src  = src_type->isa_aryptr();
5027         has_src = (top_src != NULL && top_src->klass() != NULL);
5028         src_spec = true;
5029       }
5030       if (!has_dest) {
5031         dest = maybe_cast_profiled_obj(dest, dest_k, true);
5032         dest_type  = _gvn.type(dest);
5033         top_dest  = dest_type->isa_aryptr();
5034         has_dest = (top_dest != NULL && top_dest->klass() != NULL);
5035         dest_spec = true;
5036       }
5037     }
5038   }
5039 
5040   if (has_src && has_dest && can_emit_guards) {
5041     BasicType src_elem  = top_src->klass()->as_array_klass()->element_type()->basic_type();
5042     BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
5043     if (is_reference_type(src_elem))   src_elem  = T_OBJECT;
5044     if (is_reference_type(dest_elem))  dest_elem = T_OBJECT;
5045 
5046     if (src_elem == dest_elem && src_elem == T_OBJECT) {
5047       // If both arrays are object arrays then having the exact types
5048       // for both will remove the need for a subtype check at runtime
5049       // before the call and may make it possible to pick a faster copy
5050       // routine (without a subtype check on every element)
5051       // Do we have the exact type of src?
5052       bool could_have_src = src_spec;
5053       // Do we have the exact type of dest?
5054       bool could_have_dest = dest_spec;
5055       ciKlass* src_k = top_src->klass();
5056       ciKlass* dest_k = top_dest->klass();
5057       if (!src_spec) {
5058         src_k = src_type->speculative_type_not_null();
5059         if (src_k != NULL && src_k->is_array_klass()) {
5060           could_have_src = true;
5061         }
5062       }
5063       if (!dest_spec) {
5064         dest_k = dest_type->speculative_type_not_null();
5065         if (dest_k != NULL && dest_k->is_array_klass()) {
5066           could_have_dest = true;
5067         }
5068       }
5069       if (could_have_src && could_have_dest) {
5070         // If we can have both exact types, emit the missing guards
5071         if (could_have_src && !src_spec) {
5072           src = maybe_cast_profiled_obj(src, src_k, true);
5073           src_type = _gvn.type(src);
5074           top_src = src_type->isa_aryptr();
5075         }
5076         if (could_have_dest && !dest_spec) {
5077           dest = maybe_cast_profiled_obj(dest, dest_k, true);
5078           dest_type = _gvn.type(dest);
5079           top_dest = dest_type->isa_aryptr();
5080         }
5081       }
5082     }
5083   }
5084 
5085   ciMethod* trap_method = method();
5086   int trap_bci = bci();
5087   if (saved_jvms != NULL) {
5088     trap_method = alloc->jvms()->method();
5089     trap_bci = alloc->jvms()->bci();
5090   }
5091 
5092   bool negative_length_guard_generated = false;
5093 
5094   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5095       can_emit_guards && !src->is_top() && !dest->is_top()) {
5096     // validate arguments: enables transformation the ArrayCopyNode
5097     validated = true;
5098 
5099     RegionNode* slow_region = new RegionNode(1);
5100     record_for_igvn(slow_region);
5101 
5102     // (1) src and dest are arrays.
5103     generate_non_array_guard(load_object_klass(src), slow_region);
5104     generate_non_array_guard(load_object_klass(dest), slow_region);
5105 
5106     // (2) src and dest arrays must have elements of the same BasicType
5107     // done at macro expansion or at Ideal transformation time
5108 
5109     // (4) src_offset must not be negative.
5110     generate_negative_guard(src_offset, slow_region);
5111 
5112     // (5) dest_offset must not be negative.
5113     generate_negative_guard(dest_offset, slow_region);
5114 
5115     // (7) src_offset + length must not exceed length of src.
5116     generate_limit_guard(src_offset, length,
5117                          load_array_length(src),
5118                          slow_region);
5119 
5120     // (8) dest_offset + length must not exceed length of dest.
5121     generate_limit_guard(dest_offset, length,
5122                          load_array_length(dest),
5123                          slow_region);
5124 
5125     // (6) length must not be negative.
5126     // This is also checked in generate_arraycopy() during macro expansion, but
5127     // we also have to check it here for the case where the ArrayCopyNode will
5128     // be eliminated by Escape Analysis.
5129     if (EliminateAllocations) {
5130       generate_negative_guard(length, slow_region);
5131       negative_length_guard_generated = true;
5132     }
5133 
5134     // (9) each element of an oop array must be assignable
5135     Node* dest_klass = load_object_klass(dest);
5136     if (src != dest) {
5137       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
5138       slow_region->add_req(not_subtype_ctrl);
5139     }
5140 
5141     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
5142     const Type* toop = TypeOopPtr::make_from_klass(dest_klass_t->klass());
5143     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
5144     src_type = _gvn.type(src);
5145     top_src  = src_type->isa_aryptr();
5146 
5147     // Handle flat inline type arrays (null-free arrays are handled by the subtype check above)
5148     if (!stopped() && UseFlatArray) {
5149       // If dest is flat, src must be flat as well (guaranteed by src <: dest check). Handle flat src here.
5150       assert(top_dest == NULL || !top_dest->is_flat() || top_src->is_flat(), "src array must be flat");
5151       if (top_src != NULL && top_src->is_flat()) {
5152         // Src is flat, check that dest is flat as well
5153         if (top_dest != NULL && !top_dest->is_flat()) {
5154           generate_non_flatArray_guard(dest_klass, slow_region);
5155           // Since dest is flat and src <: dest, dest must have the same type as src.
5156           top_dest = TypeOopPtr::make_from_klass(top_src->klass())->isa_aryptr();
5157           assert(top_dest->is_flat(), "dest must be flat");
5158           dest = _gvn.transform(new CheckCastPPNode(control(), dest, top_dest));
5159         }
5160       } else if (top_src == NULL || !top_src->is_not_flat()) {
5161         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5162         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5163         assert(top_dest == NULL || !top_dest->is_flat(), "dest array must not be flat");
5164         generate_flatArray_guard(load_object_klass(src), slow_region);
5165         if (top_src != NULL) {
5166           top_src = top_src->cast_to_not_flat();
5167           src = _gvn.transform(new CheckCastPPNode(control(), src, top_src));
5168         }
5169       }
5170     }
5171 
5172     {
5173       PreserveJVMState pjvms(this);
5174       set_control(_gvn.transform(slow_region));
5175       uncommon_trap(Deoptimization::Reason_intrinsic,
5176                     Deoptimization::Action_make_not_entrant);
5177       assert(stopped(), "Should be stopped");
5178     }
5179   }
5180 
5181   arraycopy_move_allocation_here(alloc, dest, saved_jvms, saved_reexecute_sp, new_idx);
5182 
5183   if (stopped()) {
5184     return true;
5185   }
5186 
5187   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != NULL, negative_length_guard_generated,
5188                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
5189                                           // so the compiler has a chance to eliminate them: during macro expansion,
5190                                           // we have to set their control (CastPP nodes are eliminated).
5191                                           load_object_klass(src), load_object_klass(dest),
5192                                           load_array_length(src), load_array_length(dest));
5193 
5194   ac->set_arraycopy(validated);
5195 
5196   Node* n = _gvn.transform(ac);
5197   if (n == ac) {
5198     ac->connect_outputs(this);
5199   } else {
5200     assert(validated, "shouldn't transform if all arguments not validated");
5201     set_all_memory(n);
5202   }
5203   clear_upper_avx();
5204 
5205 
5206   return true;
5207 }
5208 
5209 
5210 // Helper function which determines if an arraycopy immediately follows
5211 // an allocation, with no intervening tests or other escapes for the object.
5212 AllocateArrayNode*
5213 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
5214   if (stopped())             return NULL;  // no fast path
5215   if (C->AliasLevel() == 0)  return NULL;  // no MergeMems around
5216 
5217   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
5218   if (alloc == NULL)  return NULL;
5219 
5220   Node* rawmem = memory(Compile::AliasIdxRaw);
5221   // Is the allocation's memory state untouched?
5222   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
5223     // Bail out if there have been raw-memory effects since the allocation.
5224     // (Example:  There might have been a call or safepoint.)
5225     return NULL;
5226   }
5227   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
5228   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
5229     return NULL;
5230   }
5231 
5232   // There must be no unexpected observers of this allocation.
5233   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
5234     Node* obs = ptr->fast_out(i);
5235     if (obs != this->map()) {
5236       return NULL;
5237     }
5238   }
5239 
5240   // This arraycopy must unconditionally follow the allocation of the ptr.
5241   Node* alloc_ctl = ptr->in(0);
5242   Node* ctl = control();
5243   while (ctl != alloc_ctl) {
5244     // There may be guards which feed into the slow_region.
5245     // Any other control flow means that we might not get a chance
5246     // to finish initializing the allocated object.
5247     if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
5248       IfNode* iff = ctl->in(0)->as_If();
5249       Node* not_ctl = iff->proj_out_or_null(1 - ctl->as_Proj()->_con);
5250       assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
5251       // One more try:  Various low-level checks bottom out in
5252       // uncommon traps.  If the debug-info of the trap omits
5253       // any reference to the allocation, as we've already
5254       // observed, then there can be no objection to the trap.
5255       bool found_trap = false;
5256       for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {
5257         Node* obs = not_ctl->fast_out(j);
5258         if (obs->in(0) == not_ctl && obs->is_Call() &&
5259             (obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {
5260           found_trap = true; break;
5261         }
5262       }
5263       if (found_trap) {
5264         ctl = iff->in(0);       // This test feeds a harmless uncommon trap.
5265         continue;
5266       }
5267     }
5268     return NULL;
5269   }
5270 
5271   // If we get this far, we have an allocation which immediately
5272   // precedes the arraycopy, and we can take over zeroing the new object.
5273   // The arraycopy will finish the initialization, and provide
5274   // a new control state to which we will anchor the destination pointer.
5275 
5276   return alloc;
5277 }
5278 
5279 //-------------inline_encodeISOArray-----------------------------------
5280 // encode char[] to byte[] in ISO_8859_1 or ASCII
5281 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
5282   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
5283   // no receiver since it is static method
5284   Node *src         = argument(0);
5285   Node *src_offset  = argument(1);
5286   Node *dst         = argument(2);
5287   Node *dst_offset  = argument(3);
5288   Node *length      = argument(4);
5289 
5290   src = must_be_not_null(src, true);
5291   dst = must_be_not_null(dst, true);
5292 
5293   const Type* src_type = src->Value(&_gvn);
5294   const Type* dst_type = dst->Value(&_gvn);
5295   const TypeAryPtr* top_src = src_type->isa_aryptr();
5296   const TypeAryPtr* top_dest = dst_type->isa_aryptr();
5297   if (top_src  == NULL || top_src->klass()  == NULL ||
5298       top_dest == NULL || top_dest->klass() == NULL) {
5299     // failed array check
5300     return false;
5301   }
5302 
5303   // Figure out the size and type of the elements we will be copying.
5304   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5305   BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5306   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
5307     return false;
5308   }
5309 
5310   Node* src_start = array_element_address(src, src_offset, T_CHAR);
5311   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
5312   // 'src_start' points to src array + scaled offset
5313   // 'dst_start' points to dst array + scaled offset
5314 
5315   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
5316   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
5317   enc = _gvn.transform(enc);
5318   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
5319   set_memory(res_mem, mtype);
5320   set_result(enc);
5321   clear_upper_avx();
5322 
5323   return true;
5324 }
5325 
5326 //-------------inline_multiplyToLen-----------------------------------
5327 bool LibraryCallKit::inline_multiplyToLen() {
5328   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
5329 
5330   address stubAddr = StubRoutines::multiplyToLen();
5331   if (stubAddr == NULL) {
5332     return false; // Intrinsic's stub is not implemented on this platform
5333   }
5334   const char* stubName = "multiplyToLen";
5335 
5336   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
5337 
5338   // no receiver because it is a static method
5339   Node* x    = argument(0);
5340   Node* xlen = argument(1);
5341   Node* y    = argument(2);
5342   Node* ylen = argument(3);
5343   Node* z    = argument(4);
5344 
5345   x = must_be_not_null(x, true);
5346   y = must_be_not_null(y, true);
5347 
5348   const Type* x_type = x->Value(&_gvn);
5349   const Type* y_type = y->Value(&_gvn);
5350   const TypeAryPtr* top_x = x_type->isa_aryptr();
5351   const TypeAryPtr* top_y = y_type->isa_aryptr();
5352   if (top_x  == NULL || top_x->klass()  == NULL ||
5353       top_y == NULL || top_y->klass() == NULL) {
5354     // failed array check
5355     return false;
5356   }
5357 
5358   BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5359   BasicType y_elem = y_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5360   if (x_elem != T_INT || y_elem != T_INT) {
5361     return false;
5362   }
5363 
5364   // Set the original stack and the reexecute bit for the interpreter to reexecute
5365   // the bytecode that invokes BigInteger.multiplyToLen() if deoptimization happens
5366   // on the return from z array allocation in runtime.
5367   { PreserveReexecuteState preexecs(this);
5368     jvms()->set_should_reexecute(true);
5369 
5370     Node* x_start = array_element_address(x, intcon(0), x_elem);
5371     Node* y_start = array_element_address(y, intcon(0), y_elem);
5372     // 'x_start' points to x array + scaled xlen
5373     // 'y_start' points to y array + scaled ylen
5374 
5375     // Allocate the result array
5376     Node* zlen = _gvn.transform(new AddINode(xlen, ylen));
5377     ciKlass* klass = ciTypeArrayKlass::make(T_INT);
5378     Node* klass_node = makecon(TypeKlassPtr::make(klass));
5379 
5380     IdealKit ideal(this);
5381 
5382 #define __ ideal.
5383      Node* one = __ ConI(1);
5384      Node* zero = __ ConI(0);
5385      IdealVariable need_alloc(ideal), z_alloc(ideal);  __ declarations_done();
5386      __ set(need_alloc, zero);
5387      __ set(z_alloc, z);
5388      __ if_then(z, BoolTest::eq, null()); {
5389        __ increment (need_alloc, one);
5390      } __ else_(); {
5391        // Update graphKit memory and control from IdealKit.
5392        sync_kit(ideal);
5393        Node *cast = new CastPPNode(z, TypePtr::NOTNULL);
5394        cast->init_req(0, control());
5395        _gvn.set_type(cast, cast->bottom_type());
5396        C->record_for_igvn(cast);
5397 
5398        Node* zlen_arg = load_array_length(cast);
5399        // Update IdealKit memory and control from graphKit.
5400        __ sync_kit(this);
5401        __ if_then(zlen_arg, BoolTest::lt, zlen); {
5402          __ increment (need_alloc, one);
5403        } __ end_if();
5404      } __ end_if();
5405 
5406      __ if_then(__ value(need_alloc), BoolTest::ne, zero); {
5407        // Update graphKit memory and control from IdealKit.
5408        sync_kit(ideal);
5409        Node * narr = new_array(klass_node, zlen, 1);
5410        // Update IdealKit memory and control from graphKit.
5411        __ sync_kit(this);
5412        __ set(z_alloc, narr);
5413      } __ end_if();
5414 
5415      sync_kit(ideal);
5416      z = __ value(z_alloc);
5417      // Can't use TypeAryPtr::INTS which uses Bottom offset.
5418      _gvn.set_type(z, TypeOopPtr::make_from_klass(klass));
5419      // Final sync IdealKit and GraphKit.
5420      final_sync(ideal);
5421 #undef __
5422 
5423     Node* z_start = array_element_address(z, intcon(0), T_INT);
5424 
5425     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
5426                                    OptoRuntime::multiplyToLen_Type(),
5427                                    stubAddr, stubName, TypePtr::BOTTOM,
5428                                    x_start, xlen, y_start, ylen, z_start, zlen);
5429   } // original reexecute is set back here
5430 
5431   C->set_has_split_ifs(true); // Has chance for split-if optimization
5432   set_result(z);
5433   return true;
5434 }
5435 
5436 //-------------inline_squareToLen------------------------------------
5437 bool LibraryCallKit::inline_squareToLen() {
5438   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
5439 
5440   address stubAddr = StubRoutines::squareToLen();
5441   if (stubAddr == NULL) {
5442     return false; // Intrinsic's stub is not implemented on this platform
5443   }
5444   const char* stubName = "squareToLen";
5445 
5446   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
5447 
5448   Node* x    = argument(0);
5449   Node* len  = argument(1);
5450   Node* z    = argument(2);
5451   Node* zlen = argument(3);
5452 
5453   x = must_be_not_null(x, true);
5454   z = must_be_not_null(z, true);
5455 
5456   const Type* x_type = x->Value(&_gvn);
5457   const Type* z_type = z->Value(&_gvn);
5458   const TypeAryPtr* top_x = x_type->isa_aryptr();
5459   const TypeAryPtr* top_z = z_type->isa_aryptr();
5460   if (top_x  == NULL || top_x->klass()  == NULL ||
5461       top_z  == NULL || top_z->klass()  == NULL) {
5462     // failed array check
5463     return false;
5464   }
5465 
5466   BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5467   BasicType z_elem = z_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5468   if (x_elem != T_INT || z_elem != T_INT) {
5469     return false;
5470   }
5471 
5472 
5473   Node* x_start = array_element_address(x, intcon(0), x_elem);
5474   Node* z_start = array_element_address(z, intcon(0), z_elem);
5475 
5476   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
5477                                   OptoRuntime::squareToLen_Type(),
5478                                   stubAddr, stubName, TypePtr::BOTTOM,
5479                                   x_start, len, z_start, zlen);
5480 
5481   set_result(z);
5482   return true;
5483 }
5484 
5485 //-------------inline_mulAdd------------------------------------------
5486 bool LibraryCallKit::inline_mulAdd() {
5487   assert(UseMulAddIntrinsic, "not implemented on this platform");
5488 
5489   address stubAddr = StubRoutines::mulAdd();
5490   if (stubAddr == NULL) {
5491     return false; // Intrinsic's stub is not implemented on this platform
5492   }
5493   const char* stubName = "mulAdd";
5494 
5495   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
5496 
5497   Node* out      = argument(0);
5498   Node* in       = argument(1);
5499   Node* offset   = argument(2);
5500   Node* len      = argument(3);
5501   Node* k        = argument(4);
5502 
5503   out = must_be_not_null(out, true);
5504 
5505   const Type* out_type = out->Value(&_gvn);
5506   const Type* in_type = in->Value(&_gvn);
5507   const TypeAryPtr* top_out = out_type->isa_aryptr();
5508   const TypeAryPtr* top_in = in_type->isa_aryptr();
5509   if (top_out  == NULL || top_out->klass()  == NULL ||
5510       top_in == NULL || top_in->klass() == NULL) {
5511     // failed array check
5512     return false;
5513   }
5514 
5515   BasicType out_elem = out_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5516   BasicType in_elem = in_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5517   if (out_elem != T_INT || in_elem != T_INT) {
5518     return false;
5519   }
5520 
5521   Node* outlen = load_array_length(out);
5522   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
5523   Node* out_start = array_element_address(out, intcon(0), out_elem);
5524   Node* in_start = array_element_address(in, intcon(0), in_elem);
5525 
5526   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
5527                                   OptoRuntime::mulAdd_Type(),
5528                                   stubAddr, stubName, TypePtr::BOTTOM,
5529                                   out_start,in_start, new_offset, len, k);
5530   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5531   set_result(result);
5532   return true;
5533 }
5534 
5535 //-------------inline_montgomeryMultiply-----------------------------------
5536 bool LibraryCallKit::inline_montgomeryMultiply() {
5537   address stubAddr = StubRoutines::montgomeryMultiply();
5538   if (stubAddr == NULL) {
5539     return false; // Intrinsic's stub is not implemented on this platform
5540   }
5541 
5542   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
5543   const char* stubName = "montgomery_multiply";
5544 
5545   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
5546 
5547   Node* a    = argument(0);
5548   Node* b    = argument(1);
5549   Node* n    = argument(2);
5550   Node* len  = argument(3);
5551   Node* inv  = argument(4);
5552   Node* m    = argument(6);
5553 
5554   const Type* a_type = a->Value(&_gvn);
5555   const TypeAryPtr* top_a = a_type->isa_aryptr();
5556   const Type* b_type = b->Value(&_gvn);
5557   const TypeAryPtr* top_b = b_type->isa_aryptr();
5558   const Type* n_type = a->Value(&_gvn);
5559   const TypeAryPtr* top_n = n_type->isa_aryptr();
5560   const Type* m_type = a->Value(&_gvn);
5561   const TypeAryPtr* top_m = m_type->isa_aryptr();
5562   if (top_a  == NULL || top_a->klass()  == NULL ||
5563       top_b == NULL || top_b->klass()  == NULL ||
5564       top_n == NULL || top_n->klass()  == NULL ||
5565       top_m == NULL || top_m->klass()  == NULL) {
5566     // failed array check
5567     return false;
5568   }
5569 
5570   BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5571   BasicType b_elem = b_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5572   BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5573   BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5574   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
5575     return false;
5576   }
5577 
5578   // Make the call
5579   {
5580     Node* a_start = array_element_address(a, intcon(0), a_elem);
5581     Node* b_start = array_element_address(b, intcon(0), b_elem);
5582     Node* n_start = array_element_address(n, intcon(0), n_elem);
5583     Node* m_start = array_element_address(m, intcon(0), m_elem);
5584 
5585     Node* call = make_runtime_call(RC_LEAF,
5586                                    OptoRuntime::montgomeryMultiply_Type(),
5587                                    stubAddr, stubName, TypePtr::BOTTOM,
5588                                    a_start, b_start, n_start, len, inv, top(),
5589                                    m_start);
5590     set_result(m);
5591   }
5592 
5593   return true;
5594 }
5595 
5596 bool LibraryCallKit::inline_montgomerySquare() {
5597   address stubAddr = StubRoutines::montgomerySquare();
5598   if (stubAddr == NULL) {
5599     return false; // Intrinsic's stub is not implemented on this platform
5600   }
5601 
5602   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
5603   const char* stubName = "montgomery_square";
5604 
5605   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
5606 
5607   Node* a    = argument(0);
5608   Node* n    = argument(1);
5609   Node* len  = argument(2);
5610   Node* inv  = argument(3);
5611   Node* m    = argument(5);
5612 
5613   const Type* a_type = a->Value(&_gvn);
5614   const TypeAryPtr* top_a = a_type->isa_aryptr();
5615   const Type* n_type = a->Value(&_gvn);
5616   const TypeAryPtr* top_n = n_type->isa_aryptr();
5617   const Type* m_type = a->Value(&_gvn);
5618   const TypeAryPtr* top_m = m_type->isa_aryptr();
5619   if (top_a  == NULL || top_a->klass()  == NULL ||
5620       top_n == NULL || top_n->klass()  == NULL ||
5621       top_m == NULL || top_m->klass()  == NULL) {
5622     // failed array check
5623     return false;
5624   }
5625 
5626   BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5627   BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5628   BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5629   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
5630     return false;
5631   }
5632 
5633   // Make the call
5634   {
5635     Node* a_start = array_element_address(a, intcon(0), a_elem);
5636     Node* n_start = array_element_address(n, intcon(0), n_elem);
5637     Node* m_start = array_element_address(m, intcon(0), m_elem);
5638 
5639     Node* call = make_runtime_call(RC_LEAF,
5640                                    OptoRuntime::montgomerySquare_Type(),
5641                                    stubAddr, stubName, TypePtr::BOTTOM,
5642                                    a_start, n_start, len, inv, top(),
5643                                    m_start);
5644     set_result(m);
5645   }
5646 
5647   return true;
5648 }
5649 
5650 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
5651   address stubAddr = NULL;
5652   const char* stubName = NULL;
5653 
5654   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
5655   if (stubAddr == NULL) {
5656     return false; // Intrinsic's stub is not implemented on this platform
5657   }
5658 
5659   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
5660 
5661   assert(callee()->signature()->size() == 5, "expected 5 arguments");
5662 
5663   Node* newArr = argument(0);
5664   Node* oldArr = argument(1);
5665   Node* newIdx = argument(2);
5666   Node* shiftCount = argument(3);
5667   Node* numIter = argument(4);
5668 
5669   const Type* newArr_type = newArr->Value(&_gvn);
5670   const TypeAryPtr* top_newArr = newArr_type->isa_aryptr();
5671   const Type* oldArr_type = oldArr->Value(&_gvn);
5672   const TypeAryPtr* top_oldArr = oldArr_type->isa_aryptr();
5673   if (top_newArr == NULL || top_newArr->klass() == NULL || top_oldArr == NULL
5674       || top_oldArr->klass() == NULL) {
5675     return false;
5676   }
5677 
5678   BasicType newArr_elem = newArr_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5679   BasicType oldArr_elem = oldArr_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5680   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
5681     return false;
5682   }
5683 
5684   // Make the call
5685   {
5686     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
5687     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
5688 
5689     Node* call = make_runtime_call(RC_LEAF,
5690                                    OptoRuntime::bigIntegerShift_Type(),
5691                                    stubAddr,
5692                                    stubName,
5693                                    TypePtr::BOTTOM,
5694                                    newArr_start,
5695                                    oldArr_start,
5696                                    newIdx,
5697                                    shiftCount,
5698                                    numIter);
5699   }
5700 
5701   return true;
5702 }
5703 
5704 //-------------inline_vectorizedMismatch------------------------------
5705 bool LibraryCallKit::inline_vectorizedMismatch() {
5706   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
5707 
5708   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
5709   Node* obja    = argument(0); // Object
5710   Node* aoffset = argument(1); // long
5711   Node* objb    = argument(3); // Object
5712   Node* boffset = argument(4); // long
5713   Node* length  = argument(6); // int
5714   Node* scale   = argument(7); // int
5715 
5716   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
5717   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
5718   if (obja_t == NULL || obja_t->klass() == NULL ||
5719       objb_t == NULL || objb_t->klass() == NULL ||
5720       scale == top()) {
5721     return false; // failed input validation
5722   }
5723 
5724   Node* obja_adr = make_unsafe_address(obja, aoffset);
5725   Node* objb_adr = make_unsafe_address(objb, boffset);
5726 
5727   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
5728   //
5729   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
5730   //    if (length <= inline_limit) {
5731   //      inline_path:
5732   //        vmask   = VectorMaskGen length
5733   //        vload1  = LoadVectorMasked obja, vmask
5734   //        vload2  = LoadVectorMasked objb, vmask
5735   //        result1 = VectorCmpMasked vload1, vload2, vmask
5736   //    } else {
5737   //      call_stub_path:
5738   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
5739   //    }
5740   //    exit_block:
5741   //      return Phi(result1, result2);
5742   //
5743   enum { inline_path = 1,  // input is small enough to process it all at once
5744          stub_path   = 2,  // input is too large; call into the VM
5745          PATH_LIMIT  = 3
5746   };
5747 
5748   Node* exit_block = new RegionNode(PATH_LIMIT);
5749   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
5750   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
5751 
5752   Node* call_stub_path = control();
5753 
5754   BasicType elem_bt = T_ILLEGAL;
5755 
5756   const TypeInt* scale_t = _gvn.type(scale)->is_int();
5757   if (scale_t->is_con()) {
5758     switch (scale_t->get_con()) {
5759       case 0: elem_bt = T_BYTE;  break;
5760       case 1: elem_bt = T_SHORT; break;
5761       case 2: elem_bt = T_INT;   break;
5762       case 3: elem_bt = T_LONG;  break;
5763 
5764       default: elem_bt = T_ILLEGAL; break; // not supported
5765     }
5766   }
5767 
5768   int inline_limit = 0;
5769   bool do_partial_inline = false;
5770 
5771   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
5772     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
5773     do_partial_inline = inline_limit >= 16;
5774   }
5775 
5776   if (do_partial_inline) {
5777     assert(elem_bt != T_ILLEGAL, "sanity");
5778 
5779     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
5780         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
5781         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
5782 
5783       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
5784       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
5785       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
5786 
5787       call_stub_path = generate_guard(bol_gt, NULL, PROB_MIN);
5788 
5789       if (!stopped()) {
5790         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
5791 
5792         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
5793         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
5794         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
5795         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
5796 
5797         Node* vmask      = _gvn.transform(new VectorMaskGenNode(ConvI2X(casted_length), TypeVect::VECTMASK, elem_bt));
5798         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
5799         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
5800         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
5801 
5802         exit_block->init_req(inline_path, control());
5803         memory_phi->init_req(inline_path, map()->memory());
5804         result_phi->init_req(inline_path, result);
5805 
5806         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
5807         clear_upper_avx();
5808       }
5809     }
5810   }
5811 
5812   if (call_stub_path != NULL) {
5813     set_control(call_stub_path);
5814 
5815     Node* call = make_runtime_call(RC_LEAF,
5816                                    OptoRuntime::vectorizedMismatch_Type(),
5817                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
5818                                    obja_adr, objb_adr, length, scale);
5819 
5820     exit_block->init_req(stub_path, control());
5821     memory_phi->init_req(stub_path, map()->memory());
5822     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
5823   }
5824 
5825   exit_block = _gvn.transform(exit_block);
5826   memory_phi = _gvn.transform(memory_phi);
5827   result_phi = _gvn.transform(result_phi);
5828 
5829   set_control(exit_block);
5830   set_all_memory(memory_phi);
5831   set_result(result_phi);
5832 
5833   return true;
5834 }
5835 
5836 /**
5837  * Calculate CRC32 for byte.
5838  * int java.util.zip.CRC32.update(int crc, int b)
5839  */
5840 bool LibraryCallKit::inline_updateCRC32() {
5841   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5842   assert(callee()->signature()->size() == 2, "update has 2 parameters");
5843   // no receiver since it is static method
5844   Node* crc  = argument(0); // type: int
5845   Node* b    = argument(1); // type: int
5846 
5847   /*
5848    *    int c = ~ crc;
5849    *    b = timesXtoThe32[(b ^ c) & 0xFF];
5850    *    b = b ^ (c >>> 8);
5851    *    crc = ~b;
5852    */
5853 
5854   Node* M1 = intcon(-1);
5855   crc = _gvn.transform(new XorINode(crc, M1));
5856   Node* result = _gvn.transform(new XorINode(crc, b));
5857   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
5858 
5859   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
5860   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
5861   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
5862   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
5863 
5864   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
5865   result = _gvn.transform(new XorINode(crc, result));
5866   result = _gvn.transform(new XorINode(result, M1));
5867   set_result(result);
5868   return true;
5869 }
5870 
5871 /**
5872  * Calculate CRC32 for byte[] array.
5873  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
5874  */
5875 bool LibraryCallKit::inline_updateBytesCRC32() {
5876   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5877   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5878   // no receiver since it is static method
5879   Node* crc     = argument(0); // type: int
5880   Node* src     = argument(1); // type: oop
5881   Node* offset  = argument(2); // type: int
5882   Node* length  = argument(3); // type: int
5883 
5884   const Type* src_type = src->Value(&_gvn);
5885   const TypeAryPtr* top_src = src_type->isa_aryptr();
5886   if (top_src  == NULL || top_src->klass()  == NULL) {
5887     // failed array check
5888     return false;
5889   }
5890 
5891   // Figure out the size and type of the elements we will be copying.
5892   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5893   if (src_elem != T_BYTE) {
5894     return false;
5895   }
5896 
5897   // 'src_start' points to src array + scaled offset
5898   src = must_be_not_null(src, true);
5899   Node* src_start = array_element_address(src, offset, src_elem);
5900 
5901   // We assume that range check is done by caller.
5902   // TODO: generate range check (offset+length < src.length) in debug VM.
5903 
5904   // Call the stub.
5905   address stubAddr = StubRoutines::updateBytesCRC32();
5906   const char *stubName = "updateBytesCRC32";
5907 
5908   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5909                                  stubAddr, stubName, TypePtr::BOTTOM,
5910                                  crc, src_start, length);
5911   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5912   set_result(result);
5913   return true;
5914 }
5915 
5916 /**
5917  * Calculate CRC32 for ByteBuffer.
5918  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
5919  */
5920 bool LibraryCallKit::inline_updateByteBufferCRC32() {
5921   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5922   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
5923   // no receiver since it is static method
5924   Node* crc     = argument(0); // type: int
5925   Node* src     = argument(1); // type: long
5926   Node* offset  = argument(3); // type: int
5927   Node* length  = argument(4); // type: int
5928 
5929   src = ConvL2X(src);  // adjust Java long to machine word
5930   Node* base = _gvn.transform(new CastX2PNode(src));
5931   offset = ConvI2X(offset);
5932 
5933   // 'src_start' points to src array + scaled offset
5934   Node* src_start = basic_plus_adr(top(), base, offset);
5935 
5936   // Call the stub.
5937   address stubAddr = StubRoutines::updateBytesCRC32();
5938   const char *stubName = "updateBytesCRC32";
5939 
5940   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5941                                  stubAddr, stubName, TypePtr::BOTTOM,
5942                                  crc, src_start, length);
5943   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5944   set_result(result);
5945   return true;
5946 }
5947 
5948 //------------------------------get_table_from_crc32c_class-----------------------
5949 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
5950   Node* table = load_field_from_object(NULL, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
5951   assert (table != NULL, "wrong version of java.util.zip.CRC32C");
5952 
5953   return table;
5954 }
5955 
5956 //------------------------------inline_updateBytesCRC32C-----------------------
5957 //
5958 // Calculate CRC32C for byte[] array.
5959 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
5960 //
5961 bool LibraryCallKit::inline_updateBytesCRC32C() {
5962   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
5963   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5964   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
5965   // no receiver since it is a static method
5966   Node* crc     = argument(0); // type: int
5967   Node* src     = argument(1); // type: oop
5968   Node* offset  = argument(2); // type: int
5969   Node* end     = argument(3); // type: int
5970 
5971   Node* length = _gvn.transform(new SubINode(end, offset));
5972 
5973   const Type* src_type = src->Value(&_gvn);
5974   const TypeAryPtr* top_src = src_type->isa_aryptr();
5975   if (top_src  == NULL || top_src->klass()  == NULL) {
5976     // failed array check
5977     return false;
5978   }
5979 
5980   // Figure out the size and type of the elements we will be copying.
5981   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5982   if (src_elem != T_BYTE) {
5983     return false;
5984   }
5985 
5986   // 'src_start' points to src array + scaled offset
5987   src = must_be_not_null(src, true);
5988   Node* src_start = array_element_address(src, offset, src_elem);
5989 
5990   // static final int[] byteTable in class CRC32C
5991   Node* table = get_table_from_crc32c_class(callee()->holder());
5992   table = must_be_not_null(table, true);
5993   Node* table_start = array_element_address(table, intcon(0), T_INT);
5994 
5995   // We assume that range check is done by caller.
5996   // TODO: generate range check (offset+length < src.length) in debug VM.
5997 
5998   // Call the stub.
5999   address stubAddr = StubRoutines::updateBytesCRC32C();
6000   const char *stubName = "updateBytesCRC32C";
6001 
6002   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
6003                                  stubAddr, stubName, TypePtr::BOTTOM,
6004                                  crc, src_start, length, table_start);
6005   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6006   set_result(result);
6007   return true;
6008 }
6009 
6010 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
6011 //
6012 // Calculate CRC32C for DirectByteBuffer.
6013 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
6014 //
6015 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
6016   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
6017   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
6018   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
6019   // no receiver since it is a static method
6020   Node* crc     = argument(0); // type: int
6021   Node* src     = argument(1); // type: long
6022   Node* offset  = argument(3); // type: int
6023   Node* end     = argument(4); // type: int
6024 
6025   Node* length = _gvn.transform(new SubINode(end, offset));
6026 
6027   src = ConvL2X(src);  // adjust Java long to machine word
6028   Node* base = _gvn.transform(new CastX2PNode(src));
6029   offset = ConvI2X(offset);
6030 
6031   // 'src_start' points to src array + scaled offset
6032   Node* src_start = basic_plus_adr(top(), base, offset);
6033 
6034   // static final int[] byteTable in class CRC32C
6035   Node* table = get_table_from_crc32c_class(callee()->holder());
6036   table = must_be_not_null(table, true);
6037   Node* table_start = array_element_address(table, intcon(0), T_INT);
6038 
6039   // Call the stub.
6040   address stubAddr = StubRoutines::updateBytesCRC32C();
6041   const char *stubName = "updateBytesCRC32C";
6042 
6043   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
6044                                  stubAddr, stubName, TypePtr::BOTTOM,
6045                                  crc, src_start, length, table_start);
6046   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6047   set_result(result);
6048   return true;
6049 }
6050 
6051 //------------------------------inline_updateBytesAdler32----------------------
6052 //
6053 // Calculate Adler32 checksum for byte[] array.
6054 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
6055 //
6056 bool LibraryCallKit::inline_updateBytesAdler32() {
6057   assert(UseAdler32Intrinsics, "Adler32 Instrinsic support need"); // check if we actually need to check this flag or check a different one
6058   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
6059   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
6060   // no receiver since it is static method
6061   Node* crc     = argument(0); // type: int
6062   Node* src     = argument(1); // type: oop
6063   Node* offset  = argument(2); // type: int
6064   Node* length  = argument(3); // type: int
6065 
6066   const Type* src_type = src->Value(&_gvn);
6067   const TypeAryPtr* top_src = src_type->isa_aryptr();
6068   if (top_src  == NULL || top_src->klass()  == NULL) {
6069     // failed array check
6070     return false;
6071   }
6072 
6073   // Figure out the size and type of the elements we will be copying.
6074   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
6075   if (src_elem != T_BYTE) {
6076     return false;
6077   }
6078 
6079   // 'src_start' points to src array + scaled offset
6080   Node* src_start = array_element_address(src, offset, src_elem);
6081 
6082   // We assume that range check is done by caller.
6083   // TODO: generate range check (offset+length < src.length) in debug VM.
6084 
6085   // Call the stub.
6086   address stubAddr = StubRoutines::updateBytesAdler32();
6087   const char *stubName = "updateBytesAdler32";
6088 
6089   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
6090                                  stubAddr, stubName, TypePtr::BOTTOM,
6091                                  crc, src_start, length);
6092   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6093   set_result(result);
6094   return true;
6095 }
6096 
6097 //------------------------------inline_updateByteBufferAdler32---------------
6098 //
6099 // Calculate Adler32 checksum for DirectByteBuffer.
6100 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
6101 //
6102 bool LibraryCallKit::inline_updateByteBufferAdler32() {
6103   assert(UseAdler32Intrinsics, "Adler32 Instrinsic support need"); // check if we actually need to check this flag or check a different one
6104   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
6105   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
6106   // no receiver since it is static method
6107   Node* crc     = argument(0); // type: int
6108   Node* src     = argument(1); // type: long
6109   Node* offset  = argument(3); // type: int
6110   Node* length  = argument(4); // type: int
6111 
6112   src = ConvL2X(src);  // adjust Java long to machine word
6113   Node* base = _gvn.transform(new CastX2PNode(src));
6114   offset = ConvI2X(offset);
6115 
6116   // 'src_start' points to src array + scaled offset
6117   Node* src_start = basic_plus_adr(top(), base, offset);
6118 
6119   // Call the stub.
6120   address stubAddr = StubRoutines::updateBytesAdler32();
6121   const char *stubName = "updateBytesAdler32";
6122 
6123   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
6124                                  stubAddr, stubName, TypePtr::BOTTOM,
6125                                  crc, src_start, length);
6126 
6127   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6128   set_result(result);
6129   return true;
6130 }
6131 
6132 //----------------------------inline_reference_get----------------------------
6133 // public T java.lang.ref.Reference.get();
6134 bool LibraryCallKit::inline_reference_get() {
6135   const int referent_offset = java_lang_ref_Reference::referent_offset();
6136 
6137   // Get the argument:
6138   Node* reference_obj = null_check_receiver();
6139   if (stopped()) return true;
6140 
6141   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
6142   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
6143                                         decorators, /*is_static*/ false, NULL);
6144   if (result == NULL) return false;
6145 
6146   // Add memory barrier to prevent commoning reads from this field
6147   // across safepoint since GC can change its value.
6148   insert_mem_bar(Op_MemBarCPUOrder);
6149 
6150   set_result(result);
6151   return true;
6152 }
6153 
6154 //----------------------------inline_reference_refersTo0----------------------------
6155 // bool java.lang.ref.Reference.refersTo0();
6156 // bool java.lang.ref.PhantomReference.refersTo0();
6157 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
6158   // Get arguments:
6159   Node* reference_obj = null_check_receiver();
6160   Node* other_obj = argument(1);
6161   if (stopped()) return true;
6162 
6163   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
6164   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
6165   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
6166                                           decorators, /*is_static*/ false, NULL);
6167   if (referent == NULL) return false;
6168 
6169   // Add memory barrier to prevent commoning reads from this field
6170   // across safepoint since GC can change its value.
6171   insert_mem_bar(Op_MemBarCPUOrder);
6172 
6173   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
6174   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
6175   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
6176 
6177   RegionNode* region = new RegionNode(3);
6178   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
6179 
6180   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
6181   region->init_req(1, if_true);
6182   phi->init_req(1, intcon(1));
6183 
6184   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
6185   region->init_req(2, if_false);
6186   phi->init_req(2, intcon(0));
6187 
6188   set_control(_gvn.transform(region));
6189   record_for_igvn(region);
6190   set_result(_gvn.transform(phi));
6191   return true;
6192 }
6193 
6194 
6195 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
6196                                              DecoratorSet decorators = IN_HEAP, bool is_static = false,
6197                                              ciInstanceKlass* fromKls = NULL) {
6198   if (fromKls == NULL) {
6199     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
6200     assert(tinst != NULL, "obj is null");
6201     assert(tinst->klass()->is_loaded(), "obj is not loaded");
6202     fromKls = tinst->klass()->as_instance_klass();
6203   } else {
6204     assert(is_static, "only for static field access");
6205   }
6206   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
6207                                               ciSymbol::make(fieldTypeString),
6208                                               is_static);
6209 
6210   assert (field != NULL, "undefined field");
6211   if (field == NULL) return (Node *) NULL;
6212 
6213   if (is_static) {
6214     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
6215     fromObj = makecon(tip);
6216   }
6217 
6218   // Next code  copied from Parse::do_get_xxx():
6219 
6220   // Compute address and memory type.
6221   int offset  = field->offset_in_bytes();
6222   bool is_vol = field->is_volatile();
6223   ciType* field_klass = field->type();
6224   assert(field_klass->is_loaded(), "should be loaded");
6225   const TypePtr* adr_type = C->alias_type(field)->adr_type();
6226   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
6227   BasicType bt = field->layout_type();
6228 
6229   // Build the resultant type of the load
6230   const Type *type;
6231   if (bt == T_OBJECT) {
6232     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
6233   } else {
6234     type = Type::get_const_basic_type(bt);
6235   }
6236 
6237   if (is_vol) {
6238     decorators |= MO_SEQ_CST;
6239   }
6240 
6241   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
6242 }
6243 
6244 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
6245                                                  bool is_exact = true, bool is_static = false,
6246                                                  ciInstanceKlass * fromKls = NULL) {
6247   if (fromKls == NULL) {
6248     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
6249     assert(tinst != NULL, "obj is null");
6250     assert(tinst->klass()->is_loaded(), "obj is not loaded");
6251     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
6252     fromKls = tinst->klass()->as_instance_klass();
6253   }
6254   else {
6255     assert(is_static, "only for static field access");
6256   }
6257   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
6258     ciSymbol::make(fieldTypeString),
6259     is_static);
6260 
6261   assert(field != NULL, "undefined field");
6262   assert(!field->is_volatile(), "not defined for volatile fields");
6263 
6264   if (is_static) {
6265     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
6266     fromObj = makecon(tip);
6267   }
6268 
6269   // Next code  copied from Parse::do_get_xxx():
6270 
6271   // Compute address and memory type.
6272   int offset = field->offset_in_bytes();
6273   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
6274 
6275   return adr;
6276 }
6277 
6278 //------------------------------inline_aescrypt_Block-----------------------
6279 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
6280   address stubAddr = NULL;
6281   const char *stubName;
6282   assert(UseAES, "need AES instruction support");
6283 
6284   switch(id) {
6285   case vmIntrinsics::_aescrypt_encryptBlock:
6286     stubAddr = StubRoutines::aescrypt_encryptBlock();
6287     stubName = "aescrypt_encryptBlock";
6288     break;
6289   case vmIntrinsics::_aescrypt_decryptBlock:
6290     stubAddr = StubRoutines::aescrypt_decryptBlock();
6291     stubName = "aescrypt_decryptBlock";
6292     break;
6293   default:
6294     break;
6295   }
6296   if (stubAddr == NULL) return false;
6297 
6298   Node* aescrypt_object = argument(0);
6299   Node* src             = argument(1);
6300   Node* src_offset      = argument(2);
6301   Node* dest            = argument(3);
6302   Node* dest_offset     = argument(4);
6303 
6304   src = must_be_not_null(src, true);
6305   dest = must_be_not_null(dest, true);
6306 
6307   // (1) src and dest are arrays.
6308   const Type* src_type = src->Value(&_gvn);
6309   const Type* dest_type = dest->Value(&_gvn);
6310   const TypeAryPtr* top_src = src_type->isa_aryptr();
6311   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6312   assert (top_src  != NULL && top_src->klass()  != NULL &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
6313 
6314   // for the quick and dirty code we will skip all the checks.
6315   // we are just trying to get the call to be generated.
6316   Node* src_start  = src;
6317   Node* dest_start = dest;
6318   if (src_offset != NULL || dest_offset != NULL) {
6319     assert(src_offset != NULL && dest_offset != NULL, "");
6320     src_start  = array_element_address(src,  src_offset,  T_BYTE);
6321     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6322   }
6323 
6324   // now need to get the start of its expanded key array
6325   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6326   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6327   if (k_start == NULL) return false;
6328 
6329   // Call the stub.
6330   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
6331                     stubAddr, stubName, TypePtr::BOTTOM,
6332                     src_start, dest_start, k_start);
6333 
6334   return true;
6335 }
6336 
6337 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
6338 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
6339   address stubAddr = NULL;
6340   const char *stubName = NULL;
6341 
6342   assert(UseAES, "need AES instruction support");
6343 
6344   switch(id) {
6345   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
6346     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
6347     stubName = "cipherBlockChaining_encryptAESCrypt";
6348     break;
6349   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
6350     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
6351     stubName = "cipherBlockChaining_decryptAESCrypt";
6352     break;
6353   default:
6354     break;
6355   }
6356   if (stubAddr == NULL) return false;
6357 
6358   Node* cipherBlockChaining_object = argument(0);
6359   Node* src                        = argument(1);
6360   Node* src_offset                 = argument(2);
6361   Node* len                        = argument(3);
6362   Node* dest                       = argument(4);
6363   Node* dest_offset                = argument(5);
6364 
6365   src = must_be_not_null(src, false);
6366   dest = must_be_not_null(dest, false);
6367 
6368   // (1) src and dest are arrays.
6369   const Type* src_type = src->Value(&_gvn);
6370   const Type* dest_type = dest->Value(&_gvn);
6371   const TypeAryPtr* top_src = src_type->isa_aryptr();
6372   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6373   assert (top_src  != NULL && top_src->klass()  != NULL
6374           &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
6375 
6376   // checks are the responsibility of the caller
6377   Node* src_start  = src;
6378   Node* dest_start = dest;
6379   if (src_offset != NULL || dest_offset != NULL) {
6380     assert(src_offset != NULL && dest_offset != NULL, "");
6381     src_start  = array_element_address(src,  src_offset,  T_BYTE);
6382     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6383   }
6384 
6385   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
6386   // (because of the predicated logic executed earlier).
6387   // so we cast it here safely.
6388   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6389 
6390   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
6391   if (embeddedCipherObj == NULL) return false;
6392 
6393   // cast it to what we know it will be at runtime
6394   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
6395   assert(tinst != NULL, "CBC obj is null");
6396   assert(tinst->klass()->is_loaded(), "CBC obj is not loaded");
6397   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6398   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
6399 
6400   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6401   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
6402   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
6403   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
6404   aescrypt_object = _gvn.transform(aescrypt_object);
6405 
6406   // we need to get the start of the aescrypt_object's expanded key array
6407   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6408   if (k_start == NULL) return false;
6409 
6410   // similarly, get the start address of the r vector
6411   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
6412   if (objRvec == NULL) return false;
6413   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
6414 
6415   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
6416   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6417                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
6418                                      stubAddr, stubName, TypePtr::BOTTOM,
6419                                      src_start, dest_start, k_start, r_start, len);
6420 
6421   // return cipher length (int)
6422   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
6423   set_result(retvalue);
6424   return true;
6425 }
6426 
6427 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
6428 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
6429   address stubAddr = NULL;
6430   const char *stubName = NULL;
6431 
6432   assert(UseAES, "need AES instruction support");
6433 
6434   switch (id) {
6435   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
6436     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
6437     stubName = "electronicCodeBook_encryptAESCrypt";
6438     break;
6439   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
6440     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
6441     stubName = "electronicCodeBook_decryptAESCrypt";
6442     break;
6443   default:
6444     break;
6445   }
6446 
6447   if (stubAddr == NULL) return false;
6448 
6449   Node* electronicCodeBook_object = argument(0);
6450   Node* src                       = argument(1);
6451   Node* src_offset                = argument(2);
6452   Node* len                       = argument(3);
6453   Node* dest                      = argument(4);
6454   Node* dest_offset               = argument(5);
6455 
6456   // (1) src and dest are arrays.
6457   const Type* src_type = src->Value(&_gvn);
6458   const Type* dest_type = dest->Value(&_gvn);
6459   const TypeAryPtr* top_src = src_type->isa_aryptr();
6460   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6461   assert(top_src != NULL && top_src->klass() != NULL
6462          &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
6463 
6464   // checks are the responsibility of the caller
6465   Node* src_start = src;
6466   Node* dest_start = dest;
6467   if (src_offset != NULL || dest_offset != NULL) {
6468     assert(src_offset != NULL && dest_offset != NULL, "");
6469     src_start = array_element_address(src, src_offset, T_BYTE);
6470     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6471   }
6472 
6473   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
6474   // (because of the predicated logic executed earlier).
6475   // so we cast it here safely.
6476   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6477 
6478   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
6479   if (embeddedCipherObj == NULL) return false;
6480 
6481   // cast it to what we know it will be at runtime
6482   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
6483   assert(tinst != NULL, "ECB obj is null");
6484   assert(tinst->klass()->is_loaded(), "ECB obj is not loaded");
6485   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6486   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
6487 
6488   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6489   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
6490   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
6491   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
6492   aescrypt_object = _gvn.transform(aescrypt_object);
6493 
6494   // we need to get the start of the aescrypt_object's expanded key array
6495   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6496   if (k_start == NULL) return false;
6497 
6498   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
6499   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
6500                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
6501                                      stubAddr, stubName, TypePtr::BOTTOM,
6502                                      src_start, dest_start, k_start, len);
6503 
6504   // return cipher length (int)
6505   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
6506   set_result(retvalue);
6507   return true;
6508 }
6509 
6510 //------------------------------inline_counterMode_AESCrypt-----------------------
6511 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
6512   assert(UseAES, "need AES instruction support");
6513   if (!UseAESCTRIntrinsics) return false;
6514 
6515   address stubAddr = NULL;
6516   const char *stubName = NULL;
6517   if (id == vmIntrinsics::_counterMode_AESCrypt) {
6518     stubAddr = StubRoutines::counterMode_AESCrypt();
6519     stubName = "counterMode_AESCrypt";
6520   }
6521   if (stubAddr == NULL) return false;
6522 
6523   Node* counterMode_object = argument(0);
6524   Node* src = argument(1);
6525   Node* src_offset = argument(2);
6526   Node* len = argument(3);
6527   Node* dest = argument(4);
6528   Node* dest_offset = argument(5);
6529 
6530   // (1) src and dest are arrays.
6531   const Type* src_type = src->Value(&_gvn);
6532   const Type* dest_type = dest->Value(&_gvn);
6533   const TypeAryPtr* top_src = src_type->isa_aryptr();
6534   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6535   assert(top_src != NULL && top_src->klass() != NULL &&
6536          top_dest != NULL && top_dest->klass() != NULL, "args are strange");
6537 
6538   // checks are the responsibility of the caller
6539   Node* src_start = src;
6540   Node* dest_start = dest;
6541   if (src_offset != NULL || dest_offset != NULL) {
6542     assert(src_offset != NULL && dest_offset != NULL, "");
6543     src_start = array_element_address(src, src_offset, T_BYTE);
6544     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6545   }
6546 
6547   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
6548   // (because of the predicated logic executed earlier).
6549   // so we cast it here safely.
6550   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6551   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
6552   if (embeddedCipherObj == NULL) return false;
6553   // cast it to what we know it will be at runtime
6554   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
6555   assert(tinst != NULL, "CTR obj is null");
6556   assert(tinst->klass()->is_loaded(), "CTR obj is not loaded");
6557   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6558   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
6559   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6560   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
6561   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
6562   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
6563   aescrypt_object = _gvn.transform(aescrypt_object);
6564   // we need to get the start of the aescrypt_object's expanded key array
6565   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6566   if (k_start == NULL) return false;
6567   // similarly, get the start address of the r vector
6568   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
6569   if (obj_counter == NULL) return false;
6570   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
6571 
6572   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
6573   if (saved_encCounter == NULL) return false;
6574   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
6575   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
6576 
6577   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
6578   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6579                                      OptoRuntime::counterMode_aescrypt_Type(),
6580                                      stubAddr, stubName, TypePtr::BOTTOM,
6581                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
6582 
6583   // return cipher length (int)
6584   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
6585   set_result(retvalue);
6586   return true;
6587 }
6588 
6589 //------------------------------get_key_start_from_aescrypt_object-----------------------
6590 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
6591 #if defined(PPC64) || defined(S390)
6592   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
6593   // Intel's extention is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
6594   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
6595   // The ppc64 stubs of encryption and decryption use the same round keys (sessionK[0]).
6596   Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I");
6597   assert (objSessionK != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
6598   if (objSessionK == NULL) {
6599     return (Node *) NULL;
6600   }
6601   Node* objAESCryptKey = load_array_element(objSessionK, intcon(0), TypeAryPtr::OOPS, /* set_ctrl */ true);
6602 #else
6603   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I");
6604 #endif // PPC64
6605   assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
6606   if (objAESCryptKey == NULL) return (Node *) NULL;
6607 
6608   // now have the array, need to get the start address of the K array
6609   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
6610   return k_start;
6611 }
6612 
6613 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
6614 // Return node representing slow path of predicate check.
6615 // the pseudo code we want to emulate with this predicate is:
6616 // for encryption:
6617 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
6618 // for decryption:
6619 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
6620 //    note cipher==plain is more conservative than the original java code but that's OK
6621 //
6622 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
6623   // The receiver was checked for NULL already.
6624   Node* objCBC = argument(0);
6625 
6626   Node* src = argument(1);
6627   Node* dest = argument(4);
6628 
6629   // Load embeddedCipher field of CipherBlockChaining object.
6630   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
6631 
6632   // get AESCrypt klass for instanceOf check
6633   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
6634   // will have same classloader as CipherBlockChaining object
6635   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
6636   assert(tinst != NULL, "CBCobj is null");
6637   assert(tinst->klass()->is_loaded(), "CBCobj is not loaded");
6638 
6639   // we want to do an instanceof comparison against the AESCrypt class
6640   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6641   if (!klass_AESCrypt->is_loaded()) {
6642     // if AESCrypt is not even loaded, we never take the intrinsic fast path
6643     Node* ctrl = control();
6644     set_control(top()); // no regular fast path
6645     return ctrl;
6646   }
6647 
6648   src = must_be_not_null(src, true);
6649   dest = must_be_not_null(dest, true);
6650 
6651   // Resolve oops to stable for CmpP below.
6652   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6653 
6654   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
6655   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
6656   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6657 
6658   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6659 
6660   // for encryption, we are done
6661   if (!decrypting)
6662     return instof_false;  // even if it is NULL
6663 
6664   // for decryption, we need to add a further check to avoid
6665   // taking the intrinsic path when cipher and plain are the same
6666   // see the original java code for why.
6667   RegionNode* region = new RegionNode(3);
6668   region->init_req(1, instof_false);
6669 
6670   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
6671   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
6672   Node* src_dest_conjoint = generate_guard(bool_src_dest, NULL, PROB_MIN);
6673   region->init_req(2, src_dest_conjoint);
6674 
6675   record_for_igvn(region);
6676   return _gvn.transform(region);
6677 }
6678 
6679 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
6680 // Return node representing slow path of predicate check.
6681 // the pseudo code we want to emulate with this predicate is:
6682 // for encryption:
6683 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
6684 // for decryption:
6685 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
6686 //    note cipher==plain is more conservative than the original java code but that's OK
6687 //
6688 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
6689   // The receiver was checked for NULL already.
6690   Node* objECB = argument(0);
6691 
6692   // Load embeddedCipher field of ElectronicCodeBook object.
6693   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
6694 
6695   // get AESCrypt klass for instanceOf check
6696   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
6697   // will have same classloader as ElectronicCodeBook object
6698   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
6699   assert(tinst != NULL, "ECBobj is null");
6700   assert(tinst->klass()->is_loaded(), "ECBobj is not loaded");
6701 
6702   // we want to do an instanceof comparison against the AESCrypt class
6703   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6704   if (!klass_AESCrypt->is_loaded()) {
6705     // if AESCrypt is not even loaded, we never take the intrinsic fast path
6706     Node* ctrl = control();
6707     set_control(top()); // no regular fast path
6708     return ctrl;
6709   }
6710   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6711 
6712   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
6713   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
6714   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6715 
6716   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6717 
6718   // for encryption, we are done
6719   if (!decrypting)
6720     return instof_false;  // even if it is NULL
6721 
6722   // for decryption, we need to add a further check to avoid
6723   // taking the intrinsic path when cipher and plain are the same
6724   // see the original java code for why.
6725   RegionNode* region = new RegionNode(3);
6726   region->init_req(1, instof_false);
6727   Node* src = argument(1);
6728   Node* dest = argument(4);
6729   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
6730   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
6731   Node* src_dest_conjoint = generate_guard(bool_src_dest, NULL, PROB_MIN);
6732   region->init_req(2, src_dest_conjoint);
6733 
6734   record_for_igvn(region);
6735   return _gvn.transform(region);
6736 }
6737 
6738 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
6739 // Return node representing slow path of predicate check.
6740 // the pseudo code we want to emulate with this predicate is:
6741 // for encryption:
6742 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
6743 // for decryption:
6744 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
6745 //    note cipher==plain is more conservative than the original java code but that's OK
6746 //
6747 
6748 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
6749   // The receiver was checked for NULL already.
6750   Node* objCTR = argument(0);
6751 
6752   // Load embeddedCipher field of CipherBlockChaining object.
6753   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
6754 
6755   // get AESCrypt klass for instanceOf check
6756   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
6757   // will have same classloader as CipherBlockChaining object
6758   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
6759   assert(tinst != NULL, "CTRobj is null");
6760   assert(tinst->klass()->is_loaded(), "CTRobj is not loaded");
6761 
6762   // we want to do an instanceof comparison against the AESCrypt class
6763   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6764   if (!klass_AESCrypt->is_loaded()) {
6765     // if AESCrypt is not even loaded, we never take the intrinsic fast path
6766     Node* ctrl = control();
6767     set_control(top()); // no regular fast path
6768     return ctrl;
6769   }
6770 
6771   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6772   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
6773   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
6774   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6775   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6776 
6777   return instof_false; // even if it is NULL
6778 }
6779 
6780 //------------------------------inline_ghash_processBlocks
6781 bool LibraryCallKit::inline_ghash_processBlocks() {
6782   address stubAddr;
6783   const char *stubName;
6784   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
6785 
6786   stubAddr = StubRoutines::ghash_processBlocks();
6787   stubName = "ghash_processBlocks";
6788 
6789   Node* data           = argument(0);
6790   Node* offset         = argument(1);
6791   Node* len            = argument(2);
6792   Node* state          = argument(3);
6793   Node* subkeyH        = argument(4);
6794 
6795   state = must_be_not_null(state, true);
6796   subkeyH = must_be_not_null(subkeyH, true);
6797   data = must_be_not_null(data, true);
6798 
6799   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
6800   assert(state_start, "state is NULL");
6801   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
6802   assert(subkeyH_start, "subkeyH is NULL");
6803   Node* data_start  = array_element_address(data, offset, T_BYTE);
6804   assert(data_start, "data is NULL");
6805 
6806   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
6807                                   OptoRuntime::ghash_processBlocks_Type(),
6808                                   stubAddr, stubName, TypePtr::BOTTOM,
6809                                   state_start, subkeyH_start, data_start, len);
6810   return true;
6811 }
6812 
6813 bool LibraryCallKit::inline_base64_encodeBlock() {
6814   address stubAddr;
6815   const char *stubName;
6816   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
6817   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
6818   stubAddr = StubRoutines::base64_encodeBlock();
6819   stubName = "encodeBlock";
6820 
6821   if (!stubAddr) return false;
6822   Node* base64obj = argument(0);
6823   Node* src = argument(1);
6824   Node* offset = argument(2);
6825   Node* len = argument(3);
6826   Node* dest = argument(4);
6827   Node* dp = argument(5);
6828   Node* isURL = argument(6);
6829 
6830   src = must_be_not_null(src, true);
6831   dest = must_be_not_null(dest, true);
6832 
6833   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
6834   assert(src_start, "source array is NULL");
6835   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
6836   assert(dest_start, "destination array is NULL");
6837 
6838   Node* base64 = make_runtime_call(RC_LEAF,
6839                                    OptoRuntime::base64_encodeBlock_Type(),
6840                                    stubAddr, stubName, TypePtr::BOTTOM,
6841                                    src_start, offset, len, dest_start, dp, isURL);
6842   return true;
6843 }
6844 
6845 bool LibraryCallKit::inline_base64_decodeBlock() {
6846   address stubAddr;
6847   const char *stubName;
6848   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
6849   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
6850   stubAddr = StubRoutines::base64_decodeBlock();
6851   stubName = "decodeBlock";
6852 
6853   if (!stubAddr) return false;
6854   Node* base64obj = argument(0);
6855   Node* src = argument(1);
6856   Node* src_offset = argument(2);
6857   Node* len = argument(3);
6858   Node* dest = argument(4);
6859   Node* dest_offset = argument(5);
6860   Node* isURL = argument(6);
6861   Node* isMIME = argument(7);
6862 
6863   src = must_be_not_null(src, true);
6864   dest = must_be_not_null(dest, true);
6865 
6866   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
6867   assert(src_start, "source array is NULL");
6868   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
6869   assert(dest_start, "destination array is NULL");
6870 
6871   Node* call = make_runtime_call(RC_LEAF,
6872                                  OptoRuntime::base64_decodeBlock_Type(),
6873                                  stubAddr, stubName, TypePtr::BOTTOM,
6874                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
6875   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6876   set_result(result);
6877   return true;
6878 }
6879 
6880 //------------------------------inline_digestBase_implCompress-----------------------
6881 //
6882 // Calculate MD5 for single-block byte[] array.
6883 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
6884 //
6885 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
6886 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
6887 //
6888 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
6889 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
6890 //
6891 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
6892 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
6893 //
6894 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
6895 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
6896 //
6897 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
6898   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
6899 
6900   Node* digestBase_obj = argument(0);
6901   Node* src            = argument(1); // type oop
6902   Node* ofs            = argument(2); // type int
6903 
6904   const Type* src_type = src->Value(&_gvn);
6905   const TypeAryPtr* top_src = src_type->isa_aryptr();
6906   if (top_src  == NULL || top_src->klass()  == NULL) {
6907     // failed array check
6908     return false;
6909   }
6910   // Figure out the size and type of the elements we will be copying.
6911   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
6912   if (src_elem != T_BYTE) {
6913     return false;
6914   }
6915   // 'src_start' points to src array + offset
6916   src = must_be_not_null(src, true);
6917   Node* src_start = array_element_address(src, ofs, src_elem);
6918   Node* state = NULL;
6919   Node* digest_length = NULL;
6920   address stubAddr;
6921   const char *stubName;
6922 
6923   switch(id) {
6924   case vmIntrinsics::_md5_implCompress:
6925     assert(UseMD5Intrinsics, "need MD5 instruction support");
6926     state = get_state_from_digest_object(digestBase_obj, "[I");
6927     stubAddr = StubRoutines::md5_implCompress();
6928     stubName = "md5_implCompress";
6929     break;
6930   case vmIntrinsics::_sha_implCompress:
6931     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
6932     state = get_state_from_digest_object(digestBase_obj, "[I");
6933     stubAddr = StubRoutines::sha1_implCompress();
6934     stubName = "sha1_implCompress";
6935     break;
6936   case vmIntrinsics::_sha2_implCompress:
6937     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
6938     state = get_state_from_digest_object(digestBase_obj, "[I");
6939     stubAddr = StubRoutines::sha256_implCompress();
6940     stubName = "sha256_implCompress";
6941     break;
6942   case vmIntrinsics::_sha5_implCompress:
6943     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
6944     state = get_state_from_digest_object(digestBase_obj, "[J");
6945     stubAddr = StubRoutines::sha512_implCompress();
6946     stubName = "sha512_implCompress";
6947     break;
6948   case vmIntrinsics::_sha3_implCompress:
6949     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
6950     state = get_state_from_digest_object(digestBase_obj, "[B");
6951     stubAddr = StubRoutines::sha3_implCompress();
6952     stubName = "sha3_implCompress";
6953     digest_length = get_digest_length_from_digest_object(digestBase_obj);
6954     if (digest_length == NULL) return false;
6955     break;
6956   default:
6957     fatal_unexpected_iid(id);
6958     return false;
6959   }
6960   if (state == NULL) return false;
6961 
6962   assert(stubAddr != NULL, "Stub is generated");
6963   if (stubAddr == NULL) return false;
6964 
6965   // Call the stub.
6966   Node* call;
6967   if (digest_length == NULL) {
6968     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
6969                              stubAddr, stubName, TypePtr::BOTTOM,
6970                              src_start, state);
6971   } else {
6972     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
6973                              stubAddr, stubName, TypePtr::BOTTOM,
6974                              src_start, state, digest_length);
6975   }
6976 
6977   return true;
6978 }
6979 
6980 //------------------------------inline_digestBase_implCompressMB-----------------------
6981 //
6982 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
6983 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
6984 //
6985 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
6986   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
6987          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
6988   assert((uint)predicate < 5, "sanity");
6989   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
6990 
6991   Node* digestBase_obj = argument(0); // The receiver was checked for NULL already.
6992   Node* src            = argument(1); // byte[] array
6993   Node* ofs            = argument(2); // type int
6994   Node* limit          = argument(3); // type int
6995 
6996   const Type* src_type = src->Value(&_gvn);
6997   const TypeAryPtr* top_src = src_type->isa_aryptr();
6998   if (top_src  == NULL || top_src->klass()  == NULL) {
6999     // failed array check
7000     return false;
7001   }
7002   // Figure out the size and type of the elements we will be copying.
7003   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
7004   if (src_elem != T_BYTE) {
7005     return false;
7006   }
7007   // 'src_start' points to src array + offset
7008   src = must_be_not_null(src, false);
7009   Node* src_start = array_element_address(src, ofs, src_elem);
7010 
7011   const char* klass_digestBase_name = NULL;
7012   const char* stub_name = NULL;
7013   address     stub_addr = NULL;
7014   const char* state_type = "[I";
7015 
7016   switch (predicate) {
7017   case 0:
7018     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
7019       klass_digestBase_name = "sun/security/provider/MD5";
7020       stub_name = "md5_implCompressMB";
7021       stub_addr = StubRoutines::md5_implCompressMB();
7022     }
7023     break;
7024   case 1:
7025     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
7026       klass_digestBase_name = "sun/security/provider/SHA";
7027       stub_name = "sha1_implCompressMB";
7028       stub_addr = StubRoutines::sha1_implCompressMB();
7029     }
7030     break;
7031   case 2:
7032     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
7033       klass_digestBase_name = "sun/security/provider/SHA2";
7034       stub_name = "sha256_implCompressMB";
7035       stub_addr = StubRoutines::sha256_implCompressMB();
7036     }
7037     break;
7038   case 3:
7039     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
7040       klass_digestBase_name = "sun/security/provider/SHA5";
7041       stub_name = "sha512_implCompressMB";
7042       stub_addr = StubRoutines::sha512_implCompressMB();
7043       state_type = "[J";
7044     }
7045     break;
7046   case 4:
7047     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
7048       klass_digestBase_name = "sun/security/provider/SHA3";
7049       stub_name = "sha3_implCompressMB";
7050       stub_addr = StubRoutines::sha3_implCompressMB();
7051       state_type = "[B";
7052     }
7053     break;
7054   default:
7055     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
7056   }
7057   if (klass_digestBase_name != NULL) {
7058     assert(stub_addr != NULL, "Stub is generated");
7059     if (stub_addr == NULL) return false;
7060 
7061     // get DigestBase klass to lookup for SHA klass
7062     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
7063     assert(tinst != NULL, "digestBase_obj is not instance???");
7064     assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
7065 
7066     ciKlass* klass_digestBase = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
7067     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
7068     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
7069     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, state_type, stub_addr, stub_name, src_start, ofs, limit);
7070   }
7071   return false;
7072 }
7073 
7074 //------------------------------inline_digestBase_implCompressMB-----------------------
7075 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
7076                                                       const char* state_type, address stubAddr, const char *stubName,
7077                                                       Node* src_start, Node* ofs, Node* limit) {
7078   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
7079   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7080   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
7081   digest_obj = _gvn.transform(digest_obj);
7082 
7083   Node* state = get_state_from_digest_object(digest_obj, state_type);
7084   if (state == NULL) return false;
7085 
7086   Node* digest_length = NULL;
7087   if (strcmp("sha3_implCompressMB", stubName) == 0) {
7088     digest_length = get_digest_length_from_digest_object(digest_obj);
7089     if (digest_length == NULL) return false;
7090   }
7091 
7092   // Call the stub.
7093   Node* call;
7094   if (digest_length == NULL) {
7095     call = make_runtime_call(RC_LEAF|RC_NO_FP,
7096                              OptoRuntime::digestBase_implCompressMB_Type(false),
7097                              stubAddr, stubName, TypePtr::BOTTOM,
7098                              src_start, state, ofs, limit);
7099   } else {
7100      call = make_runtime_call(RC_LEAF|RC_NO_FP,
7101                              OptoRuntime::digestBase_implCompressMB_Type(true),
7102                              stubAddr, stubName, TypePtr::BOTTOM,
7103                              src_start, state, digest_length, ofs, limit);
7104   }
7105 
7106   // return ofs (int)
7107   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7108   set_result(result);
7109 
7110   return true;
7111 }
7112 
7113 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
7114 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
7115   assert(UseAES, "need AES instruction support");
7116   address stubAddr = NULL;
7117   const char *stubName = NULL;
7118   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
7119   stubName = "galoisCounterMode_AESCrypt";
7120 
7121   if (stubAddr == NULL) return false;
7122 
7123   Node* in      = argument(0);
7124   Node* inOfs   = argument(1);
7125   Node* len     = argument(2);
7126   Node* ct      = argument(3);
7127   Node* ctOfs   = argument(4);
7128   Node* out     = argument(5);
7129   Node* outOfs  = argument(6);
7130   Node* gctr_object = argument(7);
7131   Node* ghash_object = argument(8);
7132 
7133   // (1) in, ct and out are arrays.
7134   const Type* in_type = in->Value(&_gvn);
7135   const Type* ct_type = ct->Value(&_gvn);
7136   const Type* out_type = out->Value(&_gvn);
7137   const TypeAryPtr* top_in = in_type->isa_aryptr();
7138   const TypeAryPtr* top_ct = ct_type->isa_aryptr();
7139   const TypeAryPtr* top_out = out_type->isa_aryptr();
7140   assert(top_in != NULL && top_in->klass() != NULL &&
7141          top_ct != NULL && top_ct->klass() != NULL &&
7142          top_out != NULL && top_out->klass() != NULL, "args are strange");
7143 
7144   // checks are the responsibility of the caller
7145   Node* in_start = in;
7146   Node* ct_start = ct;
7147   Node* out_start = out;
7148   if (inOfs != NULL || ctOfs != NULL || outOfs != NULL) {
7149     assert(inOfs != NULL && ctOfs != NULL && outOfs != NULL, "");
7150     in_start = array_element_address(in, inOfs, T_BYTE);
7151     ct_start = array_element_address(ct, ctOfs, T_BYTE);
7152     out_start = array_element_address(out, outOfs, T_BYTE);
7153   }
7154 
7155   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7156   // (because of the predicated logic executed earlier).
7157   // so we cast it here safely.
7158   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7159   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7160   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
7161   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
7162   Node* state = load_field_from_object(ghash_object, "state", "[J");
7163 
7164   if (embeddedCipherObj == NULL || counter == NULL || subkeyHtbl == NULL || state == NULL) {
7165       return false;
7166   }
7167   // cast it to what we know it will be at runtime
7168   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
7169   assert(tinst != NULL, "GCTR obj is null");
7170   assert(tinst->klass()->is_loaded(), "GCTR obj is not loaded");
7171   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7172   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7173   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7174   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7175   const TypeOopPtr* xtype = aklass->as_instance_type();
7176   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7177   aescrypt_object = _gvn.transform(aescrypt_object);
7178   // we need to get the start of the aescrypt_object's expanded key array
7179   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7180   if (k_start == NULL) return false;
7181 
7182   // similarly, get the start address of the r vector
7183   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
7184   Node* state_start = array_element_address(state, intcon(0), T_LONG);
7185   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
7186 
7187   ciKlass* klass = ciTypeArrayKlass::make(T_LONG);
7188   Node* klass_node = makecon(TypeKlassPtr::make(klass));
7189 
7190   // Does this target support this intrinsic?
7191   if (Matcher::htbl_entries == -1) return false;
7192 
7193   Node* subkeyHtbl_48_entries_start;
7194   if (Matcher::htbl_entries != 0) {
7195     // new array to hold 48 computed htbl entries
7196     Node* subkeyHtbl_48_entries = new_array(klass_node, intcon(Matcher::htbl_entries), 0);
7197     if (subkeyHtbl_48_entries == NULL) return false;
7198     subkeyHtbl_48_entries_start = array_element_address(subkeyHtbl_48_entries, intcon(0), T_LONG);
7199   } else {
7200     // This target doesn't need the extra-large Htbl.
7201     subkeyHtbl_48_entries_start = ConvL2X(intcon(0));
7202   }
7203 
7204   // Call the stub, passing params
7205   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7206                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
7207                                stubAddr, stubName, TypePtr::BOTTOM,
7208                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, subkeyHtbl_48_entries_start, cnt_start);
7209 
7210   // return cipher length (int)
7211   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
7212   set_result(retvalue);
7213   return true;
7214 }
7215 
7216 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
7217 // Return node representing slow path of predicate check.
7218 // the pseudo code we want to emulate with this predicate is:
7219 // for encryption:
7220 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7221 // for decryption:
7222 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7223 //    note cipher==plain is more conservative than the original java code but that's OK
7224 //
7225 
7226 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
7227   // The receiver was checked for NULL already.
7228   Node* objGCTR = argument(7);
7229   // Load embeddedCipher field of GCTR object.
7230   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7231   assert(embeddedCipherObj != NULL, "embeddedCipherObj is null");
7232 
7233   // get AESCrypt klass for instanceOf check
7234   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7235   // will have same classloader as CipherBlockChaining object
7236   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
7237   assert(tinst != NULL, "GCTR obj is null");
7238   assert(tinst->klass()->is_loaded(), "GCTR obj is not loaded");
7239 
7240   // we want to do an instanceof comparison against the AESCrypt class
7241   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7242   if (!klass_AESCrypt->is_loaded()) {
7243     // if AESCrypt is not even loaded, we never take the intrinsic fast path
7244     Node* ctrl = control();
7245     set_control(top()); // no regular fast path
7246     return ctrl;
7247   }
7248 
7249   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7250   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7251   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7252   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7253   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
7254 
7255   return instof_false; // even if it is NULL
7256 }
7257 
7258 //------------------------------get_state_from_digest_object-----------------------
7259 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, const char *state_type) {
7260   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
7261   assert (digest_state != NULL, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
7262   if (digest_state == NULL) return (Node *) NULL;
7263 
7264   // now have the array, need to get the start address of the state array
7265   Node* state = array_element_address(digest_state, intcon(0), T_INT);
7266   return state;
7267 }
7268 
7269 //------------------------------get_digest_length_from_sha3_object----------------------------------
7270 Node * LibraryCallKit::get_digest_length_from_digest_object(Node *digest_object) {
7271   Node* digest_length = load_field_from_object(digest_object, "digestLength", "I");
7272   assert (digest_length != NULL, "sanity");
7273   return digest_length;
7274 }
7275 
7276 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
7277 // Return node representing slow path of predicate check.
7278 // the pseudo code we want to emulate with this predicate is:
7279 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
7280 //
7281 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
7282   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
7283          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
7284   assert((uint)predicate < 5, "sanity");
7285 
7286   // The receiver was checked for NULL already.
7287   Node* digestBaseObj = argument(0);
7288 
7289   // get DigestBase klass for instanceOf check
7290   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
7291   assert(tinst != NULL, "digestBaseObj is null");
7292   assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
7293 
7294   const char* klass_name = NULL;
7295   switch (predicate) {
7296   case 0:
7297     if (UseMD5Intrinsics) {
7298       // we want to do an instanceof comparison against the MD5 class
7299       klass_name = "sun/security/provider/MD5";
7300     }
7301     break;
7302   case 1:
7303     if (UseSHA1Intrinsics) {
7304       // we want to do an instanceof comparison against the SHA class
7305       klass_name = "sun/security/provider/SHA";
7306     }
7307     break;
7308   case 2:
7309     if (UseSHA256Intrinsics) {
7310       // we want to do an instanceof comparison against the SHA2 class
7311       klass_name = "sun/security/provider/SHA2";
7312     }
7313     break;
7314   case 3:
7315     if (UseSHA512Intrinsics) {
7316       // we want to do an instanceof comparison against the SHA5 class
7317       klass_name = "sun/security/provider/SHA5";
7318     }
7319     break;
7320   case 4:
7321     if (UseSHA3Intrinsics) {
7322       // we want to do an instanceof comparison against the SHA3 class
7323       klass_name = "sun/security/provider/SHA3";
7324     }
7325     break;
7326   default:
7327     fatal("unknown SHA intrinsic predicate: %d", predicate);
7328   }
7329 
7330   ciKlass* klass = NULL;
7331   if (klass_name != NULL) {
7332     klass = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_name));
7333   }
7334   if ((klass == NULL) || !klass->is_loaded()) {
7335     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
7336     Node* ctrl = control();
7337     set_control(top()); // no intrinsic path
7338     return ctrl;
7339   }
7340   ciInstanceKlass* instklass = klass->as_instance_klass();
7341 
7342   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
7343   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7344   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7345   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
7346 
7347   return instof_false;  // even if it is NULL
7348 }
7349 
7350 //-------------inline_fma-----------------------------------
7351 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
7352   Node *a = NULL;
7353   Node *b = NULL;
7354   Node *c = NULL;
7355   Node* result = NULL;
7356   switch (id) {
7357   case vmIntrinsics::_fmaD:
7358     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
7359     // no receiver since it is static method
7360     a = round_double_node(argument(0));
7361     b = round_double_node(argument(2));
7362     c = round_double_node(argument(4));
7363     result = _gvn.transform(new FmaDNode(control(), a, b, c));
7364     break;
7365   case vmIntrinsics::_fmaF:
7366     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
7367     a = argument(0);
7368     b = argument(1);
7369     c = argument(2);
7370     result = _gvn.transform(new FmaFNode(control(), a, b, c));
7371     break;
7372   default:
7373     fatal_unexpected_iid(id);  break;
7374   }
7375   set_result(result);
7376   return true;
7377 }
7378 
7379 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
7380   // argument(0) is receiver
7381   Node* codePoint = argument(1);
7382   Node* n = NULL;
7383 
7384   switch (id) {
7385     case vmIntrinsics::_isDigit :
7386       n = new DigitNode(control(), codePoint);
7387       break;
7388     case vmIntrinsics::_isLowerCase :
7389       n = new LowerCaseNode(control(), codePoint);
7390       break;
7391     case vmIntrinsics::_isUpperCase :
7392       n = new UpperCaseNode(control(), codePoint);
7393       break;
7394     case vmIntrinsics::_isWhitespace :
7395       n = new WhitespaceNode(control(), codePoint);
7396       break;
7397     default:
7398       fatal_unexpected_iid(id);
7399   }
7400 
7401   set_result(_gvn.transform(n));
7402   return true;
7403 }
7404 
7405 //------------------------------inline_fp_min_max------------------------------
7406 bool LibraryCallKit::inline_fp_min_max(vmIntrinsics::ID id) {
7407 /* DISABLED BECAUSE METHOD DATA ISN'T COLLECTED PER CALL-SITE, SEE JDK-8015416.
7408 
7409   // The intrinsic should be used only when the API branches aren't predictable,
7410   // the last one performing the most important comparison. The following heuristic
7411   // uses the branch statistics to eventually bail out if necessary.
7412 
7413   ciMethodData *md = callee()->method_data();
7414 
7415   if ( md != NULL && md->is_mature() && md->invocation_count() > 0 ) {
7416     ciCallProfile cp = caller()->call_profile_at_bci(bci());
7417 
7418     if ( ((double)cp.count()) / ((double)md->invocation_count()) < 0.8 ) {
7419       // Bail out if the call-site didn't contribute enough to the statistics.
7420       return false;
7421     }
7422 
7423     uint taken = 0, not_taken = 0;
7424 
7425     for (ciProfileData *p = md->first_data(); md->is_valid(p); p = md->next_data(p)) {
7426       if (p->is_BranchData()) {
7427         taken = ((ciBranchData*)p)->taken();
7428         not_taken = ((ciBranchData*)p)->not_taken();
7429       }
7430     }
7431 
7432     double balance = (((double)taken) - ((double)not_taken)) / ((double)md->invocation_count());
7433     balance = balance < 0 ? -balance : balance;
7434     if ( balance > 0.2 ) {
7435       // Bail out if the most important branch is predictable enough.
7436       return false;
7437     }
7438   }
7439 */
7440 
7441   Node *a = NULL;
7442   Node *b = NULL;
7443   Node *n = NULL;
7444   switch (id) {
7445   case vmIntrinsics::_maxF:
7446   case vmIntrinsics::_minF:
7447     assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
7448     a = argument(0);
7449     b = argument(1);
7450     break;
7451   case vmIntrinsics::_maxD:
7452   case vmIntrinsics::_minD:
7453     assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
7454     a = round_double_node(argument(0));
7455     b = round_double_node(argument(2));
7456     break;
7457   default:
7458     fatal_unexpected_iid(id);
7459     break;
7460   }
7461   switch (id) {
7462   case vmIntrinsics::_maxF:  n = new MaxFNode(a, b);  break;
7463   case vmIntrinsics::_minF:  n = new MinFNode(a, b);  break;
7464   case vmIntrinsics::_maxD:  n = new MaxDNode(a, b);  break;
7465   case vmIntrinsics::_minD:  n = new MinDNode(a, b);  break;
7466   default:  fatal_unexpected_iid(id);  break;
7467   }
7468   set_result(_gvn.transform(n));
7469   return true;
7470 }
7471 
7472 bool LibraryCallKit::inline_profileBoolean() {
7473   Node* counts = argument(1);
7474   const TypeAryPtr* ary = NULL;
7475   ciArray* aobj = NULL;
7476   if (counts->is_Con()
7477       && (ary = counts->bottom_type()->isa_aryptr()) != NULL
7478       && (aobj = ary->const_oop()->as_array()) != NULL
7479       && (aobj->length() == 2)) {
7480     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
7481     jint false_cnt = aobj->element_value(0).as_int();
7482     jint  true_cnt = aobj->element_value(1).as_int();
7483 
7484     if (C->log() != NULL) {
7485       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
7486                      false_cnt, true_cnt);
7487     }
7488 
7489     if (false_cnt + true_cnt == 0) {
7490       // According to profile, never executed.
7491       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
7492                           Deoptimization::Action_reinterpret);
7493       return true;
7494     }
7495 
7496     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
7497     // is a number of each value occurrences.
7498     Node* result = argument(0);
7499     if (false_cnt == 0 || true_cnt == 0) {
7500       // According to profile, one value has been never seen.
7501       int expected_val = (false_cnt == 0) ? 1 : 0;
7502 
7503       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
7504       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7505 
7506       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
7507       Node* fast_path = _gvn.transform(new IfTrueNode(check));
7508       Node* slow_path = _gvn.transform(new IfFalseNode(check));
7509 
7510       { // Slow path: uncommon trap for never seen value and then reexecute
7511         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
7512         // the value has been seen at least once.
7513         PreserveJVMState pjvms(this);
7514         PreserveReexecuteState preexecs(this);
7515         jvms()->set_should_reexecute(true);
7516 
7517         set_control(slow_path);
7518         set_i_o(i_o());
7519 
7520         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
7521                             Deoptimization::Action_reinterpret);
7522       }
7523       // The guard for never seen value enables sharpening of the result and
7524       // returning a constant. It allows to eliminate branches on the same value
7525       // later on.
7526       set_control(fast_path);
7527       result = intcon(expected_val);
7528     }
7529     // Stop profiling.
7530     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
7531     // By replacing method body with profile data (represented as ProfileBooleanNode
7532     // on IR level) we effectively disable profiling.
7533     // It enables full speed execution once optimized code is generated.
7534     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
7535     C->record_for_igvn(profile);
7536     set_result(profile);
7537     return true;
7538   } else {
7539     // Continue profiling.
7540     // Profile data isn't available at the moment. So, execute method's bytecode version.
7541     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
7542     // is compiled and counters aren't available since corresponding MethodHandle
7543     // isn't a compile-time constant.
7544     return false;
7545   }
7546 }
7547 
7548 bool LibraryCallKit::inline_isCompileConstant() {
7549   Node* n = argument(0);
7550   set_result(n->is_Con() ? intcon(1) : intcon(0));
7551   return true;
7552 }
7553 
7554 //------------------------------- inline_getObjectSize --------------------------------------
7555 //
7556 // Calculate the runtime size of the object/array.
7557 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
7558 //
7559 bool LibraryCallKit::inline_getObjectSize() {
7560   Node* obj = argument(3);
7561   Node* klass_node = load_object_klass(obj);
7562 
7563   jint  layout_con = Klass::_lh_neutral_value;
7564   Node* layout_val = get_layout_helper(klass_node, layout_con);
7565   int   layout_is_con = (layout_val == NULL);
7566 
7567   if (layout_is_con) {
7568     // Layout helper is constant, can figure out things at compile time.
7569 
7570     if (Klass::layout_helper_is_instance(layout_con)) {
7571       // Instance case:  layout_con contains the size itself.
7572       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
7573       set_result(size);
7574     } else {
7575       // Array case: size is round(header + element_size*arraylength).
7576       // Since arraylength is different for every array instance, we have to
7577       // compute the whole thing at runtime.
7578 
7579       Node* arr_length = load_array_length(obj);
7580 
7581       int round_mask = MinObjAlignmentInBytes - 1;
7582       int hsize  = Klass::layout_helper_header_size(layout_con);
7583       int eshift = Klass::layout_helper_log2_element_size(layout_con);
7584 
7585       if ((round_mask & ~right_n_bits(eshift)) == 0) {
7586         round_mask = 0;  // strength-reduce it if it goes away completely
7587       }
7588       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
7589       Node* header_size = intcon(hsize + round_mask);
7590 
7591       Node* lengthx = ConvI2X(arr_length);
7592       Node* headerx = ConvI2X(header_size);
7593 
7594       Node* abody = lengthx;
7595       if (eshift != 0) {
7596         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
7597       }
7598       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
7599       if (round_mask != 0) {
7600         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
7601       }
7602       size = ConvX2L(size);
7603       set_result(size);
7604     }
7605   } else {
7606     // Layout helper is not constant, need to test for array-ness at runtime.
7607 
7608     enum { _instance_path = 1, _array_path, PATH_LIMIT };
7609     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
7610     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
7611     record_for_igvn(result_reg);
7612 
7613     Node* array_ctl = generate_array_guard(klass_node, NULL);
7614     if (array_ctl != NULL) {
7615       // Array case: size is round(header + element_size*arraylength).
7616       // Since arraylength is different for every array instance, we have to
7617       // compute the whole thing at runtime.
7618 
7619       PreserveJVMState pjvms(this);
7620       set_control(array_ctl);
7621       Node* arr_length = load_array_length(obj);
7622 
7623       int round_mask = MinObjAlignmentInBytes - 1;
7624       Node* mask = intcon(round_mask);
7625 
7626       Node* hss = intcon(Klass::_lh_header_size_shift);
7627       Node* hsm = intcon(Klass::_lh_header_size_mask);
7628       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
7629       header_size = _gvn.transform(new AndINode(header_size, hsm));
7630       header_size = _gvn.transform(new AddINode(header_size, mask));
7631 
7632       // There is no need to mask or shift this value.
7633       // The semantics of LShiftINode include an implicit mask to 0x1F.
7634       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
7635       Node* elem_shift = layout_val;
7636 
7637       Node* lengthx = ConvI2X(arr_length);
7638       Node* headerx = ConvI2X(header_size);
7639 
7640       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
7641       Node* size = _gvn.transform(new AddXNode(headerx, abody));
7642       if (round_mask != 0) {
7643         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
7644       }
7645       size = ConvX2L(size);
7646 
7647       result_reg->init_req(_array_path, control());
7648       result_val->init_req(_array_path, size);
7649     }
7650 
7651     if (!stopped()) {
7652       // Instance case: the layout helper gives us instance size almost directly,
7653       // but we need to mask out the _lh_instance_slow_path_bit.
7654       Node* size = ConvI2X(layout_val);
7655       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
7656       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
7657       size = _gvn.transform(new AndXNode(size, mask));
7658       size = ConvX2L(size);
7659 
7660       result_reg->init_req(_instance_path, control());
7661       result_val->init_req(_instance_path, size);
7662     }
7663 
7664     set_result(result_reg, result_val);
7665   }
7666 
7667   return true;
7668 }
7669 
7670 //------------------------------- inline_blackhole --------------------------------------
7671 //
7672 // Make sure all arguments to this node are alive.
7673 // This matches methods that were requested to be blackholed through compile commands.
7674 //
7675 bool LibraryCallKit::inline_blackhole() {
7676   assert(callee()->is_static(), "Should have been checked before: only static methods here");
7677   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
7678   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
7679 
7680   // Bind call arguments as blackhole arguments to keep them alive
7681   Node* bh = insert_mem_bar(Op_Blackhole);
7682   uint nargs = callee()->arg_size();
7683   for (uint i = 0; i < nargs; i++) {
7684     bh->add_req(argument(i));
7685   }
7686 
7687   return true;
7688 }