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