library_call.cpp revision 5356:c9ccd7b85f20
121308Sache/*
221308Sache * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
321308Sache * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
421308Sache *
521308Sache * This code is free software; you can redistribute it and/or modify it
621308Sache * under the terms of the GNU General Public License version 2 only, as
721308Sache * published by the Free Software Foundation.
821308Sache *
921308Sache * This code is distributed in the hope that it will be useful, but WITHOUT
1058310Sache * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1121308Sache * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
1221308Sache * version 2 for more details (a copy is included in the LICENSE file that
1321308Sache * accompanied this code).
1421308Sache *
1521308Sache * You should have received a copy of the GNU General Public License version
1621308Sache * 2 along with this work; if not, write to the Free Software Foundation,
1721308Sache * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1821308Sache *
1921308Sache * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2021308Sache * or visit www.oracle.com if you need additional information or have any
2158310Sache * questions.
2221308Sache *
2321308Sache */
2421308Sache
2521308Sache#include "precompiled.hpp"
2621308Sache#include "classfile/systemDictionary.hpp"
2721308Sache#include "classfile/vmSymbols.hpp"
2821308Sache#include "compiler/compileBroker.hpp"
2921308Sache#include "compiler/compileLog.hpp"
3021308Sache#include "oops/objArrayKlass.hpp"
3121308Sache#include "opto/addnode.hpp"
3221308Sache#include "opto/callGenerator.hpp"
3321308Sache#include "opto/cfgnode.hpp"
3421308Sache#include "opto/idealKit.hpp"
3521308Sache#include "opto/mathexactnode.hpp"
3621308Sache#include "opto/mulnode.hpp"
3721308Sache#include "opto/parse.hpp"
3821308Sache#include "opto/runtime.hpp"
3921308Sache#include "opto/subnode.hpp"
4021308Sache#include "prims/nativeLookup.hpp"
4121308Sache#include "runtime/sharedRuntime.hpp"
4221308Sache#include "trace/traceMacros.hpp"
4321308Sache
4421308Sacheclass LibraryIntrinsic : public InlineCallGenerator {
4521308Sache  // Extend the set of intrinsics known to the runtime:
4621308Sache public:
4721308Sache private:
4821308Sache  bool             _is_virtual;
4958310Sache  bool             _is_predicted;
5058310Sache  vmIntrinsics::ID _intrinsic_id;
5158310Sache
5221308Sache public:
5321308Sache  LibraryIntrinsic(ciMethod* m, bool is_virtual, bool is_predicted, vmIntrinsics::ID id)
5421308Sache    : InlineCallGenerator(m),
5521308Sache      _is_virtual(is_virtual),
5621308Sache      _is_predicted(is_predicted),
5721308Sache      _intrinsic_id(id)
5875406Sache  {
5975406Sache  }
6075406Sache  virtual bool is_intrinsic() const { return true; }
6175406Sache  virtual bool is_virtual()   const { return _is_virtual; }
6221308Sache  virtual bool is_predicted()   const { return _is_predicted; }
6321308Sache  virtual JVMState* generate(JVMState* jvms);
6421308Sache  virtual Node* generate_predicate(JVMState* jvms);
6521308Sache  vmIntrinsics::ID intrinsic_id() const { return _intrinsic_id; }
6621308Sache};
6721308Sache
6821308Sache
6921308Sache// Local helper class for LibraryIntrinsic:
7021308Sacheclass LibraryCallKit : public GraphKit {
7121308Sache private:
7221308Sache  LibraryIntrinsic* _intrinsic;     // the library intrinsic being called
7321308Sache  Node*             _result;        // the result node, if any
7421308Sache  int               _reexecute_sp;  // the stack pointer when bytecode needs to be reexecuted
7521308Sache
7621308Sache  const TypeOopPtr* sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr = false);
7721308Sache
7821308Sache public:
7921308Sache  LibraryCallKit(JVMState* jvms, LibraryIntrinsic* intrinsic)
8021308Sache    : GraphKit(jvms),
8121308Sache      _intrinsic(intrinsic),
8221308Sache      _result(NULL)
8321308Sache  {
8421308Sache    // Check if this is a root compile.  In that case we don't have a caller.
8521308Sache    if (!jvms->has_method()) {
8621308Sache      _reexecute_sp = sp();
8721308Sache    } else {
8821308Sache      // Find out how many arguments the interpreter needs when deoptimizing
8921308Sache      // and save the stack pointer value so it can used by uncommon_trap.
9021308Sache      // We find the argument count by looking at the declared signature.
9121308Sache      bool ignored_will_link;
9221308Sache      ciSignature* declared_signature = NULL;
9375406Sache      ciMethod* ignored_callee = caller()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
9421308Sache      const int nargs = declared_signature->arg_size_for_bc(caller()->java_code_at_bci(bci()));
9575406Sache      _reexecute_sp = sp() + nargs;  // "push" arguments back on stack
9621308Sache    }
9721308Sache  }
9821308Sache
9921308Sache  virtual LibraryCallKit* is_LibraryCallKit() const { return (LibraryCallKit*)this; }
10021308Sache
10121308Sache  ciMethod*         caller()    const    { return jvms()->method(); }
10221308Sache  int               bci()       const    { return jvms()->bci(); }
103157184Sache  LibraryIntrinsic* intrinsic() const    { return _intrinsic; }
104157184Sache  vmIntrinsics::ID  intrinsic_id() const { return _intrinsic->intrinsic_id(); }
10575406Sache  ciMethod*         callee()    const    { return _intrinsic->method(); }
10621308Sache
10721308Sache  bool try_to_inline();
10875406Sache  Node* try_to_predicate();
10921308Sache
11021308Sache  void push_result() {
11121308Sache    // Push the result onto the stack.
11221308Sache    if (!stopped() && result() != NULL) {
11321308Sache      BasicType bt = result()->bottom_type()->basic_type();
114157184Sache      push_node(bt, result());
115157184Sache    }
116165670Sache  }
117157184Sache
118157184Sache private:
119157184Sache  void fatal_unexpected_iid(vmIntrinsics::ID iid) {
12075406Sache    fatal(err_msg_res("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid)));
121157184Sache  }
12221308Sache
12321308Sache  void  set_result(Node* n) { assert(_result == NULL, "only set once"); _result = n; }
12421308Sache  void  set_result(RegionNode* region, PhiNode* value);
12521308Sache  Node*     result() { return _result; }
12621308Sache
12721308Sache  virtual int reexecute_sp() { return _reexecute_sp; }
12821308Sache
12921308Sache  // Helper functions to inline natives
13021308Sache  Node* generate_guard(Node* test, RegionNode* region, float true_prob);
13121308Sache  Node* generate_slow_guard(Node* test, RegionNode* region);
13221308Sache  Node* generate_fair_guard(Node* test, RegionNode* region);
13375406Sache  Node* generate_negative_guard(Node* index, RegionNode* region,
13421308Sache                                // resulting CastII of index:
13521308Sache                                Node* *pos_index = NULL);
13621308Sache  Node* generate_nonpositive_guard(Node* index, bool never_negative,
13721308Sache                                   // resulting CastII of index:
13821308Sache                                   Node* *pos_index = NULL);
13921308Sache  Node* generate_limit_guard(Node* offset, Node* subseq_length,
14021308Sache                             Node* array_length,
14121308Sache                             RegionNode* region);
14221308Sache  Node* generate_current_thread(Node* &tls_output);
14321308Sache  address basictype2arraycopy(BasicType t, Node *src_offset, Node *dest_offset,
14421308Sache                              bool disjoint_bases, const char* &name, bool dest_uninitialized);
14575406Sache  Node* load_mirror_from_klass(Node* klass);
14675406Sache  Node* load_klass_from_mirror_common(Node* mirror, bool never_see_null,
14721308Sache                                      RegionNode* region, int null_path,
14821308Sache                                      int offset);
14921308Sache  Node* load_klass_from_mirror(Node* mirror, bool never_see_null,
15021308Sache                               RegionNode* region, int null_path) {
15121308Sache    int offset = java_lang_Class::klass_offset_in_bytes();
15275406Sache    return load_klass_from_mirror_common(mirror, never_see_null,
15321308Sache                                         region, null_path,
15421308Sache                                         offset);
15521308Sache  }
15621308Sache  Node* load_array_klass_from_mirror(Node* mirror, bool never_see_null,
15775406Sache                                     RegionNode* region, int null_path) {
15875406Sache    int offset = java_lang_Class::array_klass_offset_in_bytes();
15975406Sache    return load_klass_from_mirror_common(mirror, never_see_null,
16021308Sache                                         region, null_path,
16121308Sache                                         offset);
16221308Sache  }
16321308Sache  Node* generate_access_flags_guard(Node* kls,
16421308Sache                                    int modifier_mask, int modifier_bits,
16521308Sache                                    RegionNode* region);
16621308Sache  Node* generate_interface_guard(Node* kls, RegionNode* region);
16721308Sache  Node* generate_array_guard(Node* kls, RegionNode* region) {
16821308Sache    return generate_array_guard_common(kls, region, false, false);
16921308Sache  }
170119610Sache  Node* generate_non_array_guard(Node* kls, RegionNode* region) {
17121308Sache    return generate_array_guard_common(kls, region, false, true);
172119610Sache  }
17321308Sache  Node* generate_objArray_guard(Node* kls, RegionNode* region) {
17421308Sache    return generate_array_guard_common(kls, region, true, false);
17521308Sache  }
17621308Sache  Node* generate_non_objArray_guard(Node* kls, RegionNode* region) {
17721308Sache    return generate_array_guard_common(kls, region, true, true);
17821308Sache  }
17921308Sache  Node* generate_array_guard_common(Node* kls, RegionNode* region,
18021308Sache                                    bool obj_array, bool not_array);
18121308Sache  Node* generate_virtual_guard(Node* obj_klass, RegionNode* slow_region);
18221308Sache  CallJavaNode* generate_method_call(vmIntrinsics::ID method_id,
18321308Sache                                     bool is_virtual = false, bool is_static = false);
18421308Sache  CallJavaNode* generate_method_call_static(vmIntrinsics::ID method_id) {
18521308Sache    return generate_method_call(method_id, false, true);
18621308Sache  }
18721308Sache  CallJavaNode* generate_method_call_virtual(vmIntrinsics::ID method_id) {
18821308Sache    return generate_method_call(method_id, true, false);
18975406Sache  }
19075406Sache  Node * load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString, bool is_exact, bool is_static);
19121308Sache
19221308Sache  Node* make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2);
19375406Sache  Node* make_string_method_node(int opcode, Node* str1, Node* str2);
19421308Sache  bool inline_string_compareTo();
19521308Sache  bool inline_string_indexOf();
19621308Sache  Node* string_indexOf(Node* string_object, ciTypeArray* target_array, jint offset, jint cache_i, jint md2_i);
19721308Sache  bool inline_string_equals();
19821308Sache  Node* round_double_node(Node* n);
19921308Sache  bool runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName);
20021308Sache  bool inline_math_native(vmIntrinsics::ID id);
20121308Sache  bool inline_trig(vmIntrinsics::ID id);
20221308Sache  bool inline_math(vmIntrinsics::ID id);
20321308Sache  bool inline_math_mathExact(Node* math);
20421308Sache  bool inline_math_addExact();
20521308Sache  bool inline_exp();
206119610Sache  bool inline_pow();
20721308Sache  void finish_pow_exp(Node* result, Node* x, Node* y, const TypeFunc* call_type, address funcAddr, const char* funcName);
20821308Sache  bool inline_min_max(vmIntrinsics::ID id);
20921308Sache  Node* generate_min_max(vmIntrinsics::ID id, Node* x, Node* y);
21021308Sache  // This returns Type::AnyPtr, RawPtr, or OopPtr.
21121308Sache  int classify_unsafe_addr(Node* &base, Node* &offset);
21221308Sache  Node* make_unsafe_address(Node* base, Node* offset);
21321308Sache  // Helper for inline_unsafe_access.
21421308Sache  // Generates the guards that check whether the result of
21521308Sache  // Unsafe.getObject should be recorded in an SATB log buffer.
21621308Sache  void insert_pre_barrier(Node* base_oop, Node* offset, Node* pre_val, bool need_mem_bar);
21721308Sache  bool inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile);
21821308Sache  bool inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static);
21921308Sache  static bool klass_needs_init_guard(Node* kls);
22075406Sache  bool inline_unsafe_allocate();
22121308Sache  bool inline_unsafe_copyMemory();
22221308Sache  bool inline_native_currentThread();
22321308Sache#ifdef TRACE_HAVE_INTRINSICS
22421308Sache  bool inline_native_classID();
22521308Sache  bool inline_native_threadID();
22621308Sache#endif
22721308Sache  bool inline_native_time_funcs(address method, const char* funcName);
22821308Sache  bool inline_native_isInterrupted();
22921308Sache  bool inline_native_Class_query(vmIntrinsics::ID id);
23021308Sache  bool inline_native_subtype_check();
231119610Sache
23221308Sache  bool inline_native_newArray();
23321308Sache  bool inline_native_getLength();
23421308Sache  bool inline_array_copyOf(bool is_copyOfRange);
23521308Sache  bool inline_array_equals();
23621308Sache  void copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark);
23721308Sache  bool inline_native_clone(bool is_virtual);
23821308Sache  bool inline_native_Reflection_getCallerClass();
23921308Sache  // Helper function for inlining native object hash method
24075406Sache  bool inline_native_hashcode(bool is_virtual, bool is_static);
24121308Sache  bool inline_native_getClass();
24221308Sache
24321308Sache  // Helper functions for inlining arraycopy
24421308Sache  bool inline_arraycopy();
24521308Sache  void generate_arraycopy(const TypePtr* adr_type,
24621308Sache                          BasicType basic_elem_type,
24721308Sache                          Node* src,  Node* src_offset,
24821308Sache                          Node* dest, Node* dest_offset,
24921308Sache                          Node* copy_length,
25021308Sache                          bool disjoint_bases = false,
25121308Sache                          bool length_never_negative = false,
25221308Sache                          RegionNode* slow_region = NULL);
25321308Sache  AllocateArrayNode* tightly_coupled_allocation(Node* ptr,
254119610Sache                                                RegionNode* slow_region);
25521308Sache  void generate_clear_array(const TypePtr* adr_type,
25675406Sache                            Node* dest,
25721308Sache                            BasicType basic_elem_type,
25821308Sache                            Node* slice_off,
25921308Sache                            Node* slice_len,
26021308Sache                            Node* slice_end);
26121308Sache  bool generate_block_arraycopy(const TypePtr* adr_type,
26221308Sache                                BasicType basic_elem_type,
26321308Sache                                AllocateNode* alloc,
26421308Sache                                Node* src,  Node* src_offset,
26521308Sache                                Node* dest, Node* dest_offset,
26621308Sache                                Node* dest_size, bool dest_uninitialized);
26721308Sache  void generate_slow_arraycopy(const TypePtr* adr_type,
26821308Sache                               Node* src,  Node* src_offset,
26921308Sache                               Node* dest, Node* dest_offset,
27021308Sache                               Node* copy_length, bool dest_uninitialized);
27121308Sache  Node* generate_checkcast_arraycopy(const TypePtr* adr_type,
272                                     Node* dest_elem_klass,
273                                     Node* src,  Node* src_offset,
274                                     Node* dest, Node* dest_offset,
275                                     Node* copy_length, bool dest_uninitialized);
276  Node* generate_generic_arraycopy(const TypePtr* adr_type,
277                                   Node* src,  Node* src_offset,
278                                   Node* dest, Node* dest_offset,
279                                   Node* copy_length, bool dest_uninitialized);
280  void generate_unchecked_arraycopy(const TypePtr* adr_type,
281                                    BasicType basic_elem_type,
282                                    bool disjoint_bases,
283                                    Node* src,  Node* src_offset,
284                                    Node* dest, Node* dest_offset,
285                                    Node* copy_length, bool dest_uninitialized);
286  typedef enum { LS_xadd, LS_xchg, LS_cmpxchg } LoadStoreKind;
287  bool inline_unsafe_load_store(BasicType type,  LoadStoreKind kind);
288  bool inline_unsafe_ordered_store(BasicType type);
289  bool inline_unsafe_fence(vmIntrinsics::ID id);
290  bool inline_fp_conversions(vmIntrinsics::ID id);
291  bool inline_number_methods(vmIntrinsics::ID id);
292  bool inline_reference_get();
293  bool inline_aescrypt_Block(vmIntrinsics::ID id);
294  bool inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id);
295  Node* inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting);
296  Node* get_key_start_from_aescrypt_object(Node* aescrypt_object);
297  bool inline_encodeISOArray();
298  bool inline_updateCRC32();
299  bool inline_updateBytesCRC32();
300  bool inline_updateByteBufferCRC32();
301};
302
303
304//---------------------------make_vm_intrinsic----------------------------
305CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
306  vmIntrinsics::ID id = m->intrinsic_id();
307  assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
308
309  if (DisableIntrinsic[0] != '\0'
310      && strstr(DisableIntrinsic, vmIntrinsics::name_at(id)) != NULL) {
311    // disabled by a user request on the command line:
312    // example: -XX:DisableIntrinsic=_hashCode,_getClass
313    return NULL;
314  }
315
316  if (!m->is_loaded()) {
317    // do not attempt to inline unloaded methods
318    return NULL;
319  }
320
321  // Only a few intrinsics implement a virtual dispatch.
322  // They are expensive calls which are also frequently overridden.
323  if (is_virtual) {
324    switch (id) {
325    case vmIntrinsics::_hashCode:
326    case vmIntrinsics::_clone:
327      // OK, Object.hashCode and Object.clone intrinsics come in both flavors
328      break;
329    default:
330      return NULL;
331    }
332  }
333
334  // -XX:-InlineNatives disables nearly all intrinsics:
335  if (!InlineNatives) {
336    switch (id) {
337    case vmIntrinsics::_indexOf:
338    case vmIntrinsics::_compareTo:
339    case vmIntrinsics::_equals:
340    case vmIntrinsics::_equalsC:
341    case vmIntrinsics::_getAndAddInt:
342    case vmIntrinsics::_getAndAddLong:
343    case vmIntrinsics::_getAndSetInt:
344    case vmIntrinsics::_getAndSetLong:
345    case vmIntrinsics::_getAndSetObject:
346    case vmIntrinsics::_loadFence:
347    case vmIntrinsics::_storeFence:
348    case vmIntrinsics::_fullFence:
349      break;  // InlineNatives does not control String.compareTo
350    case vmIntrinsics::_Reference_get:
351      break;  // InlineNatives does not control Reference.get
352    default:
353      return NULL;
354    }
355  }
356
357  bool is_predicted = false;
358
359  switch (id) {
360  case vmIntrinsics::_compareTo:
361    if (!SpecialStringCompareTo)  return NULL;
362    if (!Matcher::match_rule_supported(Op_StrComp))  return NULL;
363    break;
364  case vmIntrinsics::_indexOf:
365    if (!SpecialStringIndexOf)  return NULL;
366    break;
367  case vmIntrinsics::_equals:
368    if (!SpecialStringEquals)  return NULL;
369    if (!Matcher::match_rule_supported(Op_StrEquals))  return NULL;
370    break;
371  case vmIntrinsics::_equalsC:
372    if (!SpecialArraysEquals)  return NULL;
373    if (!Matcher::match_rule_supported(Op_AryEq))  return NULL;
374    break;
375  case vmIntrinsics::_arraycopy:
376    if (!InlineArrayCopy)  return NULL;
377    break;
378  case vmIntrinsics::_copyMemory:
379    if (StubRoutines::unsafe_arraycopy() == NULL)  return NULL;
380    if (!InlineArrayCopy)  return NULL;
381    break;
382  case vmIntrinsics::_hashCode:
383    if (!InlineObjectHash)  return NULL;
384    break;
385  case vmIntrinsics::_clone:
386  case vmIntrinsics::_copyOf:
387  case vmIntrinsics::_copyOfRange:
388    if (!InlineObjectCopy)  return NULL;
389    // These also use the arraycopy intrinsic mechanism:
390    if (!InlineArrayCopy)  return NULL;
391    break;
392  case vmIntrinsics::_encodeISOArray:
393    if (!SpecialEncodeISOArray)  return NULL;
394    if (!Matcher::match_rule_supported(Op_EncodeISOArray))  return NULL;
395    break;
396  case vmIntrinsics::_checkIndex:
397    // We do not intrinsify this.  The optimizer does fine with it.
398    return NULL;
399
400  case vmIntrinsics::_getCallerClass:
401    if (!UseNewReflection)  return NULL;
402    if (!InlineReflectionGetCallerClass)  return NULL;
403    if (SystemDictionary::reflect_CallerSensitive_klass() == NULL)  return NULL;
404    break;
405
406  case vmIntrinsics::_bitCount_i:
407    if (!Matcher::match_rule_supported(Op_PopCountI)) return NULL;
408    break;
409
410  case vmIntrinsics::_bitCount_l:
411    if (!Matcher::match_rule_supported(Op_PopCountL)) return NULL;
412    break;
413
414  case vmIntrinsics::_numberOfLeadingZeros_i:
415    if (!Matcher::match_rule_supported(Op_CountLeadingZerosI)) return NULL;
416    break;
417
418  case vmIntrinsics::_numberOfLeadingZeros_l:
419    if (!Matcher::match_rule_supported(Op_CountLeadingZerosL)) return NULL;
420    break;
421
422  case vmIntrinsics::_numberOfTrailingZeros_i:
423    if (!Matcher::match_rule_supported(Op_CountTrailingZerosI)) return NULL;
424    break;
425
426  case vmIntrinsics::_numberOfTrailingZeros_l:
427    if (!Matcher::match_rule_supported(Op_CountTrailingZerosL)) return NULL;
428    break;
429
430  case vmIntrinsics::_reverseBytes_c:
431    if (!Matcher::match_rule_supported(Op_ReverseBytesUS)) return NULL;
432    break;
433  case vmIntrinsics::_reverseBytes_s:
434    if (!Matcher::match_rule_supported(Op_ReverseBytesS))  return NULL;
435    break;
436  case vmIntrinsics::_reverseBytes_i:
437    if (!Matcher::match_rule_supported(Op_ReverseBytesI))  return NULL;
438    break;
439  case vmIntrinsics::_reverseBytes_l:
440    if (!Matcher::match_rule_supported(Op_ReverseBytesL))  return NULL;
441    break;
442
443  case vmIntrinsics::_Reference_get:
444    // Use the intrinsic version of Reference.get() so that the value in
445    // the referent field can be registered by the G1 pre-barrier code.
446    // Also add memory barrier to prevent commoning reads from this field
447    // across safepoint since GC can change it value.
448    break;
449
450  case vmIntrinsics::_compareAndSwapObject:
451#ifdef _LP64
452    if (!UseCompressedOops && !Matcher::match_rule_supported(Op_CompareAndSwapP)) return NULL;
453#endif
454    break;
455
456  case vmIntrinsics::_compareAndSwapLong:
457    if (!Matcher::match_rule_supported(Op_CompareAndSwapL)) return NULL;
458    break;
459
460  case vmIntrinsics::_getAndAddInt:
461    if (!Matcher::match_rule_supported(Op_GetAndAddI)) return NULL;
462    break;
463
464  case vmIntrinsics::_getAndAddLong:
465    if (!Matcher::match_rule_supported(Op_GetAndAddL)) return NULL;
466    break;
467
468  case vmIntrinsics::_getAndSetInt:
469    if (!Matcher::match_rule_supported(Op_GetAndSetI)) return NULL;
470    break;
471
472  case vmIntrinsics::_getAndSetLong:
473    if (!Matcher::match_rule_supported(Op_GetAndSetL)) return NULL;
474    break;
475
476  case vmIntrinsics::_getAndSetObject:
477#ifdef _LP64
478    if (!UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;
479    if (UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetN)) return NULL;
480    break;
481#else
482    if (!Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;
483    break;
484#endif
485
486  case vmIntrinsics::_aescrypt_encryptBlock:
487  case vmIntrinsics::_aescrypt_decryptBlock:
488    if (!UseAESIntrinsics) return NULL;
489    break;
490
491  case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
492  case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
493    if (!UseAESIntrinsics) return NULL;
494    // these two require the predicated logic
495    is_predicted = true;
496    break;
497
498  case vmIntrinsics::_updateCRC32:
499  case vmIntrinsics::_updateBytesCRC32:
500  case vmIntrinsics::_updateByteBufferCRC32:
501    if (!UseCRC32Intrinsics) return NULL;
502    break;
503
504  case vmIntrinsics::_addExact:
505    if (!Matcher::match_rule_supported(Op_AddExactI)) {
506      return NULL;
507    }
508    if (!UseMathExactIntrinsics) {
509      return NULL;
510    }
511    break;
512
513 default:
514    assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
515    assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
516    break;
517  }
518
519  // -XX:-InlineClassNatives disables natives from the Class class.
520  // The flag applies to all reflective calls, notably Array.newArray
521  // (visible to Java programmers as Array.newInstance).
522  if (m->holder()->name() == ciSymbol::java_lang_Class() ||
523      m->holder()->name() == ciSymbol::java_lang_reflect_Array()) {
524    if (!InlineClassNatives)  return NULL;
525  }
526
527  // -XX:-InlineThreadNatives disables natives from the Thread class.
528  if (m->holder()->name() == ciSymbol::java_lang_Thread()) {
529    if (!InlineThreadNatives)  return NULL;
530  }
531
532  // -XX:-InlineMathNatives disables natives from the Math,Float and Double classes.
533  if (m->holder()->name() == ciSymbol::java_lang_Math() ||
534      m->holder()->name() == ciSymbol::java_lang_Float() ||
535      m->holder()->name() == ciSymbol::java_lang_Double()) {
536    if (!InlineMathNatives)  return NULL;
537  }
538
539  // -XX:-InlineUnsafeOps disables natives from the Unsafe class.
540  if (m->holder()->name() == ciSymbol::sun_misc_Unsafe()) {
541    if (!InlineUnsafeOps)  return NULL;
542  }
543
544  return new LibraryIntrinsic(m, is_virtual, is_predicted, (vmIntrinsics::ID) id);
545}
546
547//----------------------register_library_intrinsics-----------------------
548// Initialize this file's data structures, for each Compile instance.
549void Compile::register_library_intrinsics() {
550  // Nothing to do here.
551}
552
553JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
554  LibraryCallKit kit(jvms, this);
555  Compile* C = kit.C;
556  int nodes = C->unique();
557#ifndef PRODUCT
558  if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
559    char buf[1000];
560    const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
561    tty->print_cr("Intrinsic %s", str);
562  }
563#endif
564  ciMethod* callee = kit.callee();
565  const int bci    = kit.bci();
566
567  // Try to inline the intrinsic.
568  if (kit.try_to_inline()) {
569    if (C->print_intrinsics() || C->print_inlining()) {
570      C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual)" : "(intrinsic)");
571    }
572    C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
573    if (C->log()) {
574      C->log()->elem("intrinsic id='%s'%s nodes='%d'",
575                     vmIntrinsics::name_at(intrinsic_id()),
576                     (is_virtual() ? " virtual='1'" : ""),
577                     C->unique() - nodes);
578    }
579    // Push the result from the inlined method onto the stack.
580    kit.push_result();
581    return kit.transfer_exceptions_into_jvms();
582  }
583
584  // The intrinsic bailed out
585  if (C->print_intrinsics() || C->print_inlining()) {
586    if (jvms->has_method()) {
587      // Not a root compile.
588      const char* msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
589      C->print_inlining(callee, jvms->depth() - 1, bci, msg);
590    } else {
591      // Root compile
592      tty->print("Did not generate intrinsic %s%s at bci:%d in",
593               vmIntrinsics::name_at(intrinsic_id()),
594               (is_virtual() ? " (virtual)" : ""), bci);
595    }
596  }
597  C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
598  return NULL;
599}
600
601Node* LibraryIntrinsic::generate_predicate(JVMState* jvms) {
602  LibraryCallKit kit(jvms, this);
603  Compile* C = kit.C;
604  int nodes = C->unique();
605#ifndef PRODUCT
606  assert(is_predicted(), "sanity");
607  if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
608    char buf[1000];
609    const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
610    tty->print_cr("Predicate for intrinsic %s", str);
611  }
612#endif
613  ciMethod* callee = kit.callee();
614  const int bci    = kit.bci();
615
616  Node* slow_ctl = kit.try_to_predicate();
617  if (!kit.failing()) {
618    if (C->print_intrinsics() || C->print_inlining()) {
619      C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual)" : "(intrinsic)");
620    }
621    C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
622    if (C->log()) {
623      C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
624                     vmIntrinsics::name_at(intrinsic_id()),
625                     (is_virtual() ? " virtual='1'" : ""),
626                     C->unique() - nodes);
627    }
628    return slow_ctl; // Could be NULL if the check folds.
629  }
630
631  // The intrinsic bailed out
632  if (C->print_intrinsics() || C->print_inlining()) {
633    if (jvms->has_method()) {
634      // Not a root compile.
635      const char* msg = "failed to generate predicate for intrinsic";
636      C->print_inlining(kit.callee(), jvms->depth() - 1, bci, msg);
637    } else {
638      // Root compile
639      C->print_inlining_stream()->print("Did not generate predicate for intrinsic %s%s at bci:%d in",
640                                        vmIntrinsics::name_at(intrinsic_id()),
641                                        (is_virtual() ? " (virtual)" : ""), bci);
642    }
643  }
644  C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
645  return NULL;
646}
647
648bool LibraryCallKit::try_to_inline() {
649  // Handle symbolic names for otherwise undistinguished boolean switches:
650  const bool is_store       = true;
651  const bool is_native_ptr  = true;
652  const bool is_static      = true;
653  const bool is_volatile    = true;
654
655  if (!jvms()->has_method()) {
656    // Root JVMState has a null method.
657    assert(map()->memory()->Opcode() == Op_Parm, "");
658    // Insert the memory aliasing node
659    set_all_memory(reset_memory());
660  }
661  assert(merged_memory(), "");
662
663
664  switch (intrinsic_id()) {
665  case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
666  case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
667  case vmIntrinsics::_getClass:                 return inline_native_getClass();
668
669  case vmIntrinsics::_dsin:
670  case vmIntrinsics::_dcos:
671  case vmIntrinsics::_dtan:
672  case vmIntrinsics::_dabs:
673  case vmIntrinsics::_datan2:
674  case vmIntrinsics::_dsqrt:
675  case vmIntrinsics::_dexp:
676  case vmIntrinsics::_dlog:
677  case vmIntrinsics::_dlog10:
678  case vmIntrinsics::_dpow:                     return inline_math_native(intrinsic_id());
679
680  case vmIntrinsics::_min:
681  case vmIntrinsics::_max:                      return inline_min_max(intrinsic_id());
682
683  case vmIntrinsics::_addExact:                 return inline_math_addExact();
684
685  case vmIntrinsics::_arraycopy:                return inline_arraycopy();
686
687  case vmIntrinsics::_compareTo:                return inline_string_compareTo();
688  case vmIntrinsics::_indexOf:                  return inline_string_indexOf();
689  case vmIntrinsics::_equals:                   return inline_string_equals();
690
691  case vmIntrinsics::_getObject:                return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,  !is_volatile);
692  case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, !is_volatile);
693  case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,    !is_volatile);
694  case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,   !is_volatile);
695  case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,    !is_volatile);
696  case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,     !is_volatile);
697  case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,    !is_volatile);
698  case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,   !is_volatile);
699  case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,  !is_volatile);
700
701  case vmIntrinsics::_putObject:                return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,  !is_volatile);
702  case vmIntrinsics::_putBoolean:               return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN, !is_volatile);
703  case vmIntrinsics::_putByte:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,    !is_volatile);
704  case vmIntrinsics::_putShort:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,   !is_volatile);
705  case vmIntrinsics::_putChar:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,    !is_volatile);
706  case vmIntrinsics::_putInt:                   return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,     !is_volatile);
707  case vmIntrinsics::_putLong:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,    !is_volatile);
708  case vmIntrinsics::_putFloat:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,   !is_volatile);
709  case vmIntrinsics::_putDouble:                return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,  !is_volatile);
710
711  case vmIntrinsics::_getByte_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_BYTE,    !is_volatile);
712  case vmIntrinsics::_getShort_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_SHORT,   !is_volatile);
713  case vmIntrinsics::_getChar_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_CHAR,    !is_volatile);
714  case vmIntrinsics::_getInt_raw:               return inline_unsafe_access( is_native_ptr, !is_store, T_INT,     !is_volatile);
715  case vmIntrinsics::_getLong_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_LONG,    !is_volatile);
716  case vmIntrinsics::_getFloat_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_FLOAT,   !is_volatile);
717  case vmIntrinsics::_getDouble_raw:            return inline_unsafe_access( is_native_ptr, !is_store, T_DOUBLE,  !is_volatile);
718  case vmIntrinsics::_getAddress_raw:           return inline_unsafe_access( is_native_ptr, !is_store, T_ADDRESS, !is_volatile);
719
720  case vmIntrinsics::_putByte_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_BYTE,    !is_volatile);
721  case vmIntrinsics::_putShort_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_SHORT,   !is_volatile);
722  case vmIntrinsics::_putChar_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_CHAR,    !is_volatile);
723  case vmIntrinsics::_putInt_raw:               return inline_unsafe_access( is_native_ptr,  is_store, T_INT,     !is_volatile);
724  case vmIntrinsics::_putLong_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_LONG,    !is_volatile);
725  case vmIntrinsics::_putFloat_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_FLOAT,   !is_volatile);
726  case vmIntrinsics::_putDouble_raw:            return inline_unsafe_access( is_native_ptr,  is_store, T_DOUBLE,  !is_volatile);
727  case vmIntrinsics::_putAddress_raw:           return inline_unsafe_access( is_native_ptr,  is_store, T_ADDRESS, !is_volatile);
728
729  case vmIntrinsics::_getObjectVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,   is_volatile);
730  case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN,  is_volatile);
731  case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,     is_volatile);
732  case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,    is_volatile);
733  case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,     is_volatile);
734  case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,      is_volatile);
735  case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,     is_volatile);
736  case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,    is_volatile);
737  case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,   is_volatile);
738
739  case vmIntrinsics::_putObjectVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,   is_volatile);
740  case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN,  is_volatile);
741  case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,     is_volatile);
742  case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,    is_volatile);
743  case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,     is_volatile);
744  case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,      is_volatile);
745  case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,     is_volatile);
746  case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,    is_volatile);
747  case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,   is_volatile);
748
749  case vmIntrinsics::_prefetchRead:             return inline_unsafe_prefetch(!is_native_ptr, !is_store, !is_static);
750  case vmIntrinsics::_prefetchWrite:            return inline_unsafe_prefetch(!is_native_ptr,  is_store, !is_static);
751  case vmIntrinsics::_prefetchReadStatic:       return inline_unsafe_prefetch(!is_native_ptr, !is_store,  is_static);
752  case vmIntrinsics::_prefetchWriteStatic:      return inline_unsafe_prefetch(!is_native_ptr,  is_store,  is_static);
753
754  case vmIntrinsics::_compareAndSwapObject:     return inline_unsafe_load_store(T_OBJECT, LS_cmpxchg);
755  case vmIntrinsics::_compareAndSwapInt:        return inline_unsafe_load_store(T_INT,    LS_cmpxchg);
756  case vmIntrinsics::_compareAndSwapLong:       return inline_unsafe_load_store(T_LONG,   LS_cmpxchg);
757
758  case vmIntrinsics::_putOrderedObject:         return inline_unsafe_ordered_store(T_OBJECT);
759  case vmIntrinsics::_putOrderedInt:            return inline_unsafe_ordered_store(T_INT);
760  case vmIntrinsics::_putOrderedLong:           return inline_unsafe_ordered_store(T_LONG);
761
762  case vmIntrinsics::_getAndAddInt:             return inline_unsafe_load_store(T_INT,    LS_xadd);
763  case vmIntrinsics::_getAndAddLong:            return inline_unsafe_load_store(T_LONG,   LS_xadd);
764  case vmIntrinsics::_getAndSetInt:             return inline_unsafe_load_store(T_INT,    LS_xchg);
765  case vmIntrinsics::_getAndSetLong:            return inline_unsafe_load_store(T_LONG,   LS_xchg);
766  case vmIntrinsics::_getAndSetObject:          return inline_unsafe_load_store(T_OBJECT, LS_xchg);
767
768  case vmIntrinsics::_loadFence:
769  case vmIntrinsics::_storeFence:
770  case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
771
772  case vmIntrinsics::_currentThread:            return inline_native_currentThread();
773  case vmIntrinsics::_isInterrupted:            return inline_native_isInterrupted();
774
775#ifdef TRACE_HAVE_INTRINSICS
776  case vmIntrinsics::_classID:                  return inline_native_classID();
777  case vmIntrinsics::_threadID:                 return inline_native_threadID();
778  case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, TRACE_TIME_METHOD), "counterTime");
779#endif
780  case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
781  case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
782  case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
783  case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
784  case vmIntrinsics::_newArray:                 return inline_native_newArray();
785  case vmIntrinsics::_getLength:                return inline_native_getLength();
786  case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
787  case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
788  case vmIntrinsics::_equalsC:                  return inline_array_equals();
789  case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
790
791  case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
792
793  case vmIntrinsics::_isInstance:
794  case vmIntrinsics::_getModifiers:
795  case vmIntrinsics::_isInterface:
796  case vmIntrinsics::_isArray:
797  case vmIntrinsics::_isPrimitive:
798  case vmIntrinsics::_getSuperclass:
799  case vmIntrinsics::_getComponentType:
800  case vmIntrinsics::_getClassAccessFlags:      return inline_native_Class_query(intrinsic_id());
801
802  case vmIntrinsics::_floatToRawIntBits:
803  case vmIntrinsics::_floatToIntBits:
804  case vmIntrinsics::_intBitsToFloat:
805  case vmIntrinsics::_doubleToRawLongBits:
806  case vmIntrinsics::_doubleToLongBits:
807  case vmIntrinsics::_longBitsToDouble:         return inline_fp_conversions(intrinsic_id());
808
809  case vmIntrinsics::_numberOfLeadingZeros_i:
810  case vmIntrinsics::_numberOfLeadingZeros_l:
811  case vmIntrinsics::_numberOfTrailingZeros_i:
812  case vmIntrinsics::_numberOfTrailingZeros_l:
813  case vmIntrinsics::_bitCount_i:
814  case vmIntrinsics::_bitCount_l:
815  case vmIntrinsics::_reverseBytes_i:
816  case vmIntrinsics::_reverseBytes_l:
817  case vmIntrinsics::_reverseBytes_s:
818  case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
819
820  case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
821
822  case vmIntrinsics::_Reference_get:            return inline_reference_get();
823
824  case vmIntrinsics::_aescrypt_encryptBlock:
825  case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
826
827  case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
828  case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
829    return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
830
831  case vmIntrinsics::_encodeISOArray:
832    return inline_encodeISOArray();
833
834  case vmIntrinsics::_updateCRC32:
835    return inline_updateCRC32();
836  case vmIntrinsics::_updateBytesCRC32:
837    return inline_updateBytesCRC32();
838  case vmIntrinsics::_updateByteBufferCRC32:
839    return inline_updateByteBufferCRC32();
840
841  default:
842    // If you get here, it may be that someone has added a new intrinsic
843    // to the list in vmSymbols.hpp without implementing it here.
844#ifndef PRODUCT
845    if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
846      tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
847                    vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
848    }
849#endif
850    return false;
851  }
852}
853
854Node* LibraryCallKit::try_to_predicate() {
855  if (!jvms()->has_method()) {
856    // Root JVMState has a null method.
857    assert(map()->memory()->Opcode() == Op_Parm, "");
858    // Insert the memory aliasing node
859    set_all_memory(reset_memory());
860  }
861  assert(merged_memory(), "");
862
863  switch (intrinsic_id()) {
864  case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
865    return inline_cipherBlockChaining_AESCrypt_predicate(false);
866  case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
867    return inline_cipherBlockChaining_AESCrypt_predicate(true);
868
869  default:
870    // If you get here, it may be that someone has added a new intrinsic
871    // to the list in vmSymbols.hpp without implementing it here.
872#ifndef PRODUCT
873    if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
874      tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
875                    vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
876    }
877#endif
878    Node* slow_ctl = control();
879    set_control(top()); // No fast path instrinsic
880    return slow_ctl;
881  }
882}
883
884//------------------------------set_result-------------------------------
885// Helper function for finishing intrinsics.
886void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
887  record_for_igvn(region);
888  set_control(_gvn.transform(region));
889  set_result( _gvn.transform(value));
890  assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
891}
892
893//------------------------------generate_guard---------------------------
894// Helper function for generating guarded fast-slow graph structures.
895// The given 'test', if true, guards a slow path.  If the test fails
896// then a fast path can be taken.  (We generally hope it fails.)
897// In all cases, GraphKit::control() is updated to the fast path.
898// The returned value represents the control for the slow path.
899// The return value is never 'top'; it is either a valid control
900// or NULL if it is obvious that the slow path can never be taken.
901// Also, if region and the slow control are not NULL, the slow edge
902// is appended to the region.
903Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
904  if (stopped()) {
905    // Already short circuited.
906    return NULL;
907  }
908
909  // Build an if node and its projections.
910  // If test is true we take the slow path, which we assume is uncommon.
911  if (_gvn.type(test) == TypeInt::ZERO) {
912    // The slow branch is never taken.  No need to build this guard.
913    return NULL;
914  }
915
916  IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
917
918  Node* if_slow = _gvn.transform(new (C) IfTrueNode(iff));
919  if (if_slow == top()) {
920    // The slow branch is never taken.  No need to build this guard.
921    return NULL;
922  }
923
924  if (region != NULL)
925    region->add_req(if_slow);
926
927  Node* if_fast = _gvn.transform(new (C) IfFalseNode(iff));
928  set_control(if_fast);
929
930  return if_slow;
931}
932
933inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
934  return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
935}
936inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
937  return generate_guard(test, region, PROB_FAIR);
938}
939
940inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
941                                                     Node* *pos_index) {
942  if (stopped())
943    return NULL;                // already stopped
944  if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
945    return NULL;                // index is already adequately typed
946  Node* cmp_lt = _gvn.transform(new (C) CmpINode(index, intcon(0)));
947  Node* bol_lt = _gvn.transform(new (C) BoolNode(cmp_lt, BoolTest::lt));
948  Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
949  if (is_neg != NULL && pos_index != NULL) {
950    // Emulate effect of Parse::adjust_map_after_if.
951    Node* ccast = new (C) CastIINode(index, TypeInt::POS);
952    ccast->set_req(0, control());
953    (*pos_index) = _gvn.transform(ccast);
954  }
955  return is_neg;
956}
957
958inline Node* LibraryCallKit::generate_nonpositive_guard(Node* index, bool never_negative,
959                                                        Node* *pos_index) {
960  if (stopped())
961    return NULL;                // already stopped
962  if (_gvn.type(index)->higher_equal(TypeInt::POS1)) // [1,maxint]
963    return NULL;                // index is already adequately typed
964  Node* cmp_le = _gvn.transform(new (C) CmpINode(index, intcon(0)));
965  BoolTest::mask le_or_eq = (never_negative ? BoolTest::eq : BoolTest::le);
966  Node* bol_le = _gvn.transform(new (C) BoolNode(cmp_le, le_or_eq));
967  Node* is_notp = generate_guard(bol_le, NULL, PROB_MIN);
968  if (is_notp != NULL && pos_index != NULL) {
969    // Emulate effect of Parse::adjust_map_after_if.
970    Node* ccast = new (C) CastIINode(index, TypeInt::POS1);
971    ccast->set_req(0, control());
972    (*pos_index) = _gvn.transform(ccast);
973  }
974  return is_notp;
975}
976
977// Make sure that 'position' is a valid limit index, in [0..length].
978// There are two equivalent plans for checking this:
979//   A. (offset + copyLength)  unsigned<=  arrayLength
980//   B. offset  <=  (arrayLength - copyLength)
981// We require that all of the values above, except for the sum and
982// difference, are already known to be non-negative.
983// Plan A is robust in the face of overflow, if offset and copyLength
984// are both hugely positive.
985//
986// Plan B is less direct and intuitive, but it does not overflow at
987// all, since the difference of two non-negatives is always
988// representable.  Whenever Java methods must perform the equivalent
989// check they generally use Plan B instead of Plan A.
990// For the moment we use Plan A.
991inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
992                                                  Node* subseq_length,
993                                                  Node* array_length,
994                                                  RegionNode* region) {
995  if (stopped())
996    return NULL;                // already stopped
997  bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
998  if (zero_offset && subseq_length->eqv_uncast(array_length))
999    return NULL;                // common case of whole-array copy
1000  Node* last = subseq_length;
1001  if (!zero_offset)             // last += offset
1002    last = _gvn.transform(new (C) AddINode(last, offset));
1003  Node* cmp_lt = _gvn.transform(new (C) CmpUNode(array_length, last));
1004  Node* bol_lt = _gvn.transform(new (C) BoolNode(cmp_lt, BoolTest::lt));
1005  Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
1006  return is_over;
1007}
1008
1009
1010//--------------------------generate_current_thread--------------------
1011Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1012  ciKlass*    thread_klass = env()->Thread_klass();
1013  const Type* thread_type  = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1014  Node* thread = _gvn.transform(new (C) ThreadLocalNode());
1015  Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::threadObj_offset()));
1016  Node* threadObj = make_load(NULL, p, thread_type, T_OBJECT);
1017  tls_output = thread;
1018  return threadObj;
1019}
1020
1021
1022//------------------------------make_string_method_node------------------------
1023// Helper method for String intrinsic functions. This version is called
1024// with str1 and str2 pointing to String object nodes.
1025//
1026Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1, Node* str2) {
1027  Node* no_ctrl = NULL;
1028
1029  // Get start addr of string
1030  Node* str1_value   = load_String_value(no_ctrl, str1);
1031  Node* str1_offset  = load_String_offset(no_ctrl, str1);
1032  Node* str1_start   = array_element_address(str1_value, str1_offset, T_CHAR);
1033
1034  // Get length of string 1
1035  Node* str1_len  = load_String_length(no_ctrl, str1);
1036
1037  Node* str2_value   = load_String_value(no_ctrl, str2);
1038  Node* str2_offset  = load_String_offset(no_ctrl, str2);
1039  Node* str2_start   = array_element_address(str2_value, str2_offset, T_CHAR);
1040
1041  Node* str2_len = NULL;
1042  Node* result = NULL;
1043
1044  switch (opcode) {
1045  case Op_StrIndexOf:
1046    // Get length of string 2
1047    str2_len = load_String_length(no_ctrl, str2);
1048
1049    result = new (C) StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),
1050                                 str1_start, str1_len, str2_start, str2_len);
1051    break;
1052  case Op_StrComp:
1053    // Get length of string 2
1054    str2_len = load_String_length(no_ctrl, str2);
1055
1056    result = new (C) StrCompNode(control(), memory(TypeAryPtr::CHARS),
1057                                 str1_start, str1_len, str2_start, str2_len);
1058    break;
1059  case Op_StrEquals:
1060    result = new (C) StrEqualsNode(control(), memory(TypeAryPtr::CHARS),
1061                               str1_start, str2_start, str1_len);
1062    break;
1063  default:
1064    ShouldNotReachHere();
1065    return NULL;
1066  }
1067
1068  // All these intrinsics have checks.
1069  C->set_has_split_ifs(true); // Has chance for split-if optimization
1070
1071  return _gvn.transform(result);
1072}
1073
1074// Helper method for String intrinsic functions. This version is called
1075// with str1 and str2 pointing to char[] nodes, with cnt1 and cnt2 pointing
1076// to Int nodes containing the lenghts of str1 and str2.
1077//
1078Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2) {
1079  Node* result = NULL;
1080  switch (opcode) {
1081  case Op_StrIndexOf:
1082    result = new (C) StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),
1083                                 str1_start, cnt1, str2_start, cnt2);
1084    break;
1085  case Op_StrComp:
1086    result = new (C) StrCompNode(control(), memory(TypeAryPtr::CHARS),
1087                                 str1_start, cnt1, str2_start, cnt2);
1088    break;
1089  case Op_StrEquals:
1090    result = new (C) StrEqualsNode(control(), memory(TypeAryPtr::CHARS),
1091                                 str1_start, str2_start, cnt1);
1092    break;
1093  default:
1094    ShouldNotReachHere();
1095    return NULL;
1096  }
1097
1098  // All these intrinsics have checks.
1099  C->set_has_split_ifs(true); // Has chance for split-if optimization
1100
1101  return _gvn.transform(result);
1102}
1103
1104//------------------------------inline_string_compareTo------------------------
1105// public int java.lang.String.compareTo(String anotherString);
1106bool LibraryCallKit::inline_string_compareTo() {
1107  Node* receiver = null_check(argument(0));
1108  Node* arg      = null_check(argument(1));
1109  if (stopped()) {
1110    return true;
1111  }
1112  set_result(make_string_method_node(Op_StrComp, receiver, arg));
1113  return true;
1114}
1115
1116//------------------------------inline_string_equals------------------------
1117bool LibraryCallKit::inline_string_equals() {
1118  Node* receiver = null_check_receiver();
1119  // NOTE: Do not null check argument for String.equals() because spec
1120  // allows to specify NULL as argument.
1121  Node* argument = this->argument(1);
1122  if (stopped()) {
1123    return true;
1124  }
1125
1126  // paths (plus control) merge
1127  RegionNode* region = new (C) RegionNode(5);
1128  Node* phi = new (C) PhiNode(region, TypeInt::BOOL);
1129
1130  // does source == target string?
1131  Node* cmp = _gvn.transform(new (C) CmpPNode(receiver, argument));
1132  Node* bol = _gvn.transform(new (C) BoolNode(cmp, BoolTest::eq));
1133
1134  Node* if_eq = generate_slow_guard(bol, NULL);
1135  if (if_eq != NULL) {
1136    // receiver == argument
1137    phi->init_req(2, intcon(1));
1138    region->init_req(2, if_eq);
1139  }
1140
1141  // get String klass for instanceOf
1142  ciInstanceKlass* klass = env()->String_klass();
1143
1144  if (!stopped()) {
1145    Node* inst = gen_instanceof(argument, makecon(TypeKlassPtr::make(klass)));
1146    Node* cmp  = _gvn.transform(new (C) CmpINode(inst, intcon(1)));
1147    Node* bol  = _gvn.transform(new (C) BoolNode(cmp, BoolTest::ne));
1148
1149    Node* inst_false = generate_guard(bol, NULL, PROB_MIN);
1150    //instanceOf == true, fallthrough
1151
1152    if (inst_false != NULL) {
1153      phi->init_req(3, intcon(0));
1154      region->init_req(3, inst_false);
1155    }
1156  }
1157
1158  if (!stopped()) {
1159    const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
1160
1161    // Properly cast the argument to String
1162    argument = _gvn.transform(new (C) CheckCastPPNode(control(), argument, string_type));
1163    // This path is taken only when argument's type is String:NotNull.
1164    argument = cast_not_null(argument, false);
1165
1166    Node* no_ctrl = NULL;
1167
1168    // Get start addr of receiver
1169    Node* receiver_val    = load_String_value(no_ctrl, receiver);
1170    Node* receiver_offset = load_String_offset(no_ctrl, receiver);
1171    Node* receiver_start = array_element_address(receiver_val, receiver_offset, T_CHAR);
1172
1173    // Get length of receiver
1174    Node* receiver_cnt  = load_String_length(no_ctrl, receiver);
1175
1176    // Get start addr of argument
1177    Node* argument_val    = load_String_value(no_ctrl, argument);
1178    Node* argument_offset = load_String_offset(no_ctrl, argument);
1179    Node* argument_start = array_element_address(argument_val, argument_offset, T_CHAR);
1180
1181    // Get length of argument
1182    Node* argument_cnt  = load_String_length(no_ctrl, argument);
1183
1184    // Check for receiver count != argument count
1185    Node* cmp = _gvn.transform(new(C) CmpINode(receiver_cnt, argument_cnt));
1186    Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::ne));
1187    Node* if_ne = generate_slow_guard(bol, NULL);
1188    if (if_ne != NULL) {
1189      phi->init_req(4, intcon(0));
1190      region->init_req(4, if_ne);
1191    }
1192
1193    // Check for count == 0 is done by assembler code for StrEquals.
1194
1195    if (!stopped()) {
1196      Node* equals = make_string_method_node(Op_StrEquals, receiver_start, receiver_cnt, argument_start, argument_cnt);
1197      phi->init_req(1, equals);
1198      region->init_req(1, control());
1199    }
1200  }
1201
1202  // post merge
1203  set_control(_gvn.transform(region));
1204  record_for_igvn(region);
1205
1206  set_result(_gvn.transform(phi));
1207  return true;
1208}
1209
1210//------------------------------inline_array_equals----------------------------
1211bool LibraryCallKit::inline_array_equals() {
1212  Node* arg1 = argument(0);
1213  Node* arg2 = argument(1);
1214  set_result(_gvn.transform(new (C) AryEqNode(control(), memory(TypeAryPtr::CHARS), arg1, arg2)));
1215  return true;
1216}
1217
1218// Java version of String.indexOf(constant string)
1219// class StringDecl {
1220//   StringDecl(char[] ca) {
1221//     offset = 0;
1222//     count = ca.length;
1223//     value = ca;
1224//   }
1225//   int offset;
1226//   int count;
1227//   char[] value;
1228// }
1229//
1230// static int string_indexOf_J(StringDecl string_object, char[] target_object,
1231//                             int targetOffset, int cache_i, int md2) {
1232//   int cache = cache_i;
1233//   int sourceOffset = string_object.offset;
1234//   int sourceCount = string_object.count;
1235//   int targetCount = target_object.length;
1236//
1237//   int targetCountLess1 = targetCount - 1;
1238//   int sourceEnd = sourceOffset + sourceCount - targetCountLess1;
1239//
1240//   char[] source = string_object.value;
1241//   char[] target = target_object;
1242//   int lastChar = target[targetCountLess1];
1243//
1244//  outer_loop:
1245//   for (int i = sourceOffset; i < sourceEnd; ) {
1246//     int src = source[i + targetCountLess1];
1247//     if (src == lastChar) {
1248//       // With random strings and a 4-character alphabet,
1249//       // reverse matching at this point sets up 0.8% fewer
1250//       // frames, but (paradoxically) makes 0.3% more probes.
1251//       // Since those probes are nearer the lastChar probe,
1252//       // there is may be a net D$ win with reverse matching.
1253//       // But, reversing loop inhibits unroll of inner loop
1254//       // for unknown reason.  So, does running outer loop from
1255//       // (sourceOffset - targetCountLess1) to (sourceOffset + sourceCount)
1256//       for (int j = 0; j < targetCountLess1; j++) {
1257//         if (target[targetOffset + j] != source[i+j]) {
1258//           if ((cache & (1 << source[i+j])) == 0) {
1259//             if (md2 < j+1) {
1260//               i += j+1;
1261//               continue outer_loop;
1262//             }
1263//           }
1264//           i += md2;
1265//           continue outer_loop;
1266//         }
1267//       }
1268//       return i - sourceOffset;
1269//     }
1270//     if ((cache & (1 << src)) == 0) {
1271//       i += targetCountLess1;
1272//     } // using "i += targetCount;" and an "else i++;" causes a jump to jump.
1273//     i++;
1274//   }
1275//   return -1;
1276// }
1277
1278//------------------------------string_indexOf------------------------
1279Node* LibraryCallKit::string_indexOf(Node* string_object, ciTypeArray* target_array, jint targetOffset_i,
1280                                     jint cache_i, jint md2_i) {
1281
1282  Node* no_ctrl  = NULL;
1283  float likely   = PROB_LIKELY(0.9);
1284  float unlikely = PROB_UNLIKELY(0.9);
1285
1286  const int nargs = 0; // no arguments to push back for uncommon trap in predicate
1287
1288  Node* source        = load_String_value(no_ctrl, string_object);
1289  Node* sourceOffset  = load_String_offset(no_ctrl, string_object);
1290  Node* sourceCount   = load_String_length(no_ctrl, string_object);
1291
1292  Node* target = _gvn.transform( makecon(TypeOopPtr::make_from_constant(target_array, true)));
1293  jint target_length = target_array->length();
1294  const TypeAry* target_array_type = TypeAry::make(TypeInt::CHAR, TypeInt::make(0, target_length, Type::WidenMin));
1295  const TypeAryPtr* target_type = TypeAryPtr::make(TypePtr::BotPTR, target_array_type, target_array->klass(), true, Type::OffsetBot);
1296
1297  // String.value field is known to be @Stable.
1298  if (UseImplicitStableValues) {
1299    target = cast_array_to_stable(target, target_type);
1300  }
1301
1302  IdealKit kit(this, false, true);
1303#define __ kit.
1304  Node* zero             = __ ConI(0);
1305  Node* one              = __ ConI(1);
1306  Node* cache            = __ ConI(cache_i);
1307  Node* md2              = __ ConI(md2_i);
1308  Node* lastChar         = __ ConI(target_array->char_at(target_length - 1));
1309  Node* targetCount      = __ ConI(target_length);
1310  Node* targetCountLess1 = __ ConI(target_length - 1);
1311  Node* targetOffset     = __ ConI(targetOffset_i);
1312  Node* sourceEnd        = __ SubI(__ AddI(sourceOffset, sourceCount), targetCountLess1);
1313
1314  IdealVariable rtn(kit), i(kit), j(kit); __ declarations_done();
1315  Node* outer_loop = __ make_label(2 /* goto */);
1316  Node* return_    = __ make_label(1);
1317
1318  __ set(rtn,__ ConI(-1));
1319  __ loop(this, nargs, i, sourceOffset, BoolTest::lt, sourceEnd); {
1320       Node* i2  = __ AddI(__ value(i), targetCountLess1);
1321       // pin to prohibit loading of "next iteration" value which may SEGV (rare)
1322       Node* src = load_array_element(__ ctrl(), source, i2, TypeAryPtr::CHARS);
1323       __ if_then(src, BoolTest::eq, lastChar, unlikely); {
1324         __ loop(this, nargs, j, zero, BoolTest::lt, targetCountLess1); {
1325              Node* tpj = __ AddI(targetOffset, __ value(j));
1326              Node* targ = load_array_element(no_ctrl, target, tpj, target_type);
1327              Node* ipj  = __ AddI(__ value(i), __ value(j));
1328              Node* src2 = load_array_element(no_ctrl, source, ipj, TypeAryPtr::CHARS);
1329              __ if_then(targ, BoolTest::ne, src2); {
1330                __ if_then(__ AndI(cache, __ LShiftI(one, src2)), BoolTest::eq, zero); {
1331                  __ if_then(md2, BoolTest::lt, __ AddI(__ value(j), one)); {
1332                    __ increment(i, __ AddI(__ value(j), one));
1333                    __ goto_(outer_loop);
1334                  } __ end_if(); __ dead(j);
1335                }__ end_if(); __ dead(j);
1336                __ increment(i, md2);
1337                __ goto_(outer_loop);
1338              }__ end_if();
1339              __ increment(j, one);
1340         }__ end_loop(); __ dead(j);
1341         __ set(rtn, __ SubI(__ value(i), sourceOffset)); __ dead(i);
1342         __ goto_(return_);
1343       }__ end_if();
1344       __ if_then(__ AndI(cache, __ LShiftI(one, src)), BoolTest::eq, zero, likely); {
1345         __ increment(i, targetCountLess1);
1346       }__ end_if();
1347       __ increment(i, one);
1348       __ bind(outer_loop);
1349  }__ end_loop(); __ dead(i);
1350  __ bind(return_);
1351
1352  // Final sync IdealKit and GraphKit.
1353  final_sync(kit);
1354  Node* result = __ value(rtn);
1355#undef __
1356  C->set_has_loops(true);
1357  return result;
1358}
1359
1360//------------------------------inline_string_indexOf------------------------
1361bool LibraryCallKit::inline_string_indexOf() {
1362  Node* receiver = argument(0);
1363  Node* arg      = argument(1);
1364
1365  Node* result;
1366  // Disable the use of pcmpestri until it can be guaranteed that
1367  // the load doesn't cross into the uncommited space.
1368  if (Matcher::has_match_rule(Op_StrIndexOf) &&
1369      UseSSE42Intrinsics) {
1370    // Generate SSE4.2 version of indexOf
1371    // We currently only have match rules that use SSE4.2
1372
1373    receiver = null_check(receiver);
1374    arg      = null_check(arg);
1375    if (stopped()) {
1376      return true;
1377    }
1378
1379    ciInstanceKlass* str_klass = env()->String_klass();
1380    const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(str_klass);
1381
1382    // Make the merge point
1383    RegionNode* result_rgn = new (C) RegionNode(4);
1384    Node*       result_phi = new (C) PhiNode(result_rgn, TypeInt::INT);
1385    Node* no_ctrl  = NULL;
1386
1387    // Get start addr of source string
1388    Node* source = load_String_value(no_ctrl, receiver);
1389    Node* source_offset = load_String_offset(no_ctrl, receiver);
1390    Node* source_start = array_element_address(source, source_offset, T_CHAR);
1391
1392    // Get length of source string
1393    Node* source_cnt  = load_String_length(no_ctrl, receiver);
1394
1395    // Get start addr of substring
1396    Node* substr = load_String_value(no_ctrl, arg);
1397    Node* substr_offset = load_String_offset(no_ctrl, arg);
1398    Node* substr_start = array_element_address(substr, substr_offset, T_CHAR);
1399
1400    // Get length of source string
1401    Node* substr_cnt  = load_String_length(no_ctrl, arg);
1402
1403    // Check for substr count > string count
1404    Node* cmp = _gvn.transform(new(C) CmpINode(substr_cnt, source_cnt));
1405    Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::gt));
1406    Node* if_gt = generate_slow_guard(bol, NULL);
1407    if (if_gt != NULL) {
1408      result_phi->init_req(2, intcon(-1));
1409      result_rgn->init_req(2, if_gt);
1410    }
1411
1412    if (!stopped()) {
1413      // Check for substr count == 0
1414      cmp = _gvn.transform(new(C) CmpINode(substr_cnt, intcon(0)));
1415      bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::eq));
1416      Node* if_zero = generate_slow_guard(bol, NULL);
1417      if (if_zero != NULL) {
1418        result_phi->init_req(3, intcon(0));
1419        result_rgn->init_req(3, if_zero);
1420      }
1421    }
1422
1423    if (!stopped()) {
1424      result = make_string_method_node(Op_StrIndexOf, source_start, source_cnt, substr_start, substr_cnt);
1425      result_phi->init_req(1, result);
1426      result_rgn->init_req(1, control());
1427    }
1428    set_control(_gvn.transform(result_rgn));
1429    record_for_igvn(result_rgn);
1430    result = _gvn.transform(result_phi);
1431
1432  } else { // Use LibraryCallKit::string_indexOf
1433    // don't intrinsify if argument isn't a constant string.
1434    if (!arg->is_Con()) {
1435     return false;
1436    }
1437    const TypeOopPtr* str_type = _gvn.type(arg)->isa_oopptr();
1438    if (str_type == NULL) {
1439      return false;
1440    }
1441    ciInstanceKlass* klass = env()->String_klass();
1442    ciObject* str_const = str_type->const_oop();
1443    if (str_const == NULL || str_const->klass() != klass) {
1444      return false;
1445    }
1446    ciInstance* str = str_const->as_instance();
1447    assert(str != NULL, "must be instance");
1448
1449    ciObject* v = str->field_value_by_offset(java_lang_String::value_offset_in_bytes()).as_object();
1450    ciTypeArray* pat = v->as_type_array(); // pattern (argument) character array
1451
1452    int o;
1453    int c;
1454    if (java_lang_String::has_offset_field()) {
1455      o = str->field_value_by_offset(java_lang_String::offset_offset_in_bytes()).as_int();
1456      c = str->field_value_by_offset(java_lang_String::count_offset_in_bytes()).as_int();
1457    } else {
1458      o = 0;
1459      c = pat->length();
1460    }
1461
1462    // constant strings have no offset and count == length which
1463    // simplifies the resulting code somewhat so lets optimize for that.
1464    if (o != 0 || c != pat->length()) {
1465     return false;
1466    }
1467
1468    receiver = null_check(receiver, T_OBJECT);
1469    // NOTE: No null check on the argument is needed since it's a constant String oop.
1470    if (stopped()) {
1471      return true;
1472    }
1473
1474    // The null string as a pattern always returns 0 (match at beginning of string)
1475    if (c == 0) {
1476      set_result(intcon(0));
1477      return true;
1478    }
1479
1480    // Generate default indexOf
1481    jchar lastChar = pat->char_at(o + (c - 1));
1482    int cache = 0;
1483    int i;
1484    for (i = 0; i < c - 1; i++) {
1485      assert(i < pat->length(), "out of range");
1486      cache |= (1 << (pat->char_at(o + i) & (sizeof(cache) * BitsPerByte - 1)));
1487    }
1488
1489    int md2 = c;
1490    for (i = 0; i < c - 1; i++) {
1491      assert(i < pat->length(), "out of range");
1492      if (pat->char_at(o + i) == lastChar) {
1493        md2 = (c - 1) - i;
1494      }
1495    }
1496
1497    result = string_indexOf(receiver, pat, o, cache, md2);
1498  }
1499  set_result(result);
1500  return true;
1501}
1502
1503//--------------------------round_double_node--------------------------------
1504// Round a double node if necessary.
1505Node* LibraryCallKit::round_double_node(Node* n) {
1506  if (Matcher::strict_fp_requires_explicit_rounding && UseSSE <= 1)
1507    n = _gvn.transform(new (C) RoundDoubleNode(0, n));
1508  return n;
1509}
1510
1511//------------------------------inline_math-----------------------------------
1512// public static double Math.abs(double)
1513// public static double Math.sqrt(double)
1514// public static double Math.log(double)
1515// public static double Math.log10(double)
1516bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1517  Node* arg = round_double_node(argument(0));
1518  Node* n;
1519  switch (id) {
1520  case vmIntrinsics::_dabs:   n = new (C) AbsDNode(                arg);  break;
1521  case vmIntrinsics::_dsqrt:  n = new (C) SqrtDNode(C, control(),  arg);  break;
1522  case vmIntrinsics::_dlog:   n = new (C) LogDNode(C, control(),   arg);  break;
1523  case vmIntrinsics::_dlog10: n = new (C) Log10DNode(C, control(), arg);  break;
1524  default:  fatal_unexpected_iid(id);  break;
1525  }
1526  set_result(_gvn.transform(n));
1527  return true;
1528}
1529
1530//------------------------------inline_trig----------------------------------
1531// Inline sin/cos/tan instructions, if possible.  If rounding is required, do
1532// argument reduction which will turn into a fast/slow diamond.
1533bool LibraryCallKit::inline_trig(vmIntrinsics::ID id) {
1534  Node* arg = round_double_node(argument(0));
1535  Node* n = NULL;
1536
1537  switch (id) {
1538  case vmIntrinsics::_dsin:  n = new (C) SinDNode(C, control(), arg);  break;
1539  case vmIntrinsics::_dcos:  n = new (C) CosDNode(C, control(), arg);  break;
1540  case vmIntrinsics::_dtan:  n = new (C) TanDNode(C, control(), arg);  break;
1541  default:  fatal_unexpected_iid(id);  break;
1542  }
1543  n = _gvn.transform(n);
1544
1545  // Rounding required?  Check for argument reduction!
1546  if (Matcher::strict_fp_requires_explicit_rounding) {
1547    static const double     pi_4 =  0.7853981633974483;
1548    static const double neg_pi_4 = -0.7853981633974483;
1549    // pi/2 in 80-bit extended precision
1550    // static const unsigned char pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0x3f,0x00,0x00,0x00,0x00,0x00,0x00};
1551    // -pi/2 in 80-bit extended precision
1552    // static const unsigned char neg_pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0xbf,0x00,0x00,0x00,0x00,0x00,0x00};
1553    // Cutoff value for using this argument reduction technique
1554    //static const double    pi_2_minus_epsilon =  1.564660403643354;
1555    //static const double neg_pi_2_plus_epsilon = -1.564660403643354;
1556
1557    // Pseudocode for sin:
1558    // if (x <= Math.PI / 4.0) {
1559    //   if (x >= -Math.PI / 4.0) return  fsin(x);
1560    //   if (x >= -Math.PI / 2.0) return -fcos(x + Math.PI / 2.0);
1561    // } else {
1562    //   if (x <=  Math.PI / 2.0) return  fcos(x - Math.PI / 2.0);
1563    // }
1564    // return StrictMath.sin(x);
1565
1566    // Pseudocode for cos:
1567    // if (x <= Math.PI / 4.0) {
1568    //   if (x >= -Math.PI / 4.0) return  fcos(x);
1569    //   if (x >= -Math.PI / 2.0) return  fsin(x + Math.PI / 2.0);
1570    // } else {
1571    //   if (x <=  Math.PI / 2.0) return -fsin(x - Math.PI / 2.0);
1572    // }
1573    // return StrictMath.cos(x);
1574
1575    // Actually, sticking in an 80-bit Intel value into C2 will be tough; it
1576    // requires a special machine instruction to load it.  Instead we'll try
1577    // the 'easy' case.  If we really need the extra range +/- PI/2 we'll
1578    // probably do the math inside the SIN encoding.
1579
1580    // Make the merge point
1581    RegionNode* r = new (C) RegionNode(3);
1582    Node* phi = new (C) PhiNode(r, Type::DOUBLE);
1583
1584    // Flatten arg so we need only 1 test
1585    Node *abs = _gvn.transform(new (C) AbsDNode(arg));
1586    // Node for PI/4 constant
1587    Node *pi4 = makecon(TypeD::make(pi_4));
1588    // Check PI/4 : abs(arg)
1589    Node *cmp = _gvn.transform(new (C) CmpDNode(pi4,abs));
1590    // Check: If PI/4 < abs(arg) then go slow
1591    Node *bol = _gvn.transform(new (C) BoolNode( cmp, BoolTest::lt ));
1592    // Branch either way
1593    IfNode *iff = create_and_xform_if(control(),bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
1594    set_control(opt_iff(r,iff));
1595
1596    // Set fast path result
1597    phi->init_req(2, n);
1598
1599    // Slow path - non-blocking leaf call
1600    Node* call = NULL;
1601    switch (id) {
1602    case vmIntrinsics::_dsin:
1603      call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1604                               CAST_FROM_FN_PTR(address, SharedRuntime::dsin),
1605                               "Sin", NULL, arg, top());
1606      break;
1607    case vmIntrinsics::_dcos:
1608      call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1609                               CAST_FROM_FN_PTR(address, SharedRuntime::dcos),
1610                               "Cos", NULL, arg, top());
1611      break;
1612    case vmIntrinsics::_dtan:
1613      call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1614                               CAST_FROM_FN_PTR(address, SharedRuntime::dtan),
1615                               "Tan", NULL, arg, top());
1616      break;
1617    }
1618    assert(control()->in(0) == call, "");
1619    Node* slow_result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
1620    r->init_req(1, control());
1621    phi->init_req(1, slow_result);
1622
1623    // Post-merge
1624    set_control(_gvn.transform(r));
1625    record_for_igvn(r);
1626    n = _gvn.transform(phi);
1627
1628    C->set_has_split_ifs(true); // Has chance for split-if optimization
1629  }
1630  set_result(n);
1631  return true;
1632}
1633
1634void LibraryCallKit::finish_pow_exp(Node* result, Node* x, Node* y, const TypeFunc* call_type, address funcAddr, const char* funcName) {
1635  //-------------------
1636  //result=(result.isNaN())? funcAddr():result;
1637  // Check: If isNaN() by checking result!=result? then either trap
1638  // or go to runtime
1639  Node* cmpisnan = _gvn.transform(new (C) CmpDNode(result, result));
1640  // Build the boolean node
1641  Node* bolisnum = _gvn.transform(new (C) BoolNode(cmpisnan, BoolTest::eq));
1642
1643  if (!too_many_traps(Deoptimization::Reason_intrinsic)) {
1644    { BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);
1645      // The pow or exp intrinsic returned a NaN, which requires a call
1646      // to the runtime.  Recompile with the runtime call.
1647      uncommon_trap(Deoptimization::Reason_intrinsic,
1648                    Deoptimization::Action_make_not_entrant);
1649    }
1650    set_result(result);
1651  } else {
1652    // If this inlining ever returned NaN in the past, we compile a call
1653    // to the runtime to properly handle corner cases
1654
1655    IfNode* iff = create_and_xform_if(control(), bolisnum, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
1656    Node* if_slow = _gvn.transform(new (C) IfFalseNode(iff));
1657    Node* if_fast = _gvn.transform(new (C) IfTrueNode(iff));
1658
1659    if (!if_slow->is_top()) {
1660      RegionNode* result_region = new (C) RegionNode(3);
1661      PhiNode*    result_val = new (C) PhiNode(result_region, Type::DOUBLE);
1662
1663      result_region->init_req(1, if_fast);
1664      result_val->init_req(1, result);
1665
1666      set_control(if_slow);
1667
1668      const TypePtr* no_memory_effects = NULL;
1669      Node* rt = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
1670                                   no_memory_effects,
1671                                   x, top(), y, y ? top() : NULL);
1672      Node* value = _gvn.transform(new (C) ProjNode(rt, TypeFunc::Parms+0));
1673#ifdef ASSERT
1674      Node* value_top = _gvn.transform(new (C) ProjNode(rt, TypeFunc::Parms+1));
1675      assert(value_top == top(), "second value must be top");
1676#endif
1677
1678      result_region->init_req(2, control());
1679      result_val->init_req(2, value);
1680      set_result(result_region, result_val);
1681    } else {
1682      set_result(result);
1683    }
1684  }
1685}
1686
1687//------------------------------inline_exp-------------------------------------
1688// Inline exp instructions, if possible.  The Intel hardware only misses
1689// really odd corner cases (+/- Infinity).  Just uncommon-trap them.
1690bool LibraryCallKit::inline_exp() {
1691  Node* arg = round_double_node(argument(0));
1692  Node* n   = _gvn.transform(new (C) ExpDNode(C, control(), arg));
1693
1694  finish_pow_exp(n, arg, NULL, OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
1695
1696  C->set_has_split_ifs(true); // Has chance for split-if optimization
1697  return true;
1698}
1699
1700//------------------------------inline_pow-------------------------------------
1701// Inline power instructions, if possible.
1702bool LibraryCallKit::inline_pow() {
1703  // Pseudocode for pow
1704  // if (x <= 0.0) {
1705  //   long longy = (long)y;
1706  //   if ((double)longy == y) { // if y is long
1707  //     if (y + 1 == y) longy = 0; // huge number: even
1708  //     result = ((1&longy) == 0)?-DPow(abs(x), y):DPow(abs(x), y);
1709  //   } else {
1710  //     result = NaN;
1711  //   }
1712  // } else {
1713  //   result = DPow(x,y);
1714  // }
1715  // if (result != result)?  {
1716  //   result = uncommon_trap() or runtime_call();
1717  // }
1718  // return result;
1719
1720  Node* x = round_double_node(argument(0));
1721  Node* y = round_double_node(argument(2));
1722
1723  Node* result = NULL;
1724
1725  if (!too_many_traps(Deoptimization::Reason_intrinsic)) {
1726    // Short form: skip the fancy tests and just check for NaN result.
1727    result = _gvn.transform(new (C) PowDNode(C, control(), x, y));
1728  } else {
1729    // If this inlining ever returned NaN in the past, include all
1730    // checks + call to the runtime.
1731
1732    // Set the merge point for If node with condition of (x <= 0.0)
1733    // There are four possible paths to region node and phi node
1734    RegionNode *r = new (C) RegionNode(4);
1735    Node *phi = new (C) PhiNode(r, Type::DOUBLE);
1736
1737    // Build the first if node: if (x <= 0.0)
1738    // Node for 0 constant
1739    Node *zeronode = makecon(TypeD::ZERO);
1740    // Check x:0
1741    Node *cmp = _gvn.transform(new (C) CmpDNode(x, zeronode));
1742    // Check: If (x<=0) then go complex path
1743    Node *bol1 = _gvn.transform(new (C) BoolNode( cmp, BoolTest::le ));
1744    // Branch either way
1745    IfNode *if1 = create_and_xform_if(control(),bol1, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1746    // Fast path taken; set region slot 3
1747    Node *fast_taken = _gvn.transform(new (C) IfFalseNode(if1));
1748    r->init_req(3,fast_taken); // Capture fast-control
1749
1750    // Fast path not-taken, i.e. slow path
1751    Node *complex_path = _gvn.transform(new (C) IfTrueNode(if1));
1752
1753    // Set fast path result
1754    Node *fast_result = _gvn.transform(new (C) PowDNode(C, control(), x, y));
1755    phi->init_req(3, fast_result);
1756
1757    // Complex path
1758    // Build the second if node (if y is long)
1759    // Node for (long)y
1760    Node *longy = _gvn.transform(new (C) ConvD2LNode(y));
1761    // Node for (double)((long) y)
1762    Node *doublelongy= _gvn.transform(new (C) ConvL2DNode(longy));
1763    // Check (double)((long) y) : y
1764    Node *cmplongy= _gvn.transform(new (C) CmpDNode(doublelongy, y));
1765    // Check if (y isn't long) then go to slow path
1766
1767    Node *bol2 = _gvn.transform(new (C) BoolNode( cmplongy, BoolTest::ne ));
1768    // Branch either way
1769    IfNode *if2 = create_and_xform_if(complex_path,bol2, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1770    Node* ylong_path = _gvn.transform(new (C) IfFalseNode(if2));
1771
1772    Node *slow_path = _gvn.transform(new (C) IfTrueNode(if2));
1773
1774    // Calculate DPow(abs(x), y)*(1 & (long)y)
1775    // Node for constant 1
1776    Node *conone = longcon(1);
1777    // 1& (long)y
1778    Node *signnode= _gvn.transform(new (C) AndLNode(conone, longy));
1779
1780    // A huge number is always even. Detect a huge number by checking
1781    // if y + 1 == y and set integer to be tested for parity to 0.
1782    // Required for corner case:
1783    // (long)9.223372036854776E18 = max_jlong
1784    // (double)(long)9.223372036854776E18 = 9.223372036854776E18
1785    // max_jlong is odd but 9.223372036854776E18 is even
1786    Node* yplus1 = _gvn.transform(new (C) AddDNode(y, makecon(TypeD::make(1))));
1787    Node *cmpyplus1= _gvn.transform(new (C) CmpDNode(yplus1, y));
1788    Node *bolyplus1 = _gvn.transform(new (C) BoolNode( cmpyplus1, BoolTest::eq ));
1789    Node* correctedsign = NULL;
1790    if (ConditionalMoveLimit != 0) {
1791      correctedsign = _gvn.transform( CMoveNode::make(C, NULL, bolyplus1, signnode, longcon(0), TypeLong::LONG));
1792    } else {
1793      IfNode *ifyplus1 = create_and_xform_if(ylong_path,bolyplus1, PROB_FAIR, COUNT_UNKNOWN);
1794      RegionNode *r = new (C) RegionNode(3);
1795      Node *phi = new (C) PhiNode(r, TypeLong::LONG);
1796      r->init_req(1, _gvn.transform(new (C) IfFalseNode(ifyplus1)));
1797      r->init_req(2, _gvn.transform(new (C) IfTrueNode(ifyplus1)));
1798      phi->init_req(1, signnode);
1799      phi->init_req(2, longcon(0));
1800      correctedsign = _gvn.transform(phi);
1801      ylong_path = _gvn.transform(r);
1802      record_for_igvn(r);
1803    }
1804
1805    // zero node
1806    Node *conzero = longcon(0);
1807    // Check (1&(long)y)==0?
1808    Node *cmpeq1 = _gvn.transform(new (C) CmpLNode(correctedsign, conzero));
1809    // Check if (1&(long)y)!=0?, if so the result is negative
1810    Node *bol3 = _gvn.transform(new (C) BoolNode( cmpeq1, BoolTest::ne ));
1811    // abs(x)
1812    Node *absx=_gvn.transform(new (C) AbsDNode(x));
1813    // abs(x)^y
1814    Node *absxpowy = _gvn.transform(new (C) PowDNode(C, control(), absx, y));
1815    // -abs(x)^y
1816    Node *negabsxpowy = _gvn.transform(new (C) NegDNode (absxpowy));
1817    // (1&(long)y)==1?-DPow(abs(x), y):DPow(abs(x), y)
1818    Node *signresult = NULL;
1819    if (ConditionalMoveLimit != 0) {
1820      signresult = _gvn.transform( CMoveNode::make(C, NULL, bol3, absxpowy, negabsxpowy, Type::DOUBLE));
1821    } else {
1822      IfNode *ifyeven = create_and_xform_if(ylong_path,bol3, PROB_FAIR, COUNT_UNKNOWN);
1823      RegionNode *r = new (C) RegionNode(3);
1824      Node *phi = new (C) PhiNode(r, Type::DOUBLE);
1825      r->init_req(1, _gvn.transform(new (C) IfFalseNode(ifyeven)));
1826      r->init_req(2, _gvn.transform(new (C) IfTrueNode(ifyeven)));
1827      phi->init_req(1, absxpowy);
1828      phi->init_req(2, negabsxpowy);
1829      signresult = _gvn.transform(phi);
1830      ylong_path = _gvn.transform(r);
1831      record_for_igvn(r);
1832    }
1833    // Set complex path fast result
1834    r->init_req(2, ylong_path);
1835    phi->init_req(2, signresult);
1836
1837    static const jlong nan_bits = CONST64(0x7ff8000000000000);
1838    Node *slow_result = makecon(TypeD::make(*(double*)&nan_bits)); // return NaN
1839    r->init_req(1,slow_path);
1840    phi->init_req(1,slow_result);
1841
1842    // Post merge
1843    set_control(_gvn.transform(r));
1844    record_for_igvn(r);
1845    result = _gvn.transform(phi);
1846  }
1847
1848  finish_pow_exp(result, x, y, OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow), "POW");
1849
1850  C->set_has_split_ifs(true); // Has chance for split-if optimization
1851  return true;
1852}
1853
1854//------------------------------runtime_math-----------------------------
1855bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1856  assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1857         "must be (DD)D or (D)D type");
1858
1859  // Inputs
1860  Node* a = round_double_node(argument(0));
1861  Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? round_double_node(argument(2)) : NULL;
1862
1863  const TypePtr* no_memory_effects = NULL;
1864  Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
1865                                 no_memory_effects,
1866                                 a, top(), b, b ? top() : NULL);
1867  Node* value = _gvn.transform(new (C) ProjNode(trig, TypeFunc::Parms+0));
1868#ifdef ASSERT
1869  Node* value_top = _gvn.transform(new (C) ProjNode(trig, TypeFunc::Parms+1));
1870  assert(value_top == top(), "second value must be top");
1871#endif
1872
1873  set_result(value);
1874  return true;
1875}
1876
1877//------------------------------inline_math_native-----------------------------
1878bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1879#define FN_PTR(f) CAST_FROM_FN_PTR(address, f)
1880  switch (id) {
1881    // These intrinsics are not properly supported on all hardware
1882  case vmIntrinsics::_dcos:   return Matcher::has_match_rule(Op_CosD)   ? inline_trig(id) :
1883    runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dcos),   "COS");
1884  case vmIntrinsics::_dsin:   return Matcher::has_match_rule(Op_SinD)   ? inline_trig(id) :
1885    runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dsin),   "SIN");
1886  case vmIntrinsics::_dtan:   return Matcher::has_match_rule(Op_TanD)   ? inline_trig(id) :
1887    runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dtan),   "TAN");
1888
1889  case vmIntrinsics::_dlog:   return Matcher::has_match_rule(Op_LogD)   ? inline_math(id) :
1890    runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog),   "LOG");
1891  case vmIntrinsics::_dlog10: return Matcher::has_match_rule(Op_Log10D) ? inline_math(id) :
1892    runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog10), "LOG10");
1893
1894    // These intrinsics are supported on all hardware
1895  case vmIntrinsics::_dsqrt:  return Matcher::has_match_rule(Op_SqrtD)  ? inline_math(id) : false;
1896  case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_math(id) : false;
1897
1898  case vmIntrinsics::_dexp:   return Matcher::has_match_rule(Op_ExpD)   ? inline_exp()    :
1899    runtime_math(OptoRuntime::Math_D_D_Type(),  FN_PTR(SharedRuntime::dexp),  "EXP");
1900  case vmIntrinsics::_dpow:   return Matcher::has_match_rule(Op_PowD)   ? inline_pow()    :
1901    runtime_math(OptoRuntime::Math_DD_D_Type(), FN_PTR(SharedRuntime::dpow),  "POW");
1902#undef FN_PTR
1903
1904   // These intrinsics are not yet correctly implemented
1905  case vmIntrinsics::_datan2:
1906    return false;
1907
1908  default:
1909    fatal_unexpected_iid(id);
1910    return false;
1911  }
1912}
1913
1914static bool is_simple_name(Node* n) {
1915  return (n->req() == 1         // constant
1916          || (n->is_Type() && n->as_Type()->type()->singleton())
1917          || n->is_Proj()       // parameter or return value
1918          || n->is_Phi()        // local of some sort
1919          );
1920}
1921
1922//----------------------------inline_min_max-----------------------------------
1923bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1924  set_result(generate_min_max(id, argument(0), argument(1)));
1925  return true;
1926}
1927
1928bool LibraryCallKit::inline_math_mathExact(Node* math) {
1929  Node* result = _gvn.transform( new(C) ProjNode(math, MathExactNode::result_proj_node));
1930  Node* flags = _gvn.transform( new(C) FlagsProjNode(math, MathExactNode::flags_proj_node));
1931
1932  Node* bol = _gvn.transform( new (C) BoolNode(flags, BoolTest::overflow) );
1933  IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
1934  Node* fast_path = _gvn.transform( new (C) IfFalseNode(check));
1935  Node* slow_path = _gvn.transform( new (C) IfTrueNode(check) );
1936
1937  {
1938    PreserveJVMState pjvms(this);
1939    PreserveReexecuteState preexecs(this);
1940    jvms()->set_should_reexecute(true);
1941
1942    set_control(slow_path);
1943    set_i_o(i_o());
1944
1945    uncommon_trap(Deoptimization::Reason_intrinsic,
1946                  Deoptimization::Action_none);
1947  }
1948
1949  set_control(fast_path);
1950  set_result(result);
1951  return true;
1952}
1953
1954bool LibraryCallKit::inline_math_addExact() {
1955  Node* arg1 = argument(0);
1956  Node* arg2 = argument(1);
1957
1958  Node* add = _gvn.transform( new(C) AddExactINode(NULL, arg1, arg2) );
1959  if (add->Opcode() == Op_AddExactI) {
1960    return inline_math_mathExact(add);
1961  } else {
1962    set_result(add);
1963  }
1964  return true;
1965}
1966
1967Node*
1968LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {
1969  // These are the candidate return value:
1970  Node* xvalue = x0;
1971  Node* yvalue = y0;
1972
1973  if (xvalue == yvalue) {
1974    return xvalue;
1975  }
1976
1977  bool want_max = (id == vmIntrinsics::_max);
1978
1979  const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();
1980  const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();
1981  if (txvalue == NULL || tyvalue == NULL)  return top();
1982  // This is not really necessary, but it is consistent with a
1983  // hypothetical MaxINode::Value method:
1984  int widen = MAX2(txvalue->_widen, tyvalue->_widen);
1985
1986  // %%% This folding logic should (ideally) be in a different place.
1987  // Some should be inside IfNode, and there to be a more reliable
1988  // transformation of ?: style patterns into cmoves.  We also want
1989  // more powerful optimizations around cmove and min/max.
1990
1991  // Try to find a dominating comparison of these guys.
1992  // It can simplify the index computation for Arrays.copyOf
1993  // and similar uses of System.arraycopy.
1994  // First, compute the normalized version of CmpI(x, y).
1995  int   cmp_op = Op_CmpI;
1996  Node* xkey = xvalue;
1997  Node* ykey = yvalue;
1998  Node* ideal_cmpxy = _gvn.transform(new(C) CmpINode(xkey, ykey));
1999  if (ideal_cmpxy->is_Cmp()) {
2000    // E.g., if we have CmpI(length - offset, count),
2001    // it might idealize to CmpI(length, count + offset)
2002    cmp_op = ideal_cmpxy->Opcode();
2003    xkey = ideal_cmpxy->in(1);
2004    ykey = ideal_cmpxy->in(2);
2005  }
2006
2007  // Start by locating any relevant comparisons.
2008  Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;
2009  Node* cmpxy = NULL;
2010  Node* cmpyx = NULL;
2011  for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {
2012    Node* cmp = start_from->fast_out(k);
2013    if (cmp->outcnt() > 0 &&            // must have prior uses
2014        cmp->in(0) == NULL &&           // must be context-independent
2015        cmp->Opcode() == cmp_op) {      // right kind of compare
2016      if (cmp->in(1) == xkey && cmp->in(2) == ykey)  cmpxy = cmp;
2017      if (cmp->in(1) == ykey && cmp->in(2) == xkey)  cmpyx = cmp;
2018    }
2019  }
2020
2021  const int NCMPS = 2;
2022  Node* cmps[NCMPS] = { cmpxy, cmpyx };
2023  int cmpn;
2024  for (cmpn = 0; cmpn < NCMPS; cmpn++) {
2025    if (cmps[cmpn] != NULL)  break;     // find a result
2026  }
2027  if (cmpn < NCMPS) {
2028    // Look for a dominating test that tells us the min and max.
2029    int depth = 0;                // Limit search depth for speed
2030    Node* dom = control();
2031    for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {
2032      if (++depth >= 100)  break;
2033      Node* ifproj = dom;
2034      if (!ifproj->is_Proj())  continue;
2035      Node* iff = ifproj->in(0);
2036      if (!iff->is_If())  continue;
2037      Node* bol = iff->in(1);
2038      if (!bol->is_Bool())  continue;
2039      Node* cmp = bol->in(1);
2040      if (cmp == NULL)  continue;
2041      for (cmpn = 0; cmpn < NCMPS; cmpn++)
2042        if (cmps[cmpn] == cmp)  break;
2043      if (cmpn == NCMPS)  continue;
2044      BoolTest::mask btest = bol->as_Bool()->_test._test;
2045      if (ifproj->is_IfFalse())  btest = BoolTest(btest).negate();
2046      if (cmp->in(1) == ykey)    btest = BoolTest(btest).commute();
2047      // At this point, we know that 'x btest y' is true.
2048      switch (btest) {
2049      case BoolTest::eq:
2050        // They are proven equal, so we can collapse the min/max.
2051        // Either value is the answer.  Choose the simpler.
2052        if (is_simple_name(yvalue) && !is_simple_name(xvalue))
2053          return yvalue;
2054        return xvalue;
2055      case BoolTest::lt:          // x < y
2056      case BoolTest::le:          // x <= y
2057        return (want_max ? yvalue : xvalue);
2058      case BoolTest::gt:          // x > y
2059      case BoolTest::ge:          // x >= y
2060        return (want_max ? xvalue : yvalue);
2061      }
2062    }
2063  }
2064
2065  // We failed to find a dominating test.
2066  // Let's pick a test that might GVN with prior tests.
2067  Node*          best_bol   = NULL;
2068  BoolTest::mask best_btest = BoolTest::illegal;
2069  for (cmpn = 0; cmpn < NCMPS; cmpn++) {
2070    Node* cmp = cmps[cmpn];
2071    if (cmp == NULL)  continue;
2072    for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {
2073      Node* bol = cmp->fast_out(j);
2074      if (!bol->is_Bool())  continue;
2075      BoolTest::mask btest = bol->as_Bool()->_test._test;
2076      if (btest == BoolTest::eq || btest == BoolTest::ne)  continue;
2077      if (cmp->in(1) == ykey)   btest = BoolTest(btest).commute();
2078      if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {
2079        best_bol   = bol->as_Bool();
2080        best_btest = btest;
2081      }
2082    }
2083  }
2084
2085  Node* answer_if_true  = NULL;
2086  Node* answer_if_false = NULL;
2087  switch (best_btest) {
2088  default:
2089    if (cmpxy == NULL)
2090      cmpxy = ideal_cmpxy;
2091    best_bol = _gvn.transform(new(C) BoolNode(cmpxy, BoolTest::lt));
2092    // and fall through:
2093  case BoolTest::lt:          // x < y
2094  case BoolTest::le:          // x <= y
2095    answer_if_true  = (want_max ? yvalue : xvalue);
2096    answer_if_false = (want_max ? xvalue : yvalue);
2097    break;
2098  case BoolTest::gt:          // x > y
2099  case BoolTest::ge:          // x >= y
2100    answer_if_true  = (want_max ? xvalue : yvalue);
2101    answer_if_false = (want_max ? yvalue : xvalue);
2102    break;
2103  }
2104
2105  jint hi, lo;
2106  if (want_max) {
2107    // We can sharpen the minimum.
2108    hi = MAX2(txvalue->_hi, tyvalue->_hi);
2109    lo = MAX2(txvalue->_lo, tyvalue->_lo);
2110  } else {
2111    // We can sharpen the maximum.
2112    hi = MIN2(txvalue->_hi, tyvalue->_hi);
2113    lo = MIN2(txvalue->_lo, tyvalue->_lo);
2114  }
2115
2116  // Use a flow-free graph structure, to avoid creating excess control edges
2117  // which could hinder other optimizations.
2118  // Since Math.min/max is often used with arraycopy, we want
2119  // tightly_coupled_allocation to be able to see beyond min/max expressions.
2120  Node* cmov = CMoveNode::make(C, NULL, best_bol,
2121                               answer_if_false, answer_if_true,
2122                               TypeInt::make(lo, hi, widen));
2123
2124  return _gvn.transform(cmov);
2125
2126  /*
2127  // This is not as desirable as it may seem, since Min and Max
2128  // nodes do not have a full set of optimizations.
2129  // And they would interfere, anyway, with 'if' optimizations
2130  // and with CMoveI canonical forms.
2131  switch (id) {
2132  case vmIntrinsics::_min:
2133    result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;
2134  case vmIntrinsics::_max:
2135    result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;
2136  default:
2137    ShouldNotReachHere();
2138  }
2139  */
2140}
2141
2142inline int
2143LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset) {
2144  const TypePtr* base_type = TypePtr::NULL_PTR;
2145  if (base != NULL)  base_type = _gvn.type(base)->isa_ptr();
2146  if (base_type == NULL) {
2147    // Unknown type.
2148    return Type::AnyPtr;
2149  } else if (base_type == TypePtr::NULL_PTR) {
2150    // Since this is a NULL+long form, we have to switch to a rawptr.
2151    base   = _gvn.transform(new (C) CastX2PNode(offset));
2152    offset = MakeConX(0);
2153    return Type::RawPtr;
2154  } else if (base_type->base() == Type::RawPtr) {
2155    return Type::RawPtr;
2156  } else if (base_type->isa_oopptr()) {
2157    // Base is never null => always a heap address.
2158    if (base_type->ptr() == TypePtr::NotNull) {
2159      return Type::OopPtr;
2160    }
2161    // Offset is small => always a heap address.
2162    const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2163    if (offset_type != NULL &&
2164        base_type->offset() == 0 &&     // (should always be?)
2165        offset_type->_lo >= 0 &&
2166        !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2167      return Type::OopPtr;
2168    }
2169    // Otherwise, it might either be oop+off or NULL+addr.
2170    return Type::AnyPtr;
2171  } else {
2172    // No information:
2173    return Type::AnyPtr;
2174  }
2175}
2176
2177inline Node* LibraryCallKit::make_unsafe_address(Node* base, Node* offset) {
2178  int kind = classify_unsafe_addr(base, offset);
2179  if (kind == Type::RawPtr) {
2180    return basic_plus_adr(top(), base, offset);
2181  } else {
2182    return basic_plus_adr(base, offset);
2183  }
2184}
2185
2186//--------------------------inline_number_methods-----------------------------
2187// inline int     Integer.numberOfLeadingZeros(int)
2188// inline int        Long.numberOfLeadingZeros(long)
2189//
2190// inline int     Integer.numberOfTrailingZeros(int)
2191// inline int        Long.numberOfTrailingZeros(long)
2192//
2193// inline int     Integer.bitCount(int)
2194// inline int        Long.bitCount(long)
2195//
2196// inline char  Character.reverseBytes(char)
2197// inline short     Short.reverseBytes(short)
2198// inline int     Integer.reverseBytes(int)
2199// inline long       Long.reverseBytes(long)
2200bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2201  Node* arg = argument(0);
2202  Node* n;
2203  switch (id) {
2204  case vmIntrinsics::_numberOfLeadingZeros_i:   n = new (C) CountLeadingZerosINode( arg);  break;
2205  case vmIntrinsics::_numberOfLeadingZeros_l:   n = new (C) CountLeadingZerosLNode( arg);  break;
2206  case vmIntrinsics::_numberOfTrailingZeros_i:  n = new (C) CountTrailingZerosINode(arg);  break;
2207  case vmIntrinsics::_numberOfTrailingZeros_l:  n = new (C) CountTrailingZerosLNode(arg);  break;
2208  case vmIntrinsics::_bitCount_i:               n = new (C) PopCountINode(          arg);  break;
2209  case vmIntrinsics::_bitCount_l:               n = new (C) PopCountLNode(          arg);  break;
2210  case vmIntrinsics::_reverseBytes_c:           n = new (C) ReverseBytesUSNode(0,   arg);  break;
2211  case vmIntrinsics::_reverseBytes_s:           n = new (C) ReverseBytesSNode( 0,   arg);  break;
2212  case vmIntrinsics::_reverseBytes_i:           n = new (C) ReverseBytesINode( 0,   arg);  break;
2213  case vmIntrinsics::_reverseBytes_l:           n = new (C) ReverseBytesLNode( 0,   arg);  break;
2214  default:  fatal_unexpected_iid(id);  break;
2215  }
2216  set_result(_gvn.transform(n));
2217  return true;
2218}
2219
2220//----------------------------inline_unsafe_access----------------------------
2221
2222const static BasicType T_ADDRESS_HOLDER = T_LONG;
2223
2224// Helper that guards and inserts a pre-barrier.
2225void LibraryCallKit::insert_pre_barrier(Node* base_oop, Node* offset,
2226                                        Node* pre_val, bool need_mem_bar) {
2227  // We could be accessing the referent field of a reference object. If so, when G1
2228  // is enabled, we need to log the value in the referent field in an SATB buffer.
2229  // This routine performs some compile time filters and generates suitable
2230  // runtime filters that guard the pre-barrier code.
2231  // Also add memory barrier for non volatile load from the referent field
2232  // to prevent commoning of loads across safepoint.
2233  if (!UseG1GC && !need_mem_bar)
2234    return;
2235
2236  // Some compile time checks.
2237
2238  // If offset is a constant, is it java_lang_ref_Reference::_reference_offset?
2239  const TypeX* otype = offset->find_intptr_t_type();
2240  if (otype != NULL && otype->is_con() &&
2241      otype->get_con() != java_lang_ref_Reference::referent_offset) {
2242    // Constant offset but not the reference_offset so just return
2243    return;
2244  }
2245
2246  // We only need to generate the runtime guards for instances.
2247  const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();
2248  if (btype != NULL) {
2249    if (btype->isa_aryptr()) {
2250      // Array type so nothing to do
2251      return;
2252    }
2253
2254    const TypeInstPtr* itype = btype->isa_instptr();
2255    if (itype != NULL) {
2256      // Can the klass of base_oop be statically determined to be
2257      // _not_ a sub-class of Reference and _not_ Object?
2258      ciKlass* klass = itype->klass();
2259      if ( klass->is_loaded() &&
2260          !klass->is_subtype_of(env()->Reference_klass()) &&
2261          !env()->Object_klass()->is_subtype_of(klass)) {
2262        return;
2263      }
2264    }
2265  }
2266
2267  // The compile time filters did not reject base_oop/offset so
2268  // we need to generate the following runtime filters
2269  //
2270  // if (offset == java_lang_ref_Reference::_reference_offset) {
2271  //   if (instance_of(base, java.lang.ref.Reference)) {
2272  //     pre_barrier(_, pre_val, ...);
2273  //   }
2274  // }
2275
2276  float likely   = PROB_LIKELY(  0.999);
2277  float unlikely = PROB_UNLIKELY(0.999);
2278
2279  IdealKit ideal(this);
2280#define __ ideal.
2281
2282  Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset);
2283
2284  __ if_then(offset, BoolTest::eq, referent_off, unlikely); {
2285      // Update graphKit memory and control from IdealKit.
2286      sync_kit(ideal);
2287
2288      Node* ref_klass_con = makecon(TypeKlassPtr::make(env()->Reference_klass()));
2289      Node* is_instof = gen_instanceof(base_oop, ref_klass_con);
2290
2291      // Update IdealKit memory and control from graphKit.
2292      __ sync_kit(this);
2293
2294      Node* one = __ ConI(1);
2295      // is_instof == 0 if base_oop == NULL
2296      __ if_then(is_instof, BoolTest::eq, one, unlikely); {
2297
2298        // Update graphKit from IdeakKit.
2299        sync_kit(ideal);
2300
2301        // Use the pre-barrier to record the value in the referent field
2302        pre_barrier(false /* do_load */,
2303                    __ ctrl(),
2304                    NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
2305                    pre_val /* pre_val */,
2306                    T_OBJECT);
2307        if (need_mem_bar) {
2308          // Add memory barrier to prevent commoning reads from this field
2309          // across safepoint since GC can change its value.
2310          insert_mem_bar(Op_MemBarCPUOrder);
2311        }
2312        // Update IdealKit from graphKit.
2313        __ sync_kit(this);
2314
2315      } __ end_if(); // _ref_type != ref_none
2316  } __ end_if(); // offset == referent_offset
2317
2318  // Final sync IdealKit and GraphKit.
2319  final_sync(ideal);
2320#undef __
2321}
2322
2323
2324// Interpret Unsafe.fieldOffset cookies correctly:
2325extern jlong Unsafe_field_offset_to_byte_offset(jlong field_offset);
2326
2327const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr) {
2328  // Attempt to infer a sharper value type from the offset and base type.
2329  ciKlass* sharpened_klass = NULL;
2330
2331  // See if it is an instance field, with an object type.
2332  if (alias_type->field() != NULL) {
2333    assert(!is_native_ptr, "native pointer op cannot use a java address");
2334    if (alias_type->field()->type()->is_klass()) {
2335      sharpened_klass = alias_type->field()->type()->as_klass();
2336    }
2337  }
2338
2339  // See if it is a narrow oop array.
2340  if (adr_type->isa_aryptr()) {
2341    if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2342      const TypeOopPtr *elem_type = adr_type->is_aryptr()->elem()->isa_oopptr();
2343      if (elem_type != NULL) {
2344        sharpened_klass = elem_type->klass();
2345      }
2346    }
2347  }
2348
2349  // The sharpened class might be unloaded if there is no class loader
2350  // contraint in place.
2351  if (sharpened_klass != NULL && sharpened_klass->is_loaded()) {
2352    const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);
2353
2354#ifndef PRODUCT
2355    if (C->print_intrinsics() || C->print_inlining()) {
2356      tty->print("  from base type: ");  adr_type->dump();
2357      tty->print("  sharpened value: ");  tjp->dump();
2358    }
2359#endif
2360    // Sharpen the value type.
2361    return tjp;
2362  }
2363  return NULL;
2364}
2365
2366bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile) {
2367  if (callee()->is_static())  return false;  // caller must have the capability!
2368
2369#ifndef PRODUCT
2370  {
2371    ResourceMark rm;
2372    // Check the signatures.
2373    ciSignature* sig = callee()->signature();
2374#ifdef ASSERT
2375    if (!is_store) {
2376      // Object getObject(Object base, int/long offset), etc.
2377      BasicType rtype = sig->return_type()->basic_type();
2378      if (rtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::getAddress_name())
2379          rtype = T_ADDRESS;  // it is really a C void*
2380      assert(rtype == type, "getter must return the expected value");
2381      if (!is_native_ptr) {
2382        assert(sig->count() == 2, "oop getter has 2 arguments");
2383        assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2384        assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2385      } else {
2386        assert(sig->count() == 1, "native getter has 1 argument");
2387        assert(sig->type_at(0)->basic_type() == T_LONG, "getter base is long");
2388      }
2389    } else {
2390      // void putObject(Object base, int/long offset, Object x), etc.
2391      assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2392      if (!is_native_ptr) {
2393        assert(sig->count() == 3, "oop putter has 3 arguments");
2394        assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2395        assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2396      } else {
2397        assert(sig->count() == 2, "native putter has 2 arguments");
2398        assert(sig->type_at(0)->basic_type() == T_LONG, "putter base is long");
2399      }
2400      BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2401      if (vtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::putAddress_name())
2402        vtype = T_ADDRESS;  // it is really a C void*
2403      assert(vtype == type, "putter must accept the expected value");
2404    }
2405#endif // ASSERT
2406 }
2407#endif //PRODUCT
2408
2409  C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2410
2411  Node* receiver = argument(0);  // type: oop
2412
2413  // Build address expression.  See the code in inline_unsafe_prefetch.
2414  Node* adr;
2415  Node* heap_base_oop = top();
2416  Node* offset = top();
2417  Node* val;
2418
2419  if (!is_native_ptr) {
2420    // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2421    Node* base = argument(1);  // type: oop
2422    // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2423    offset = argument(2);  // type: long
2424    // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2425    // to be plain byte offsets, which are also the same as those accepted
2426    // by oopDesc::field_base.
2427    assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2428           "fieldOffset must be byte-scaled");
2429    // 32-bit machines ignore the high half!
2430    offset = ConvL2X(offset);
2431    adr = make_unsafe_address(base, offset);
2432    heap_base_oop = base;
2433    val = is_store ? argument(4) : NULL;
2434  } else {
2435    Node* ptr = argument(1);  // type: long
2436    ptr = ConvL2X(ptr);  // adjust Java long to machine word
2437    adr = make_unsafe_address(NULL, ptr);
2438    val = is_store ? argument(3) : NULL;
2439  }
2440
2441  const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2442
2443  // First guess at the value type.
2444  const Type *value_type = Type::get_const_basic_type(type);
2445
2446  // Try to categorize the address.  If it comes up as TypeJavaPtr::BOTTOM,
2447  // there was not enough information to nail it down.
2448  Compile::AliasType* alias_type = C->alias_type(adr_type);
2449  assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2450
2451  // We will need memory barriers unless we can determine a unique
2452  // alias category for this reference.  (Note:  If for some reason
2453  // the barriers get omitted and the unsafe reference begins to "pollute"
2454  // the alias analysis of the rest of the graph, either Compile::can_alias
2455  // or Compile::must_alias will throw a diagnostic assert.)
2456  bool need_mem_bar = (alias_type->adr_type() == TypeOopPtr::BOTTOM);
2457
2458  // If we are reading the value of the referent field of a Reference
2459  // object (either by using Unsafe directly or through reflection)
2460  // then, if G1 is enabled, we need to record the referent in an
2461  // SATB log buffer using the pre-barrier mechanism.
2462  // Also we need to add memory barrier to prevent commoning reads
2463  // from this field across safepoint since GC can change its value.
2464  bool need_read_barrier = !is_native_ptr && !is_store &&
2465                           offset != top() && heap_base_oop != top();
2466
2467  if (!is_store && type == T_OBJECT) {
2468    const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type, is_native_ptr);
2469    if (tjp != NULL) {
2470      value_type = tjp;
2471    }
2472  }
2473
2474  receiver = null_check(receiver);
2475  if (stopped()) {
2476    return true;
2477  }
2478  // Heap pointers get a null-check from the interpreter,
2479  // as a courtesy.  However, this is not guaranteed by Unsafe,
2480  // and it is not possible to fully distinguish unintended nulls
2481  // from intended ones in this API.
2482
2483  if (is_volatile) {
2484    // We need to emit leading and trailing CPU membars (see below) in
2485    // addition to memory membars when is_volatile. This is a little
2486    // too strong, but avoids the need to insert per-alias-type
2487    // volatile membars (for stores; compare Parse::do_put_xxx), which
2488    // we cannot do effectively here because we probably only have a
2489    // rough approximation of type.
2490    need_mem_bar = true;
2491    // For Stores, place a memory ordering barrier now.
2492    if (is_store)
2493      insert_mem_bar(Op_MemBarRelease);
2494  }
2495
2496  // Memory barrier to prevent normal and 'unsafe' accesses from
2497  // bypassing each other.  Happens after null checks, so the
2498  // exception paths do not take memory state from the memory barrier,
2499  // so there's no problems making a strong assert about mixing users
2500  // of safe & unsafe memory.  Otherwise fails in a CTW of rt.jar
2501  // around 5701, class sun/reflect/UnsafeBooleanFieldAccessorImpl.
2502  if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2503
2504  if (!is_store) {
2505    Node* p = make_load(control(), adr, value_type, type, adr_type, is_volatile);
2506    // load value
2507    switch (type) {
2508    case T_BOOLEAN:
2509    case T_CHAR:
2510    case T_BYTE:
2511    case T_SHORT:
2512    case T_INT:
2513    case T_LONG:
2514    case T_FLOAT:
2515    case T_DOUBLE:
2516      break;
2517    case T_OBJECT:
2518      if (need_read_barrier) {
2519        insert_pre_barrier(heap_base_oop, offset, p, !(is_volatile || need_mem_bar));
2520      }
2521      break;
2522    case T_ADDRESS:
2523      // Cast to an int type.
2524      p = _gvn.transform(new (C) CastP2XNode(NULL, p));
2525      p = ConvX2L(p);
2526      break;
2527    default:
2528      fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));
2529      break;
2530    }
2531    // The load node has the control of the preceding MemBarCPUOrder.  All
2532    // following nodes will have the control of the MemBarCPUOrder inserted at
2533    // the end of this method.  So, pushing the load onto the stack at a later
2534    // point is fine.
2535    set_result(p);
2536  } else {
2537    // place effect of store into memory
2538    switch (type) {
2539    case T_DOUBLE:
2540      val = dstore_rounding(val);
2541      break;
2542    case T_ADDRESS:
2543      // Repackage the long as a pointer.
2544      val = ConvL2X(val);
2545      val = _gvn.transform(new (C) CastX2PNode(val));
2546      break;
2547    }
2548
2549    if (type != T_OBJECT ) {
2550      (void) store_to_memory(control(), adr, val, type, adr_type, is_volatile);
2551    } else {
2552      // Possibly an oop being stored to Java heap or native memory
2553      if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(heap_base_oop))) {
2554        // oop to Java heap.
2555        (void) store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type);
2556      } else {
2557        // We can't tell at compile time if we are storing in the Java heap or outside
2558        // of it. So we need to emit code to conditionally do the proper type of
2559        // store.
2560
2561        IdealKit ideal(this);
2562#define __ ideal.
2563        // QQQ who knows what probability is here??
2564        __ if_then(heap_base_oop, BoolTest::ne, null(), PROB_UNLIKELY(0.999)); {
2565          // Sync IdealKit and graphKit.
2566          sync_kit(ideal);
2567          Node* st = store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type);
2568          // Update IdealKit memory.
2569          __ sync_kit(this);
2570        } __ else_(); {
2571          __ store(__ ctrl(), adr, val, type, alias_type->index(), is_volatile);
2572        } __ end_if();
2573        // Final sync IdealKit and GraphKit.
2574        final_sync(ideal);
2575#undef __
2576      }
2577    }
2578  }
2579
2580  if (is_volatile) {
2581    if (!is_store)
2582      insert_mem_bar(Op_MemBarAcquire);
2583    else
2584      insert_mem_bar(Op_MemBarVolatile);
2585  }
2586
2587  if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2588
2589  return true;
2590}
2591
2592//----------------------------inline_unsafe_prefetch----------------------------
2593
2594bool LibraryCallKit::inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static) {
2595#ifndef PRODUCT
2596  {
2597    ResourceMark rm;
2598    // Check the signatures.
2599    ciSignature* sig = callee()->signature();
2600#ifdef ASSERT
2601    // Object getObject(Object base, int/long offset), etc.
2602    BasicType rtype = sig->return_type()->basic_type();
2603    if (!is_native_ptr) {
2604      assert(sig->count() == 2, "oop prefetch has 2 arguments");
2605      assert(sig->type_at(0)->basic_type() == T_OBJECT, "prefetch base is object");
2606      assert(sig->type_at(1)->basic_type() == T_LONG, "prefetcha offset is correct");
2607    } else {
2608      assert(sig->count() == 1, "native prefetch has 1 argument");
2609      assert(sig->type_at(0)->basic_type() == T_LONG, "prefetch base is long");
2610    }
2611#endif // ASSERT
2612  }
2613#endif // !PRODUCT
2614
2615  C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2616
2617  const int idx = is_static ? 0 : 1;
2618  if (!is_static) {
2619    null_check_receiver();
2620    if (stopped()) {
2621      return true;
2622    }
2623  }
2624
2625  // Build address expression.  See the code in inline_unsafe_access.
2626  Node *adr;
2627  if (!is_native_ptr) {
2628    // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2629    Node* base   = argument(idx + 0);  // type: oop
2630    // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2631    Node* offset = argument(idx + 1);  // type: long
2632    // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2633    // to be plain byte offsets, which are also the same as those accepted
2634    // by oopDesc::field_base.
2635    assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2636           "fieldOffset must be byte-scaled");
2637    // 32-bit machines ignore the high half!
2638    offset = ConvL2X(offset);
2639    adr = make_unsafe_address(base, offset);
2640  } else {
2641    Node* ptr = argument(idx + 0);  // type: long
2642    ptr = ConvL2X(ptr);  // adjust Java long to machine word
2643    adr = make_unsafe_address(NULL, ptr);
2644  }
2645
2646  // Generate the read or write prefetch
2647  Node *prefetch;
2648  if (is_store) {
2649    prefetch = new (C) PrefetchWriteNode(i_o(), adr);
2650  } else {
2651    prefetch = new (C) PrefetchReadNode(i_o(), adr);
2652  }
2653  prefetch->init_req(0, control());
2654  set_i_o(_gvn.transform(prefetch));
2655
2656  return true;
2657}
2658
2659//----------------------------inline_unsafe_load_store----------------------------
2660// This method serves a couple of different customers (depending on LoadStoreKind):
2661//
2662// LS_cmpxchg:
2663//   public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x);
2664//   public final native boolean compareAndSwapInt(   Object o, long offset, int    expected, int    x);
2665//   public final native boolean compareAndSwapLong(  Object o, long offset, long   expected, long   x);
2666//
2667// LS_xadd:
2668//   public int  getAndAddInt( Object o, long offset, int  delta)
2669//   public long getAndAddLong(Object o, long offset, long delta)
2670//
2671// LS_xchg:
2672//   int    getAndSet(Object o, long offset, int    newValue)
2673//   long   getAndSet(Object o, long offset, long   newValue)
2674//   Object getAndSet(Object o, long offset, Object newValue)
2675//
2676bool LibraryCallKit::inline_unsafe_load_store(BasicType type, LoadStoreKind kind) {
2677  // This basic scheme here is the same as inline_unsafe_access, but
2678  // differs in enough details that combining them would make the code
2679  // overly confusing.  (This is a true fact! I originally combined
2680  // them, but even I was confused by it!) As much code/comments as
2681  // possible are retained from inline_unsafe_access though to make
2682  // the correspondences clearer. - dl
2683
2684  if (callee()->is_static())  return false;  // caller must have the capability!
2685
2686#ifndef PRODUCT
2687  BasicType rtype;
2688  {
2689    ResourceMark rm;
2690    // Check the signatures.
2691    ciSignature* sig = callee()->signature();
2692    rtype = sig->return_type()->basic_type();
2693    if (kind == LS_xadd || kind == LS_xchg) {
2694      // Check the signatures.
2695#ifdef ASSERT
2696      assert(rtype == type, "get and set must return the expected type");
2697      assert(sig->count() == 3, "get and set has 3 arguments");
2698      assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2699      assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2700      assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2701#endif // ASSERT
2702    } else if (kind == LS_cmpxchg) {
2703      // Check the signatures.
2704#ifdef ASSERT
2705      assert(rtype == T_BOOLEAN, "CAS must return boolean");
2706      assert(sig->count() == 4, "CAS has 4 arguments");
2707      assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2708      assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2709#endif // ASSERT
2710    } else {
2711      ShouldNotReachHere();
2712    }
2713  }
2714#endif //PRODUCT
2715
2716  C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2717
2718  // Get arguments:
2719  Node* receiver = NULL;
2720  Node* base     = NULL;
2721  Node* offset   = NULL;
2722  Node* oldval   = NULL;
2723  Node* newval   = NULL;
2724  if (kind == LS_cmpxchg) {
2725    const bool two_slot_type = type2size[type] == 2;
2726    receiver = argument(0);  // type: oop
2727    base     = argument(1);  // type: oop
2728    offset   = argument(2);  // type: long
2729    oldval   = argument(4);  // type: oop, int, or long
2730    newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2731  } else if (kind == LS_xadd || kind == LS_xchg){
2732    receiver = argument(0);  // type: oop
2733    base     = argument(1);  // type: oop
2734    offset   = argument(2);  // type: long
2735    oldval   = NULL;
2736    newval   = argument(4);  // type: oop, int, or long
2737  }
2738
2739  // Null check receiver.
2740  receiver = null_check(receiver);
2741  if (stopped()) {
2742    return true;
2743  }
2744
2745  // Build field offset expression.
2746  // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2747  // to be plain byte offsets, which are also the same as those accepted
2748  // by oopDesc::field_base.
2749  assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2750  // 32-bit machines ignore the high half of long offsets
2751  offset = ConvL2X(offset);
2752  Node* adr = make_unsafe_address(base, offset);
2753  const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2754
2755  // For CAS, unlike inline_unsafe_access, there seems no point in
2756  // trying to refine types. Just use the coarse types here.
2757  const Type *value_type = Type::get_const_basic_type(type);
2758  Compile::AliasType* alias_type = C->alias_type(adr_type);
2759  assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2760
2761  if (kind == LS_xchg && type == T_OBJECT) {
2762    const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2763    if (tjp != NULL) {
2764      value_type = tjp;
2765    }
2766  }
2767
2768  int alias_idx = C->get_alias_index(adr_type);
2769
2770  // Memory-model-wise, a LoadStore acts like a little synchronized
2771  // block, so needs barriers on each side.  These don't translate
2772  // into actual barriers on most machines, but we still need rest of
2773  // compiler to respect ordering.
2774
2775  insert_mem_bar(Op_MemBarRelease);
2776  insert_mem_bar(Op_MemBarCPUOrder);
2777
2778  // 4984716: MemBars must be inserted before this
2779  //          memory node in order to avoid a false
2780  //          dependency which will confuse the scheduler.
2781  Node *mem = memory(alias_idx);
2782
2783  // For now, we handle only those cases that actually exist: ints,
2784  // longs, and Object. Adding others should be straightforward.
2785  Node* load_store;
2786  switch(type) {
2787  case T_INT:
2788    if (kind == LS_xadd) {
2789      load_store = _gvn.transform(new (C) GetAndAddINode(control(), mem, adr, newval, adr_type));
2790    } else if (kind == LS_xchg) {
2791      load_store = _gvn.transform(new (C) GetAndSetINode(control(), mem, adr, newval, adr_type));
2792    } else if (kind == LS_cmpxchg) {
2793      load_store = _gvn.transform(new (C) CompareAndSwapINode(control(), mem, adr, newval, oldval));
2794    } else {
2795      ShouldNotReachHere();
2796    }
2797    break;
2798  case T_LONG:
2799    if (kind == LS_xadd) {
2800      load_store = _gvn.transform(new (C) GetAndAddLNode(control(), mem, adr, newval, adr_type));
2801    } else if (kind == LS_xchg) {
2802      load_store = _gvn.transform(new (C) GetAndSetLNode(control(), mem, adr, newval, adr_type));
2803    } else if (kind == LS_cmpxchg) {
2804      load_store = _gvn.transform(new (C) CompareAndSwapLNode(control(), mem, adr, newval, oldval));
2805    } else {
2806      ShouldNotReachHere();
2807    }
2808    break;
2809  case T_OBJECT:
2810    // Transformation of a value which could be NULL pointer (CastPP #NULL)
2811    // could be delayed during Parse (for example, in adjust_map_after_if()).
2812    // Execute transformation here to avoid barrier generation in such case.
2813    if (_gvn.type(newval) == TypePtr::NULL_PTR)
2814      newval = _gvn.makecon(TypePtr::NULL_PTR);
2815
2816    // Reference stores need a store barrier.
2817    if (kind == LS_xchg) {
2818      // If pre-barrier must execute before the oop store, old value will require do_load here.
2819      if (!can_move_pre_barrier()) {
2820        pre_barrier(true /* do_load*/,
2821                    control(), base, adr, alias_idx, newval, value_type->make_oopptr(),
2822                    NULL /* pre_val*/,
2823                    T_OBJECT);
2824      } // Else move pre_barrier to use load_store value, see below.
2825    } else if (kind == LS_cmpxchg) {
2826      // Same as for newval above:
2827      if (_gvn.type(oldval) == TypePtr::NULL_PTR) {
2828        oldval = _gvn.makecon(TypePtr::NULL_PTR);
2829      }
2830      // The only known value which might get overwritten is oldval.
2831      pre_barrier(false /* do_load */,
2832                  control(), NULL, NULL, max_juint, NULL, NULL,
2833                  oldval /* pre_val */,
2834                  T_OBJECT);
2835    } else {
2836      ShouldNotReachHere();
2837    }
2838
2839#ifdef _LP64
2840    if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2841      Node *newval_enc = _gvn.transform(new (C) EncodePNode(newval, newval->bottom_type()->make_narrowoop()));
2842      if (kind == LS_xchg) {
2843        load_store = _gvn.transform(new (C) GetAndSetNNode(control(), mem, adr,
2844                                                              newval_enc, adr_type, value_type->make_narrowoop()));
2845      } else {
2846        assert(kind == LS_cmpxchg, "wrong LoadStore operation");
2847        Node *oldval_enc = _gvn.transform(new (C) EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
2848        load_store = _gvn.transform(new (C) CompareAndSwapNNode(control(), mem, adr,
2849                                                                   newval_enc, oldval_enc));
2850      }
2851    } else
2852#endif
2853    {
2854      if (kind == LS_xchg) {
2855        load_store = _gvn.transform(new (C) GetAndSetPNode(control(), mem, adr, newval, adr_type, value_type->is_oopptr()));
2856      } else {
2857        assert(kind == LS_cmpxchg, "wrong LoadStore operation");
2858        load_store = _gvn.transform(new (C) CompareAndSwapPNode(control(), mem, adr, newval, oldval));
2859      }
2860    }
2861    post_barrier(control(), load_store, base, adr, alias_idx, newval, T_OBJECT, true);
2862    break;
2863  default:
2864    fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));
2865    break;
2866  }
2867
2868  // SCMemProjNodes represent the memory state of a LoadStore. Their
2869  // main role is to prevent LoadStore nodes from being optimized away
2870  // when their results aren't used.
2871  Node* proj = _gvn.transform(new (C) SCMemProjNode(load_store));
2872  set_memory(proj, alias_idx);
2873
2874  if (type == T_OBJECT && kind == LS_xchg) {
2875#ifdef _LP64
2876    if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2877      load_store = _gvn.transform(new (C) DecodeNNode(load_store, load_store->get_ptr_type()));
2878    }
2879#endif
2880    if (can_move_pre_barrier()) {
2881      // Don't need to load pre_val. The old value is returned by load_store.
2882      // The pre_barrier can execute after the xchg as long as no safepoint
2883      // gets inserted between them.
2884      pre_barrier(false /* do_load */,
2885                  control(), NULL, NULL, max_juint, NULL, NULL,
2886                  load_store /* pre_val */,
2887                  T_OBJECT);
2888    }
2889  }
2890
2891  // Add the trailing membar surrounding the access
2892  insert_mem_bar(Op_MemBarCPUOrder);
2893  insert_mem_bar(Op_MemBarAcquire);
2894
2895  assert(type2size[load_store->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
2896  set_result(load_store);
2897  return true;
2898}
2899
2900//----------------------------inline_unsafe_ordered_store----------------------
2901// public native void sun.misc.Unsafe.putOrderedObject(Object o, long offset, Object x);
2902// public native void sun.misc.Unsafe.putOrderedInt(Object o, long offset, int x);
2903// public native void sun.misc.Unsafe.putOrderedLong(Object o, long offset, long x);
2904bool LibraryCallKit::inline_unsafe_ordered_store(BasicType type) {
2905  // This is another variant of inline_unsafe_access, differing in
2906  // that it always issues store-store ("release") barrier and ensures
2907  // store-atomicity (which only matters for "long").
2908
2909  if (callee()->is_static())  return false;  // caller must have the capability!
2910
2911#ifndef PRODUCT
2912  {
2913    ResourceMark rm;
2914    // Check the signatures.
2915    ciSignature* sig = callee()->signature();
2916#ifdef ASSERT
2917    BasicType rtype = sig->return_type()->basic_type();
2918    assert(rtype == T_VOID, "must return void");
2919    assert(sig->count() == 3, "has 3 arguments");
2920    assert(sig->type_at(0)->basic_type() == T_OBJECT, "base is object");
2921    assert(sig->type_at(1)->basic_type() == T_LONG, "offset is long");
2922#endif // ASSERT
2923  }
2924#endif //PRODUCT
2925
2926  C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2927
2928  // Get arguments:
2929  Node* receiver = argument(0);  // type: oop
2930  Node* base     = argument(1);  // type: oop
2931  Node* offset   = argument(2);  // type: long
2932  Node* val      = argument(4);  // type: oop, int, or long
2933
2934  // Null check receiver.
2935  receiver = null_check(receiver);
2936  if (stopped()) {
2937    return true;
2938  }
2939
2940  // Build field offset expression.
2941  assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2942  // 32-bit machines ignore the high half of long offsets
2943  offset = ConvL2X(offset);
2944  Node* adr = make_unsafe_address(base, offset);
2945  const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2946  const Type *value_type = Type::get_const_basic_type(type);
2947  Compile::AliasType* alias_type = C->alias_type(adr_type);
2948
2949  insert_mem_bar(Op_MemBarRelease);
2950  insert_mem_bar(Op_MemBarCPUOrder);
2951  // Ensure that the store is atomic for longs:
2952  const bool require_atomic_access = true;
2953  Node* store;
2954  if (type == T_OBJECT) // reference stores need a store barrier.
2955    store = store_oop_to_unknown(control(), base, adr, adr_type, val, type);
2956  else {
2957    store = store_to_memory(control(), adr, val, type, adr_type, require_atomic_access);
2958  }
2959  insert_mem_bar(Op_MemBarCPUOrder);
2960  return true;
2961}
2962
2963bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
2964  // Regardless of form, don't allow previous ld/st to move down,
2965  // then issue acquire, release, or volatile mem_bar.
2966  insert_mem_bar(Op_MemBarCPUOrder);
2967  switch(id) {
2968    case vmIntrinsics::_loadFence:
2969      insert_mem_bar(Op_MemBarAcquire);
2970      return true;
2971    case vmIntrinsics::_storeFence:
2972      insert_mem_bar(Op_MemBarRelease);
2973      return true;
2974    case vmIntrinsics::_fullFence:
2975      insert_mem_bar(Op_MemBarVolatile);
2976      return true;
2977    default:
2978      fatal_unexpected_iid(id);
2979      return false;
2980  }
2981}
2982
2983bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
2984  if (!kls->is_Con()) {
2985    return true;
2986  }
2987  const TypeKlassPtr* klsptr = kls->bottom_type()->isa_klassptr();
2988  if (klsptr == NULL) {
2989    return true;
2990  }
2991  ciInstanceKlass* ik = klsptr->klass()->as_instance_klass();
2992  // don't need a guard for a klass that is already initialized
2993  return !ik->is_initialized();
2994}
2995
2996//----------------------------inline_unsafe_allocate---------------------------
2997// public native Object sun.misc.Unsafe.allocateInstance(Class<?> cls);
2998bool LibraryCallKit::inline_unsafe_allocate() {
2999  if (callee()->is_static())  return false;  // caller must have the capability!
3000
3001  null_check_receiver();  // null-check, then ignore
3002  Node* cls = null_check(argument(1));
3003  if (stopped())  return true;
3004
3005  Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
3006  kls = null_check(kls);
3007  if (stopped())  return true;  // argument was like int.class
3008
3009  Node* test = NULL;
3010  if (LibraryCallKit::klass_needs_init_guard(kls)) {
3011    // Note:  The argument might still be an illegal value like
3012    // Serializable.class or Object[].class.   The runtime will handle it.
3013    // But we must make an explicit check for initialization.
3014    Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3015    // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3016    // can generate code to load it as unsigned byte.
3017    Node* inst = make_load(NULL, insp, TypeInt::UBYTE, T_BOOLEAN);
3018    Node* bits = intcon(InstanceKlass::fully_initialized);
3019    test = _gvn.transform(new (C) SubINode(inst, bits));
3020    // The 'test' is non-zero if we need to take a slow path.
3021  }
3022
3023  Node* obj = new_instance(kls, test);
3024  set_result(obj);
3025  return true;
3026}
3027
3028#ifdef TRACE_HAVE_INTRINSICS
3029/*
3030 * oop -> myklass
3031 * myklass->trace_id |= USED
3032 * return myklass->trace_id & ~0x3
3033 */
3034bool LibraryCallKit::inline_native_classID() {
3035  null_check_receiver();  // null-check, then ignore
3036  Node* cls = null_check(argument(1), T_OBJECT);
3037  Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
3038  kls = null_check(kls, T_OBJECT);
3039  ByteSize offset = TRACE_ID_OFFSET;
3040  Node* insp = basic_plus_adr(kls, in_bytes(offset));
3041  Node* tvalue = make_load(NULL, insp, TypeLong::LONG, T_LONG);
3042  Node* bits = longcon(~0x03l); // ignore bit 0 & 1
3043  Node* andl = _gvn.transform(new (C) AndLNode(tvalue, bits));
3044  Node* clsused = longcon(0x01l); // set the class bit
3045  Node* orl = _gvn.transform(new (C) OrLNode(tvalue, clsused));
3046
3047  const TypePtr *adr_type = _gvn.type(insp)->isa_ptr();
3048  store_to_memory(control(), insp, orl, T_LONG, adr_type);
3049  set_result(andl);
3050  return true;
3051}
3052
3053bool LibraryCallKit::inline_native_threadID() {
3054  Node* tls_ptr = NULL;
3055  Node* cur_thr = generate_current_thread(tls_ptr);
3056  Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
3057  Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS);
3058  p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::thread_id_offset()));
3059
3060  Node* threadid = NULL;
3061  size_t thread_id_size = OSThread::thread_id_size();
3062  if (thread_id_size == (size_t) BytesPerLong) {
3063    threadid = ConvL2I(make_load(control(), p, TypeLong::LONG, T_LONG));
3064  } else if (thread_id_size == (size_t) BytesPerInt) {
3065    threadid = make_load(control(), p, TypeInt::INT, T_INT);
3066  } else {
3067    ShouldNotReachHere();
3068  }
3069  set_result(threadid);
3070  return true;
3071}
3072#endif
3073
3074//------------------------inline_native_time_funcs--------------
3075// inline code for System.currentTimeMillis() and System.nanoTime()
3076// these have the same type and signature
3077bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3078  const TypeFunc* tf = OptoRuntime::void_long_Type();
3079  const TypePtr* no_memory_effects = NULL;
3080  Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3081  Node* value = _gvn.transform(new (C) ProjNode(time, TypeFunc::Parms+0));
3082#ifdef ASSERT
3083  Node* value_top = _gvn.transform(new (C) ProjNode(time, TypeFunc::Parms+1));
3084  assert(value_top == top(), "second value must be top");
3085#endif
3086  set_result(value);
3087  return true;
3088}
3089
3090//------------------------inline_native_currentThread------------------
3091bool LibraryCallKit::inline_native_currentThread() {
3092  Node* junk = NULL;
3093  set_result(generate_current_thread(junk));
3094  return true;
3095}
3096
3097//------------------------inline_native_isInterrupted------------------
3098// private native boolean java.lang.Thread.isInterrupted(boolean ClearInterrupted);
3099bool LibraryCallKit::inline_native_isInterrupted() {
3100  // Add a fast path to t.isInterrupted(clear_int):
3101  //   (t == Thread.current() && (!TLS._osthread._interrupted || !clear_int))
3102  //   ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)
3103  // So, in the common case that the interrupt bit is false,
3104  // we avoid making a call into the VM.  Even if the interrupt bit
3105  // is true, if the clear_int argument is false, we avoid the VM call.
3106  // However, if the receiver is not currentThread, we must call the VM,
3107  // because there must be some locking done around the operation.
3108
3109  // We only go to the fast case code if we pass two guards.
3110  // Paths which do not pass are accumulated in the slow_region.
3111
3112  enum {
3113    no_int_result_path   = 1, // t == Thread.current() && !TLS._osthread._interrupted
3114    no_clear_result_path = 2, // t == Thread.current() &&  TLS._osthread._interrupted && !clear_int
3115    slow_result_path     = 3, // slow path: t.isInterrupted(clear_int)
3116    PATH_LIMIT
3117  };
3118
3119  // Ensure that it's not possible to move the load of TLS._osthread._interrupted flag
3120  // out of the function.
3121  insert_mem_bar(Op_MemBarCPUOrder);
3122
3123  RegionNode* result_rgn = new (C) RegionNode(PATH_LIMIT);
3124  PhiNode*    result_val = new (C) PhiNode(result_rgn, TypeInt::BOOL);
3125
3126  RegionNode* slow_region = new (C) RegionNode(1);
3127  record_for_igvn(slow_region);
3128
3129  // (a) Receiving thread must be the current thread.
3130  Node* rec_thr = argument(0);
3131  Node* tls_ptr = NULL;
3132  Node* cur_thr = generate_current_thread(tls_ptr);
3133  Node* cmp_thr = _gvn.transform(new (C) CmpPNode(cur_thr, rec_thr));
3134  Node* bol_thr = _gvn.transform(new (C) BoolNode(cmp_thr, BoolTest::ne));
3135
3136  generate_slow_guard(bol_thr, slow_region);
3137
3138  // (b) Interrupt bit on TLS must be false.
3139  Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
3140  Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS);
3141  p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::interrupted_offset()));
3142
3143  // Set the control input on the field _interrupted read to prevent it floating up.
3144  Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT);
3145  Node* cmp_bit = _gvn.transform(new (C) CmpINode(int_bit, intcon(0)));
3146  Node* bol_bit = _gvn.transform(new (C) BoolNode(cmp_bit, BoolTest::ne));
3147
3148  IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
3149
3150  // First fast path:  if (!TLS._interrupted) return false;
3151  Node* false_bit = _gvn.transform(new (C) IfFalseNode(iff_bit));
3152  result_rgn->init_req(no_int_result_path, false_bit);
3153  result_val->init_req(no_int_result_path, intcon(0));
3154
3155  // drop through to next case
3156  set_control( _gvn.transform(new (C) IfTrueNode(iff_bit)));
3157
3158  // (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.
3159  Node* clr_arg = argument(1);
3160  Node* cmp_arg = _gvn.transform(new (C) CmpINode(clr_arg, intcon(0)));
3161  Node* bol_arg = _gvn.transform(new (C) BoolNode(cmp_arg, BoolTest::ne));
3162  IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN);
3163
3164  // Second fast path:  ... else if (!clear_int) return true;
3165  Node* false_arg = _gvn.transform(new (C) IfFalseNode(iff_arg));
3166  result_rgn->init_req(no_clear_result_path, false_arg);
3167  result_val->init_req(no_clear_result_path, intcon(1));
3168
3169  // drop through to next case
3170  set_control( _gvn.transform(new (C) IfTrueNode(iff_arg)));
3171
3172  // (d) Otherwise, go to the slow path.
3173  slow_region->add_req(control());
3174  set_control( _gvn.transform(slow_region));
3175
3176  if (stopped()) {
3177    // There is no slow path.
3178    result_rgn->init_req(slow_result_path, top());
3179    result_val->init_req(slow_result_path, top());
3180  } else {
3181    // non-virtual because it is a private non-static
3182    CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_isInterrupted);
3183
3184    Node* slow_val = set_results_for_java_call(slow_call);
3185    // this->control() comes from set_results_for_java_call
3186
3187    Node* fast_io  = slow_call->in(TypeFunc::I_O);
3188    Node* fast_mem = slow_call->in(TypeFunc::Memory);
3189
3190    // These two phis are pre-filled with copies of of the fast IO and Memory
3191    PhiNode* result_mem  = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
3192    PhiNode* result_io   = PhiNode::make(result_rgn, fast_io,  Type::ABIO);
3193
3194    result_rgn->init_req(slow_result_path, control());
3195    result_io ->init_req(slow_result_path, i_o());
3196    result_mem->init_req(slow_result_path, reset_memory());
3197    result_val->init_req(slow_result_path, slow_val);
3198
3199    set_all_memory(_gvn.transform(result_mem));
3200    set_i_o(       _gvn.transform(result_io));
3201  }
3202
3203  C->set_has_split_ifs(true); // Has chance for split-if optimization
3204  set_result(result_rgn, result_val);
3205  return true;
3206}
3207
3208//---------------------------load_mirror_from_klass----------------------------
3209// Given a klass oop, load its java mirror (a java.lang.Class oop).
3210Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
3211  Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
3212  return make_load(NULL, p, TypeInstPtr::MIRROR, T_OBJECT);
3213}
3214
3215//-----------------------load_klass_from_mirror_common-------------------------
3216// Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
3217// Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
3218// and branch to the given path on the region.
3219// If never_see_null, take an uncommon trap on null, so we can optimistically
3220// compile for the non-null case.
3221// If the region is NULL, force never_see_null = true.
3222Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
3223                                                    bool never_see_null,
3224                                                    RegionNode* region,
3225                                                    int null_path,
3226                                                    int offset) {
3227  if (region == NULL)  never_see_null = true;
3228  Node* p = basic_plus_adr(mirror, offset);
3229  const TypeKlassPtr*  kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3230  Node* kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
3231  Node* null_ctl = top();
3232  kls = null_check_oop(kls, &null_ctl, never_see_null);
3233  if (region != NULL) {
3234    // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
3235    region->init_req(null_path, null_ctl);
3236  } else {
3237    assert(null_ctl == top(), "no loose ends");
3238  }
3239  return kls;
3240}
3241
3242//--------------------(inline_native_Class_query helpers)---------------------
3243// Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE, JVM_ACC_HAS_FINALIZER.
3244// Fall through if (mods & mask) == bits, take the guard otherwise.
3245Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3246  // Branch around if the given klass has the given modifier bit set.
3247  // Like generate_guard, adds a new path onto the region.
3248  Node* modp = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3249  Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT);
3250  Node* mask = intcon(modifier_mask);
3251  Node* bits = intcon(modifier_bits);
3252  Node* mbit = _gvn.transform(new (C) AndINode(mods, mask));
3253  Node* cmp  = _gvn.transform(new (C) CmpINode(mbit, bits));
3254  Node* bol  = _gvn.transform(new (C) BoolNode(cmp, BoolTest::ne));
3255  return generate_fair_guard(bol, region);
3256}
3257Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3258  return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);
3259}
3260
3261//-------------------------inline_native_Class_query-------------------
3262bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
3263  const Type* return_type = TypeInt::BOOL;
3264  Node* prim_return_value = top();  // what happens if it's a primitive class?
3265  bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3266  bool expect_prim = false;     // most of these guys expect to work on refs
3267
3268  enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
3269
3270  Node* mirror = argument(0);
3271  Node* obj    = top();
3272
3273  switch (id) {
3274  case vmIntrinsics::_isInstance:
3275    // nothing is an instance of a primitive type
3276    prim_return_value = intcon(0);
3277    obj = argument(1);
3278    break;
3279  case vmIntrinsics::_getModifiers:
3280    prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3281    assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");
3282    return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);
3283    break;
3284  case vmIntrinsics::_isInterface:
3285    prim_return_value = intcon(0);
3286    break;
3287  case vmIntrinsics::_isArray:
3288    prim_return_value = intcon(0);
3289    expect_prim = true;  // cf. ObjectStreamClass.getClassSignature
3290    break;
3291  case vmIntrinsics::_isPrimitive:
3292    prim_return_value = intcon(1);
3293    expect_prim = true;  // obviously
3294    break;
3295  case vmIntrinsics::_getSuperclass:
3296    prim_return_value = null();
3297    return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
3298    break;
3299  case vmIntrinsics::_getComponentType:
3300    prim_return_value = null();
3301    return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
3302    break;
3303  case vmIntrinsics::_getClassAccessFlags:
3304    prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3305    return_type = TypeInt::INT;  // not bool!  6297094
3306    break;
3307  default:
3308    fatal_unexpected_iid(id);
3309    break;
3310  }
3311
3312  const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3313  if (mirror_con == NULL)  return false;  // cannot happen?
3314
3315#ifndef PRODUCT
3316  if (C->print_intrinsics() || C->print_inlining()) {
3317    ciType* k = mirror_con->java_mirror_type();
3318    if (k) {
3319      tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
3320      k->print_name();
3321      tty->cr();
3322    }
3323  }
3324#endif
3325
3326  // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
3327  RegionNode* region = new (C) RegionNode(PATH_LIMIT);
3328  record_for_igvn(region);
3329  PhiNode* phi = new (C) PhiNode(region, return_type);
3330
3331  // The mirror will never be null of Reflection.getClassAccessFlags, however
3332  // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
3333  // if it is. See bug 4774291.
3334
3335  // For Reflection.getClassAccessFlags(), the null check occurs in
3336  // the wrong place; see inline_unsafe_access(), above, for a similar
3337  // situation.
3338  mirror = null_check(mirror);
3339  // If mirror or obj is dead, only null-path is taken.
3340  if (stopped())  return true;
3341
3342  if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
3343
3344  // Now load the mirror's klass metaobject, and null-check it.
3345  // Side-effects region with the control path if the klass is null.
3346  Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
3347  // If kls is null, we have a primitive mirror.
3348  phi->init_req(_prim_path, prim_return_value);
3349  if (stopped()) { set_result(region, phi); return true; }
3350
3351  Node* p;  // handy temp
3352  Node* null_ctl;
3353
3354  // Now that we have the non-null klass, we can perform the real query.
3355  // For constant classes, the query will constant-fold in LoadNode::Value.
3356  Node* query_value = top();
3357  switch (id) {
3358  case vmIntrinsics::_isInstance:
3359    // nothing is an instance of a primitive type
3360    query_value = gen_instanceof(obj, kls);
3361    break;
3362
3363  case vmIntrinsics::_getModifiers:
3364    p = basic_plus_adr(kls, in_bytes(Klass::modifier_flags_offset()));
3365    query_value = make_load(NULL, p, TypeInt::INT, T_INT);
3366    break;
3367
3368  case vmIntrinsics::_isInterface:
3369    // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3370    if (generate_interface_guard(kls, region) != NULL)
3371      // A guard was added.  If the guard is taken, it was an interface.
3372      phi->add_req(intcon(1));
3373    // If we fall through, it's a plain class.
3374    query_value = intcon(0);
3375    break;
3376
3377  case vmIntrinsics::_isArray:
3378    // (To verify this code sequence, check the asserts in JVM_IsArrayClass.)
3379    if (generate_array_guard(kls, region) != NULL)
3380      // A guard was added.  If the guard is taken, it was an array.
3381      phi->add_req(intcon(1));
3382    // If we fall through, it's a plain class.
3383    query_value = intcon(0);
3384    break;
3385
3386  case vmIntrinsics::_isPrimitive:
3387    query_value = intcon(0); // "normal" path produces false
3388    break;
3389
3390  case vmIntrinsics::_getSuperclass:
3391    // The rules here are somewhat unfortunate, but we can still do better
3392    // with random logic than with a JNI call.
3393    // Interfaces store null or Object as _super, but must report null.
3394    // Arrays store an intermediate super as _super, but must report Object.
3395    // Other types can report the actual _super.
3396    // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3397    if (generate_interface_guard(kls, region) != NULL)
3398      // A guard was added.  If the guard is taken, it was an interface.
3399      phi->add_req(null());
3400    if (generate_array_guard(kls, region) != NULL)
3401      // A guard was added.  If the guard is taken, it was an array.
3402      phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
3403    // If we fall through, it's a plain class.  Get its _super.
3404    p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
3405    kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL));
3406    null_ctl = top();
3407    kls = null_check_oop(kls, &null_ctl);
3408    if (null_ctl != top()) {
3409      // If the guard is taken, Object.superClass is null (both klass and mirror).
3410      region->add_req(null_ctl);
3411      phi   ->add_req(null());
3412    }
3413    if (!stopped()) {
3414      query_value = load_mirror_from_klass(kls);
3415    }
3416    break;
3417
3418  case vmIntrinsics::_getComponentType:
3419    if (generate_array_guard(kls, region) != NULL) {
3420      // Be sure to pin the oop load to the guard edge just created:
3421      Node* is_array_ctrl = region->in(region->req()-1);
3422      Node* cma = basic_plus_adr(kls, in_bytes(ArrayKlass::component_mirror_offset()));
3423      Node* cmo = make_load(is_array_ctrl, cma, TypeInstPtr::MIRROR, T_OBJECT);
3424      phi->add_req(cmo);
3425    }
3426    query_value = null();  // non-array case is null
3427    break;
3428
3429  case vmIntrinsics::_getClassAccessFlags:
3430    p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3431    query_value = make_load(NULL, p, TypeInt::INT, T_INT);
3432    break;
3433
3434  default:
3435    fatal_unexpected_iid(id);
3436    break;
3437  }
3438
3439  // Fall-through is the normal case of a query to a real class.
3440  phi->init_req(1, query_value);
3441  region->init_req(1, control());
3442
3443  C->set_has_split_ifs(true); // Has chance for split-if optimization
3444  set_result(region, phi);
3445  return true;
3446}
3447
3448//--------------------------inline_native_subtype_check------------------------
3449// This intrinsic takes the JNI calls out of the heart of
3450// UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
3451bool LibraryCallKit::inline_native_subtype_check() {
3452  // Pull both arguments off the stack.
3453  Node* args[2];                // two java.lang.Class mirrors: superc, subc
3454  args[0] = argument(0);
3455  args[1] = argument(1);
3456  Node* klasses[2];             // corresponding Klasses: superk, subk
3457  klasses[0] = klasses[1] = top();
3458
3459  enum {
3460    // A full decision tree on {superc is prim, subc is prim}:
3461    _prim_0_path = 1,           // {P,N} => false
3462                                // {P,P} & superc!=subc => false
3463    _prim_same_path,            // {P,P} & superc==subc => true
3464    _prim_1_path,               // {N,P} => false
3465    _ref_subtype_path,          // {N,N} & subtype check wins => true
3466    _both_ref_path,             // {N,N} & subtype check loses => false
3467    PATH_LIMIT
3468  };
3469
3470  RegionNode* region = new (C) RegionNode(PATH_LIMIT);
3471  Node*       phi    = new (C) PhiNode(region, TypeInt::BOOL);
3472  record_for_igvn(region);
3473
3474  const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
3475  const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3476  int class_klass_offset = java_lang_Class::klass_offset_in_bytes();
3477
3478  // First null-check both mirrors and load each mirror's klass metaobject.
3479  int which_arg;
3480  for (which_arg = 0; which_arg <= 1; which_arg++) {
3481    Node* arg = args[which_arg];
3482    arg = null_check(arg);
3483    if (stopped())  break;
3484    args[which_arg] = arg;
3485
3486    Node* p = basic_plus_adr(arg, class_klass_offset);
3487    Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
3488    klasses[which_arg] = _gvn.transform(kls);
3489  }
3490
3491  // Having loaded both klasses, test each for null.
3492  bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3493  for (which_arg = 0; which_arg <= 1; which_arg++) {
3494    Node* kls = klasses[which_arg];
3495    Node* null_ctl = top();
3496    kls = null_check_oop(kls, &null_ctl, never_see_null);
3497    int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
3498    region->init_req(prim_path, null_ctl);
3499    if (stopped())  break;
3500    klasses[which_arg] = kls;
3501  }
3502
3503  if (!stopped()) {
3504    // now we have two reference types, in klasses[0..1]
3505    Node* subk   = klasses[1];  // the argument to isAssignableFrom
3506    Node* superk = klasses[0];  // the receiver
3507    region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
3508    // now we have a successful reference subtype check
3509    region->set_req(_ref_subtype_path, control());
3510  }
3511
3512  // If both operands are primitive (both klasses null), then
3513  // we must return true when they are identical primitives.
3514  // It is convenient to test this after the first null klass check.
3515  set_control(region->in(_prim_0_path)); // go back to first null check
3516  if (!stopped()) {
3517    // Since superc is primitive, make a guard for the superc==subc case.
3518    Node* cmp_eq = _gvn.transform(new (C) CmpPNode(args[0], args[1]));
3519    Node* bol_eq = _gvn.transform(new (C) BoolNode(cmp_eq, BoolTest::eq));
3520    generate_guard(bol_eq, region, PROB_FAIR);
3521    if (region->req() == PATH_LIMIT+1) {
3522      // A guard was added.  If the added guard is taken, superc==subc.
3523      region->swap_edges(PATH_LIMIT, _prim_same_path);
3524      region->del_req(PATH_LIMIT);
3525    }
3526    region->set_req(_prim_0_path, control()); // Not equal after all.
3527  }
3528
3529  // these are the only paths that produce 'true':
3530  phi->set_req(_prim_same_path,   intcon(1));
3531  phi->set_req(_ref_subtype_path, intcon(1));
3532
3533  // pull together the cases:
3534  assert(region->req() == PATH_LIMIT, "sane region");
3535  for (uint i = 1; i < region->req(); i++) {
3536    Node* ctl = region->in(i);
3537    if (ctl == NULL || ctl == top()) {
3538      region->set_req(i, top());
3539      phi   ->set_req(i, top());
3540    } else if (phi->in(i) == NULL) {
3541      phi->set_req(i, intcon(0)); // all other paths produce 'false'
3542    }
3543  }
3544
3545  set_control(_gvn.transform(region));
3546  set_result(_gvn.transform(phi));
3547  return true;
3548}
3549
3550//---------------------generate_array_guard_common------------------------
3551Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
3552                                                  bool obj_array, bool not_array) {
3553  // If obj_array/non_array==false/false:
3554  // Branch around if the given klass is in fact an array (either obj or prim).
3555  // If obj_array/non_array==false/true:
3556  // Branch around if the given klass is not an array klass of any kind.
3557  // If obj_array/non_array==true/true:
3558  // Branch around if the kls is not an oop array (kls is int[], String, etc.)
3559  // If obj_array/non_array==true/false:
3560  // Branch around if the kls is an oop array (Object[] or subtype)
3561  //
3562  // Like generate_guard, adds a new path onto the region.
3563  jint  layout_con = 0;
3564  Node* layout_val = get_layout_helper(kls, layout_con);
3565  if (layout_val == NULL) {
3566    bool query = (obj_array
3567                  ? Klass::layout_helper_is_objArray(layout_con)
3568                  : Klass::layout_helper_is_array(layout_con));
3569    if (query == not_array) {
3570      return NULL;                       // never a branch
3571    } else {                             // always a branch
3572      Node* always_branch = control();
3573      if (region != NULL)
3574        region->add_req(always_branch);
3575      set_control(top());
3576      return always_branch;
3577    }
3578  }
3579  // Now test the correct condition.
3580  jint  nval = (obj_array
3581                ? ((jint)Klass::_lh_array_tag_type_value
3582                   <<    Klass::_lh_array_tag_shift)
3583                : Klass::_lh_neutral_value);
3584  Node* cmp = _gvn.transform(new(C) CmpINode(layout_val, intcon(nval)));
3585  BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
3586  // invert the test if we are looking for a non-array
3587  if (not_array)  btest = BoolTest(btest).negate();
3588  Node* bol = _gvn.transform(new(C) BoolNode(cmp, btest));
3589  return generate_fair_guard(bol, region);
3590}
3591
3592
3593//-----------------------inline_native_newArray--------------------------
3594// private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
3595bool LibraryCallKit::inline_native_newArray() {
3596  Node* mirror    = argument(0);
3597  Node* count_val = argument(1);
3598
3599  mirror = null_check(mirror);
3600  // If mirror or obj is dead, only null-path is taken.
3601  if (stopped())  return true;
3602
3603  enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
3604  RegionNode* result_reg = new(C) RegionNode(PATH_LIMIT);
3605  PhiNode*    result_val = new(C) PhiNode(result_reg,
3606                                          TypeInstPtr::NOTNULL);
3607  PhiNode*    result_io  = new(C) PhiNode(result_reg, Type::ABIO);
3608  PhiNode*    result_mem = new(C) PhiNode(result_reg, Type::MEMORY,
3609                                          TypePtr::BOTTOM);
3610
3611  bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3612  Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
3613                                                  result_reg, _slow_path);
3614  Node* normal_ctl   = control();
3615  Node* no_array_ctl = result_reg->in(_slow_path);
3616
3617  // Generate code for the slow case.  We make a call to newArray().
3618  set_control(no_array_ctl);
3619  if (!stopped()) {
3620    // Either the input type is void.class, or else the
3621    // array klass has not yet been cached.  Either the
3622    // ensuing call will throw an exception, or else it
3623    // will cache the array klass for next time.
3624    PreserveJVMState pjvms(this);
3625    CallJavaNode* slow_call = generate_method_call_static(vmIntrinsics::_newArray);
3626    Node* slow_result = set_results_for_java_call(slow_call);
3627    // this->control() comes from set_results_for_java_call
3628    result_reg->set_req(_slow_path, control());
3629    result_val->set_req(_slow_path, slow_result);
3630    result_io ->set_req(_slow_path, i_o());
3631    result_mem->set_req(_slow_path, reset_memory());
3632  }
3633
3634  set_control(normal_ctl);
3635  if (!stopped()) {
3636    // Normal case:  The array type has been cached in the java.lang.Class.
3637    // The following call works fine even if the array type is polymorphic.
3638    // It could be a dynamic mix of int[], boolean[], Object[], etc.
3639    Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
3640    result_reg->init_req(_normal_path, control());
3641    result_val->init_req(_normal_path, obj);
3642    result_io ->init_req(_normal_path, i_o());
3643    result_mem->init_req(_normal_path, reset_memory());
3644  }
3645
3646  // Return the combined state.
3647  set_i_o(        _gvn.transform(result_io)  );
3648  set_all_memory( _gvn.transform(result_mem));
3649
3650  C->set_has_split_ifs(true); // Has chance for split-if optimization
3651  set_result(result_reg, result_val);
3652  return true;
3653}
3654
3655//----------------------inline_native_getLength--------------------------
3656// public static native int java.lang.reflect.Array.getLength(Object array);
3657bool LibraryCallKit::inline_native_getLength() {
3658  if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3659
3660  Node* array = null_check(argument(0));
3661  // If array is dead, only null-path is taken.
3662  if (stopped())  return true;
3663
3664  // Deoptimize if it is a non-array.
3665  Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);
3666
3667  if (non_array != NULL) {
3668    PreserveJVMState pjvms(this);
3669    set_control(non_array);
3670    uncommon_trap(Deoptimization::Reason_intrinsic,
3671                  Deoptimization::Action_maybe_recompile);
3672  }
3673
3674  // If control is dead, only non-array-path is taken.
3675  if (stopped())  return true;
3676
3677  // The works fine even if the array type is polymorphic.
3678  // It could be a dynamic mix of int[], boolean[], Object[], etc.
3679  Node* result = load_array_length(array);
3680
3681  C->set_has_split_ifs(true);  // Has chance for split-if optimization
3682  set_result(result);
3683  return true;
3684}
3685
3686//------------------------inline_array_copyOf----------------------------
3687// public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
3688// public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
3689bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
3690  if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3691
3692  // Get the arguments.
3693  Node* original          = argument(0);
3694  Node* start             = is_copyOfRange? argument(1): intcon(0);
3695  Node* end               = is_copyOfRange? argument(2): argument(1);
3696  Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
3697
3698  Node* newcopy;
3699
3700  // Set the original stack and the reexecute bit for the interpreter to reexecute
3701  // the bytecode that invokes Arrays.copyOf if deoptimization happens.
3702  { PreserveReexecuteState preexecs(this);
3703    jvms()->set_should_reexecute(true);
3704
3705    array_type_mirror = null_check(array_type_mirror);
3706    original          = null_check(original);
3707
3708    // Check if a null path was taken unconditionally.
3709    if (stopped())  return true;
3710
3711    Node* orig_length = load_array_length(original);
3712
3713    Node* klass_node = load_klass_from_mirror(array_type_mirror, false, NULL, 0);
3714    klass_node = null_check(klass_node);
3715
3716    RegionNode* bailout = new (C) RegionNode(1);
3717    record_for_igvn(bailout);
3718
3719    // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
3720    // Bail out if that is so.
3721    Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
3722    if (not_objArray != NULL) {
3723      // Improve the klass node's type from the new optimistic assumption:
3724      ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
3725      const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
3726      Node* cast = new (C) CastPPNode(klass_node, akls);
3727      cast->init_req(0, control());
3728      klass_node = _gvn.transform(cast);
3729    }
3730
3731    // Bail out if either start or end is negative.
3732    generate_negative_guard(start, bailout, &start);
3733    generate_negative_guard(end,   bailout, &end);
3734
3735    Node* length = end;
3736    if (_gvn.type(start) != TypeInt::ZERO) {
3737      length = _gvn.transform(new (C) SubINode(end, start));
3738    }
3739
3740    // Bail out if length is negative.
3741    // Without this the new_array would throw
3742    // NegativeArraySizeException but IllegalArgumentException is what
3743    // should be thrown
3744    generate_negative_guard(length, bailout, &length);
3745
3746    if (bailout->req() > 1) {
3747      PreserveJVMState pjvms(this);
3748      set_control(_gvn.transform(bailout));
3749      uncommon_trap(Deoptimization::Reason_intrinsic,
3750                    Deoptimization::Action_maybe_recompile);
3751    }
3752
3753    if (!stopped()) {
3754      // How many elements will we copy from the original?
3755      // The answer is MinI(orig_length - start, length).
3756      Node* orig_tail = _gvn.transform(new (C) SubINode(orig_length, start));
3757      Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
3758
3759      newcopy = new_array(klass_node, length, 0);  // no argments to push
3760
3761      // Generate a direct call to the right arraycopy function(s).
3762      // We know the copy is disjoint but we might not know if the
3763      // oop stores need checking.
3764      // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
3765      // This will fail a store-check if x contains any non-nulls.
3766      bool disjoint_bases = true;
3767      // if start > orig_length then the length of the copy may be
3768      // negative.
3769      bool length_never_negative = !is_copyOfRange;
3770      generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,
3771                         original, start, newcopy, intcon(0), moved,
3772                         disjoint_bases, length_never_negative);
3773    }
3774  } // original reexecute is set back here
3775
3776  C->set_has_split_ifs(true); // Has chance for split-if optimization
3777  if (!stopped()) {
3778    set_result(newcopy);
3779  }
3780  return true;
3781}
3782
3783
3784//----------------------generate_virtual_guard---------------------------
3785// Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
3786Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
3787                                             RegionNode* slow_region) {
3788  ciMethod* method = callee();
3789  int vtable_index = method->vtable_index();
3790  assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
3791         err_msg_res("bad index %d", vtable_index));
3792  // Get the Method* out of the appropriate vtable entry.
3793  int entry_offset  = (InstanceKlass::vtable_start_offset() +
3794                     vtable_index*vtableEntry::size()) * wordSize +
3795                     vtableEntry::method_offset_in_bytes();
3796  Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
3797  Node* target_call = make_load(NULL, entry_addr, TypePtr::NOTNULL, T_ADDRESS);
3798
3799  // Compare the target method with the expected method (e.g., Object.hashCode).
3800  const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
3801
3802  Node* native_call = makecon(native_call_addr);
3803  Node* chk_native  = _gvn.transform(new(C) CmpPNode(target_call, native_call));
3804  Node* test_native = _gvn.transform(new(C) BoolNode(chk_native, BoolTest::ne));
3805
3806  return generate_slow_guard(test_native, slow_region);
3807}
3808
3809//-----------------------generate_method_call----------------------------
3810// Use generate_method_call to make a slow-call to the real
3811// method if the fast path fails.  An alternative would be to
3812// use a stub like OptoRuntime::slow_arraycopy_Java.
3813// This only works for expanding the current library call,
3814// not another intrinsic.  (E.g., don't use this for making an
3815// arraycopy call inside of the copyOf intrinsic.)
3816CallJavaNode*
3817LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {
3818  // When compiling the intrinsic method itself, do not use this technique.
3819  guarantee(callee() != C->method(), "cannot make slow-call to self");
3820
3821  ciMethod* method = callee();
3822  // ensure the JVMS we have will be correct for this call
3823  guarantee(method_id == method->intrinsic_id(), "must match");
3824
3825  const TypeFunc* tf = TypeFunc::make(method);
3826  CallJavaNode* slow_call;
3827  if (is_static) {
3828    assert(!is_virtual, "");
3829    slow_call = new(C) CallStaticJavaNode(C, tf,
3830                           SharedRuntime::get_resolve_static_call_stub(),
3831                           method, bci());
3832  } else if (is_virtual) {
3833    null_check_receiver();
3834    int vtable_index = Method::invalid_vtable_index;
3835    if (UseInlineCaches) {
3836      // Suppress the vtable call
3837    } else {
3838      // hashCode and clone are not a miranda methods,
3839      // so the vtable index is fixed.
3840      // No need to use the linkResolver to get it.
3841       vtable_index = method->vtable_index();
3842       assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
3843              err_msg_res("bad index %d", vtable_index));
3844    }
3845    slow_call = new(C) CallDynamicJavaNode(tf,
3846                          SharedRuntime::get_resolve_virtual_call_stub(),
3847                          method, vtable_index, bci());
3848  } else {  // neither virtual nor static:  opt_virtual
3849    null_check_receiver();
3850    slow_call = new(C) CallStaticJavaNode(C, tf,
3851                                SharedRuntime::get_resolve_opt_virtual_call_stub(),
3852                                method, bci());
3853    slow_call->set_optimized_virtual(true);
3854  }
3855  set_arguments_for_java_call(slow_call);
3856  set_edges_for_java_call(slow_call);
3857  return slow_call;
3858}
3859
3860
3861//------------------------------inline_native_hashcode--------------------
3862// Build special case code for calls to hashCode on an object.
3863bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
3864  assert(is_static == callee()->is_static(), "correct intrinsic selection");
3865  assert(!(is_virtual && is_static), "either virtual, special, or static");
3866
3867  enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
3868
3869  RegionNode* result_reg = new(C) RegionNode(PATH_LIMIT);
3870  PhiNode*    result_val = new(C) PhiNode(result_reg,
3871                                          TypeInt::INT);
3872  PhiNode*    result_io  = new(C) PhiNode(result_reg, Type::ABIO);
3873  PhiNode*    result_mem = new(C) PhiNode(result_reg, Type::MEMORY,
3874                                          TypePtr::BOTTOM);
3875  Node* obj = NULL;
3876  if (!is_static) {
3877    // Check for hashing null object
3878    obj = null_check_receiver();
3879    if (stopped())  return true;        // unconditionally null
3880    result_reg->init_req(_null_path, top());
3881    result_val->init_req(_null_path, top());
3882  } else {
3883    // Do a null check, and return zero if null.
3884    // System.identityHashCode(null) == 0
3885    obj = argument(0);
3886    Node* null_ctl = top();
3887    obj = null_check_oop(obj, &null_ctl);
3888    result_reg->init_req(_null_path, null_ctl);
3889    result_val->init_req(_null_path, _gvn.intcon(0));
3890  }
3891
3892  // Unconditionally null?  Then return right away.
3893  if (stopped()) {
3894    set_control( result_reg->in(_null_path));
3895    if (!stopped())
3896      set_result(result_val->in(_null_path));
3897    return true;
3898  }
3899
3900  // After null check, get the object's klass.
3901  Node* obj_klass = load_object_klass(obj);
3902
3903  // This call may be virtual (invokevirtual) or bound (invokespecial).
3904  // For each case we generate slightly different code.
3905
3906  // We only go to the fast case code if we pass a number of guards.  The
3907  // paths which do not pass are accumulated in the slow_region.
3908  RegionNode* slow_region = new (C) RegionNode(1);
3909  record_for_igvn(slow_region);
3910
3911  // If this is a virtual call, we generate a funny guard.  We pull out
3912  // the vtable entry corresponding to hashCode() from the target object.
3913  // If the target method which we are calling happens to be the native
3914  // Object hashCode() method, we pass the guard.  We do not need this
3915  // guard for non-virtual calls -- the caller is known to be the native
3916  // Object hashCode().
3917  if (is_virtual) {
3918    generate_virtual_guard(obj_klass, slow_region);
3919  }
3920
3921  // Get the header out of the object, use LoadMarkNode when available
3922  Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
3923  Node* header = make_load(control(), header_addr, TypeX_X, TypeX_X->basic_type());
3924
3925  // Test the header to see if it is unlocked.
3926  Node *lock_mask      = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place);
3927  Node *lmasked_header = _gvn.transform(new (C) AndXNode(header, lock_mask));
3928  Node *unlocked_val   = _gvn.MakeConX(markOopDesc::unlocked_value);
3929  Node *chk_unlocked   = _gvn.transform(new (C) CmpXNode( lmasked_header, unlocked_val));
3930  Node *test_unlocked  = _gvn.transform(new (C) BoolNode( chk_unlocked, BoolTest::ne));
3931
3932  generate_slow_guard(test_unlocked, slow_region);
3933
3934  // Get the hash value and check to see that it has been properly assigned.
3935  // We depend on hash_mask being at most 32 bits and avoid the use of
3936  // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
3937  // vm: see markOop.hpp.
3938  Node *hash_mask      = _gvn.intcon(markOopDesc::hash_mask);
3939  Node *hash_shift     = _gvn.intcon(markOopDesc::hash_shift);
3940  Node *hshifted_header= _gvn.transform(new (C) URShiftXNode(header, hash_shift));
3941  // This hack lets the hash bits live anywhere in the mark object now, as long
3942  // as the shift drops the relevant bits into the low 32 bits.  Note that
3943  // Java spec says that HashCode is an int so there's no point in capturing
3944  // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
3945  hshifted_header      = ConvX2I(hshifted_header);
3946  Node *hash_val       = _gvn.transform(new (C) AndINode(hshifted_header, hash_mask));
3947
3948  Node *no_hash_val    = _gvn.intcon(markOopDesc::no_hash);
3949  Node *chk_assigned   = _gvn.transform(new (C) CmpINode( hash_val, no_hash_val));
3950  Node *test_assigned  = _gvn.transform(new (C) BoolNode( chk_assigned, BoolTest::eq));
3951
3952  generate_slow_guard(test_assigned, slow_region);
3953
3954  Node* init_mem = reset_memory();
3955  // fill in the rest of the null path:
3956  result_io ->init_req(_null_path, i_o());
3957  result_mem->init_req(_null_path, init_mem);
3958
3959  result_val->init_req(_fast_path, hash_val);
3960  result_reg->init_req(_fast_path, control());
3961  result_io ->init_req(_fast_path, i_o());
3962  result_mem->init_req(_fast_path, init_mem);
3963
3964  // Generate code for the slow case.  We make a call to hashCode().
3965  set_control(_gvn.transform(slow_region));
3966  if (!stopped()) {
3967    // No need for PreserveJVMState, because we're using up the present state.
3968    set_all_memory(init_mem);
3969    vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
3970    CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);
3971    Node* slow_result = set_results_for_java_call(slow_call);
3972    // this->control() comes from set_results_for_java_call
3973    result_reg->init_req(_slow_path, control());
3974    result_val->init_req(_slow_path, slow_result);
3975    result_io  ->set_req(_slow_path, i_o());
3976    result_mem ->set_req(_slow_path, reset_memory());
3977  }
3978
3979  // Return the combined state.
3980  set_i_o(        _gvn.transform(result_io)  );
3981  set_all_memory( _gvn.transform(result_mem));
3982
3983  set_result(result_reg, result_val);
3984  return true;
3985}
3986
3987//---------------------------inline_native_getClass----------------------------
3988// public final native Class<?> java.lang.Object.getClass();
3989//
3990// Build special case code for calls to getClass on an object.
3991bool LibraryCallKit::inline_native_getClass() {
3992  Node* obj = null_check_receiver();
3993  if (stopped())  return true;
3994  set_result(load_mirror_from_klass(load_object_klass(obj)));
3995  return true;
3996}
3997
3998//-----------------inline_native_Reflection_getCallerClass---------------------
3999// public static native Class<?> sun.reflect.Reflection.getCallerClass();
4000//
4001// In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4002//
4003// NOTE: This code must perform the same logic as JVM_GetCallerClass
4004// in that it must skip particular security frames and checks for
4005// caller sensitive methods.
4006bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4007#ifndef PRODUCT
4008  if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4009    tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4010  }
4011#endif
4012
4013  if (!jvms()->has_method()) {
4014#ifndef PRODUCT
4015    if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4016      tty->print_cr("  Bailing out because intrinsic was inlined at top level");
4017    }
4018#endif
4019    return false;
4020  }
4021
4022  // Walk back up the JVM state to find the caller at the required
4023  // depth.
4024  JVMState* caller_jvms = jvms();
4025
4026  // Cf. JVM_GetCallerClass
4027  // NOTE: Start the loop at depth 1 because the current JVM state does
4028  // not include the Reflection.getCallerClass() frame.
4029  for (int n = 1; caller_jvms != NULL; caller_jvms = caller_jvms->caller(), n++) {
4030    ciMethod* m = caller_jvms->method();
4031    switch (n) {
4032    case 0:
4033      fatal("current JVM state does not include the Reflection.getCallerClass frame");
4034      break;
4035    case 1:
4036      // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
4037      if (!m->caller_sensitive()) {
4038#ifndef PRODUCT
4039        if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4040          tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
4041        }
4042#endif
4043        return false;  // bail-out; let JVM_GetCallerClass do the work
4044      }
4045      break;
4046    default:
4047      if (!m->is_ignored_by_security_stack_walk()) {
4048        // We have reached the desired frame; return the holder class.
4049        // Acquire method holder as java.lang.Class and push as constant.
4050        ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
4051        ciInstance* caller_mirror = caller_klass->java_mirror();
4052        set_result(makecon(TypeInstPtr::make(caller_mirror)));
4053
4054#ifndef PRODUCT
4055        if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4056          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());
4057          tty->print_cr("  JVM state at this point:");
4058          for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4059            ciMethod* m = jvms()->of_depth(i)->method();
4060            tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4061          }
4062        }
4063#endif
4064        return true;
4065      }
4066      break;
4067    }
4068  }
4069
4070#ifndef PRODUCT
4071  if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4072    tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
4073    tty->print_cr("  JVM state at this point:");
4074    for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4075      ciMethod* m = jvms()->of_depth(i)->method();
4076      tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4077    }
4078  }
4079#endif
4080
4081  return false;  // bail-out; let JVM_GetCallerClass do the work
4082}
4083
4084bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
4085  Node* arg = argument(0);
4086  Node* result;
4087
4088  switch (id) {
4089  case vmIntrinsics::_floatToRawIntBits:    result = new (C) MoveF2INode(arg);  break;
4090  case vmIntrinsics::_intBitsToFloat:       result = new (C) MoveI2FNode(arg);  break;
4091  case vmIntrinsics::_doubleToRawLongBits:  result = new (C) MoveD2LNode(arg);  break;
4092  case vmIntrinsics::_longBitsToDouble:     result = new (C) MoveL2DNode(arg);  break;
4093
4094  case vmIntrinsics::_doubleToLongBits: {
4095    // two paths (plus control) merge in a wood
4096    RegionNode *r = new (C) RegionNode(3);
4097    Node *phi = new (C) PhiNode(r, TypeLong::LONG);
4098
4099    Node *cmpisnan = _gvn.transform(new (C) CmpDNode(arg, arg));
4100    // Build the boolean node
4101    Node *bolisnan = _gvn.transform(new (C) BoolNode(cmpisnan, BoolTest::ne));
4102
4103    // Branch either way.
4104    // NaN case is less traveled, which makes all the difference.
4105    IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4106    Node *opt_isnan = _gvn.transform(ifisnan);
4107    assert( opt_isnan->is_If(), "Expect an IfNode");
4108    IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4109    Node *iftrue = _gvn.transform(new (C) IfTrueNode(opt_ifisnan));
4110
4111    set_control(iftrue);
4112
4113    static const jlong nan_bits = CONST64(0x7ff8000000000000);
4114    Node *slow_result = longcon(nan_bits); // return NaN
4115    phi->init_req(1, _gvn.transform( slow_result ));
4116    r->init_req(1, iftrue);
4117
4118    // Else fall through
4119    Node *iffalse = _gvn.transform(new (C) IfFalseNode(opt_ifisnan));
4120    set_control(iffalse);
4121
4122    phi->init_req(2, _gvn.transform(new (C) MoveD2LNode(arg)));
4123    r->init_req(2, iffalse);
4124
4125    // Post merge
4126    set_control(_gvn.transform(r));
4127    record_for_igvn(r);
4128
4129    C->set_has_split_ifs(true); // Has chance for split-if optimization
4130    result = phi;
4131    assert(result->bottom_type()->isa_long(), "must be");
4132    break;
4133  }
4134
4135  case vmIntrinsics::_floatToIntBits: {
4136    // two paths (plus control) merge in a wood
4137    RegionNode *r = new (C) RegionNode(3);
4138    Node *phi = new (C) PhiNode(r, TypeInt::INT);
4139
4140    Node *cmpisnan = _gvn.transform(new (C) CmpFNode(arg, arg));
4141    // Build the boolean node
4142    Node *bolisnan = _gvn.transform(new (C) BoolNode(cmpisnan, BoolTest::ne));
4143
4144    // Branch either way.
4145    // NaN case is less traveled, which makes all the difference.
4146    IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4147    Node *opt_isnan = _gvn.transform(ifisnan);
4148    assert( opt_isnan->is_If(), "Expect an IfNode");
4149    IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4150    Node *iftrue = _gvn.transform(new (C) IfTrueNode(opt_ifisnan));
4151
4152    set_control(iftrue);
4153
4154    static const jint nan_bits = 0x7fc00000;
4155    Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
4156    phi->init_req(1, _gvn.transform( slow_result ));
4157    r->init_req(1, iftrue);
4158
4159    // Else fall through
4160    Node *iffalse = _gvn.transform(new (C) IfFalseNode(opt_ifisnan));
4161    set_control(iffalse);
4162
4163    phi->init_req(2, _gvn.transform(new (C) MoveF2INode(arg)));
4164    r->init_req(2, iffalse);
4165
4166    // Post merge
4167    set_control(_gvn.transform(r));
4168    record_for_igvn(r);
4169
4170    C->set_has_split_ifs(true); // Has chance for split-if optimization
4171    result = phi;
4172    assert(result->bottom_type()->isa_int(), "must be");
4173    break;
4174  }
4175
4176  default:
4177    fatal_unexpected_iid(id);
4178    break;
4179  }
4180  set_result(_gvn.transform(result));
4181  return true;
4182}
4183
4184#ifdef _LP64
4185#define XTOP ,top() /*additional argument*/
4186#else  //_LP64
4187#define XTOP        /*no additional argument*/
4188#endif //_LP64
4189
4190//----------------------inline_unsafe_copyMemory-------------------------
4191// public native void sun.misc.Unsafe.copyMemory(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
4192bool LibraryCallKit::inline_unsafe_copyMemory() {
4193  if (callee()->is_static())  return false;  // caller must have the capability!
4194  null_check_receiver();  // null-check receiver
4195  if (stopped())  return true;
4196
4197  C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
4198
4199  Node* src_ptr =         argument(1);   // type: oop
4200  Node* src_off = ConvL2X(argument(2));  // type: long
4201  Node* dst_ptr =         argument(4);   // type: oop
4202  Node* dst_off = ConvL2X(argument(5));  // type: long
4203  Node* size    = ConvL2X(argument(7));  // type: long
4204
4205  assert(Unsafe_field_offset_to_byte_offset(11) == 11,
4206         "fieldOffset must be byte-scaled");
4207
4208  Node* src = make_unsafe_address(src_ptr, src_off);
4209  Node* dst = make_unsafe_address(dst_ptr, dst_off);
4210
4211  // Conservatively insert a memory barrier on all memory slices.
4212  // Do not let writes of the copy source or destination float below the copy.
4213  insert_mem_bar(Op_MemBarCPUOrder);
4214
4215  // Call it.  Note that the length argument is not scaled.
4216  make_runtime_call(RC_LEAF|RC_NO_FP,
4217                    OptoRuntime::fast_arraycopy_Type(),
4218                    StubRoutines::unsafe_arraycopy(),
4219                    "unsafe_arraycopy",
4220                    TypeRawPtr::BOTTOM,
4221                    src, dst, size XTOP);
4222
4223  // Do not let reads of the copy destination float above the copy.
4224  insert_mem_bar(Op_MemBarCPUOrder);
4225
4226  return true;
4227}
4228
4229//------------------------clone_coping-----------------------------------
4230// Helper function for inline_native_clone.
4231void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark) {
4232  assert(obj_size != NULL, "");
4233  Node* raw_obj = alloc_obj->in(1);
4234  assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
4235
4236  AllocateNode* alloc = NULL;
4237  if (ReduceBulkZeroing) {
4238    // We will be completely responsible for initializing this object -
4239    // mark Initialize node as complete.
4240    alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
4241    // The object was just allocated - there should be no any stores!
4242    guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");
4243    // Mark as complete_with_arraycopy so that on AllocateNode
4244    // expansion, we know this AllocateNode is initialized by an array
4245    // copy and a StoreStore barrier exists after the array copy.
4246    alloc->initialization()->set_complete_with_arraycopy();
4247  }
4248
4249  // Copy the fastest available way.
4250  // TODO: generate fields copies for small objects instead.
4251  Node* src  = obj;
4252  Node* dest = alloc_obj;
4253  Node* size = _gvn.transform(obj_size);
4254
4255  // Exclude the header but include array length to copy by 8 bytes words.
4256  // Can't use base_offset_in_bytes(bt) since basic type is unknown.
4257  int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :
4258                            instanceOopDesc::base_offset_in_bytes();
4259  // base_off:
4260  // 8  - 32-bit VM
4261  // 12 - 64-bit VM, compressed klass
4262  // 16 - 64-bit VM, normal klass
4263  if (base_off % BytesPerLong != 0) {
4264    assert(UseCompressedClassPointers, "");
4265    if (is_array) {
4266      // Exclude length to copy by 8 bytes words.
4267      base_off += sizeof(int);
4268    } else {
4269      // Include klass to copy by 8 bytes words.
4270      base_off = instanceOopDesc::klass_offset_in_bytes();
4271    }
4272    assert(base_off % BytesPerLong == 0, "expect 8 bytes alignment");
4273  }
4274  src  = basic_plus_adr(src,  base_off);
4275  dest = basic_plus_adr(dest, base_off);
4276
4277  // Compute the length also, if needed:
4278  Node* countx = size;
4279  countx = _gvn.transform(new (C) SubXNode(countx, MakeConX(base_off)));
4280  countx = _gvn.transform(new (C) URShiftXNode(countx, intcon(LogBytesPerLong) ));
4281
4282  const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4283  bool disjoint_bases = true;
4284  generate_unchecked_arraycopy(raw_adr_type, T_LONG, disjoint_bases,
4285                               src, NULL, dest, NULL, countx,
4286                               /*dest_uninitialized*/true);
4287
4288  // If necessary, emit some card marks afterwards.  (Non-arrays only.)
4289  if (card_mark) {
4290    assert(!is_array, "");
4291    // Put in store barrier for any and all oops we are sticking
4292    // into this object.  (We could avoid this if we could prove
4293    // that the object type contains no oop fields at all.)
4294    Node* no_particular_value = NULL;
4295    Node* no_particular_field = NULL;
4296    int raw_adr_idx = Compile::AliasIdxRaw;
4297    post_barrier(control(),
4298                 memory(raw_adr_type),
4299                 alloc_obj,
4300                 no_particular_field,
4301                 raw_adr_idx,
4302                 no_particular_value,
4303                 T_OBJECT,
4304                 false);
4305  }
4306
4307  // Do not let reads from the cloned object float above the arraycopy.
4308  if (alloc != NULL) {
4309    // Do not let stores that initialize this object be reordered with
4310    // a subsequent store that would make this object accessible by
4311    // other threads.
4312    // Record what AllocateNode this StoreStore protects so that
4313    // escape analysis can go from the MemBarStoreStoreNode to the
4314    // AllocateNode and eliminate the MemBarStoreStoreNode if possible
4315    // based on the escape status of the AllocateNode.
4316    insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
4317  } else {
4318    insert_mem_bar(Op_MemBarCPUOrder);
4319  }
4320}
4321
4322//------------------------inline_native_clone----------------------------
4323// protected native Object java.lang.Object.clone();
4324//
4325// Here are the simple edge cases:
4326//  null receiver => normal trap
4327//  virtual and clone was overridden => slow path to out-of-line clone
4328//  not cloneable or finalizer => slow path to out-of-line Object.clone
4329//
4330// The general case has two steps, allocation and copying.
4331// Allocation has two cases, and uses GraphKit::new_instance or new_array.
4332//
4333// Copying also has two cases, oop arrays and everything else.
4334// Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
4335// Everything else uses the tight inline loop supplied by CopyArrayNode.
4336//
4337// These steps fold up nicely if and when the cloned object's klass
4338// can be sharply typed as an object array, a type array, or an instance.
4339//
4340bool LibraryCallKit::inline_native_clone(bool is_virtual) {
4341  PhiNode* result_val;
4342
4343  // Set the reexecute bit for the interpreter to reexecute
4344  // the bytecode that invokes Object.clone if deoptimization happens.
4345  { PreserveReexecuteState preexecs(this);
4346    jvms()->set_should_reexecute(true);
4347
4348    Node* obj = null_check_receiver();
4349    if (stopped())  return true;
4350
4351    Node* obj_klass = load_object_klass(obj);
4352    const TypeKlassPtr* tklass = _gvn.type(obj_klass)->isa_klassptr();
4353    const TypeOopPtr*   toop   = ((tklass != NULL)
4354                                ? tklass->as_instance_type()
4355                                : TypeInstPtr::NOTNULL);
4356
4357    // Conservatively insert a memory barrier on all memory slices.
4358    // Do not let writes into the original float below the clone.
4359    insert_mem_bar(Op_MemBarCPUOrder);
4360
4361    // paths into result_reg:
4362    enum {
4363      _slow_path = 1,     // out-of-line call to clone method (virtual or not)
4364      _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
4365      _array_path,        // plain array allocation, plus arrayof_long_arraycopy
4366      _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
4367      PATH_LIMIT
4368    };
4369    RegionNode* result_reg = new(C) RegionNode(PATH_LIMIT);
4370    result_val             = new(C) PhiNode(result_reg,
4371                                            TypeInstPtr::NOTNULL);
4372    PhiNode*    result_i_o = new(C) PhiNode(result_reg, Type::ABIO);
4373    PhiNode*    result_mem = new(C) PhiNode(result_reg, Type::MEMORY,
4374                                            TypePtr::BOTTOM);
4375    record_for_igvn(result_reg);
4376
4377    const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4378    int raw_adr_idx = Compile::AliasIdxRaw;
4379
4380    Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);
4381    if (array_ctl != NULL) {
4382      // It's an array.
4383      PreserveJVMState pjvms(this);
4384      set_control(array_ctl);
4385      Node* obj_length = load_array_length(obj);
4386      Node* obj_size  = NULL;
4387      Node* alloc_obj = new_array(obj_klass, obj_length, 0, &obj_size);  // no arguments to push
4388
4389      if (!use_ReduceInitialCardMarks()) {
4390        // If it is an oop array, it requires very special treatment,
4391        // because card marking is required on each card of the array.
4392        Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);
4393        if (is_obja != NULL) {
4394          PreserveJVMState pjvms2(this);
4395          set_control(is_obja);
4396          // Generate a direct call to the right arraycopy function(s).
4397          bool disjoint_bases = true;
4398          bool length_never_negative = true;
4399          generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,
4400                             obj, intcon(0), alloc_obj, intcon(0),
4401                             obj_length,
4402                             disjoint_bases, length_never_negative);
4403          result_reg->init_req(_objArray_path, control());
4404          result_val->init_req(_objArray_path, alloc_obj);
4405          result_i_o ->set_req(_objArray_path, i_o());
4406          result_mem ->set_req(_objArray_path, reset_memory());
4407        }
4408      }
4409      // Otherwise, there are no card marks to worry about.
4410      // (We can dispense with card marks if we know the allocation
4411      //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
4412      //  causes the non-eden paths to take compensating steps to
4413      //  simulate a fresh allocation, so that no further
4414      //  card marks are required in compiled code to initialize
4415      //  the object.)
4416
4417      if (!stopped()) {
4418        copy_to_clone(obj, alloc_obj, obj_size, true, false);
4419
4420        // Present the results of the copy.
4421        result_reg->init_req(_array_path, control());
4422        result_val->init_req(_array_path, alloc_obj);
4423        result_i_o ->set_req(_array_path, i_o());
4424        result_mem ->set_req(_array_path, reset_memory());
4425      }
4426    }
4427
4428    // We only go to the instance fast case code if we pass a number of guards.
4429    // The paths which do not pass are accumulated in the slow_region.
4430    RegionNode* slow_region = new (C) RegionNode(1);
4431    record_for_igvn(slow_region);
4432    if (!stopped()) {
4433      // It's an instance (we did array above).  Make the slow-path tests.
4434      // If this is a virtual call, we generate a funny guard.  We grab
4435      // the vtable entry corresponding to clone() from the target object.
4436      // If the target method which we are calling happens to be the
4437      // Object clone() method, we pass the guard.  We do not need this
4438      // guard for non-virtual calls; the caller is known to be the native
4439      // Object clone().
4440      if (is_virtual) {
4441        generate_virtual_guard(obj_klass, slow_region);
4442      }
4443
4444      // The object must be cloneable and must not have a finalizer.
4445      // Both of these conditions may be checked in a single test.
4446      // We could optimize the cloneable test further, but we don't care.
4447      generate_access_flags_guard(obj_klass,
4448                                  // Test both conditions:
4449                                  JVM_ACC_IS_CLONEABLE | JVM_ACC_HAS_FINALIZER,
4450                                  // Must be cloneable but not finalizer:
4451                                  JVM_ACC_IS_CLONEABLE,
4452                                  slow_region);
4453    }
4454
4455    if (!stopped()) {
4456      // It's an instance, and it passed the slow-path tests.
4457      PreserveJVMState pjvms(this);
4458      Node* obj_size  = NULL;
4459      Node* alloc_obj = new_instance(obj_klass, NULL, &obj_size);
4460
4461      copy_to_clone(obj, alloc_obj, obj_size, false, !use_ReduceInitialCardMarks());
4462
4463      // Present the results of the slow call.
4464      result_reg->init_req(_instance_path, control());
4465      result_val->init_req(_instance_path, alloc_obj);
4466      result_i_o ->set_req(_instance_path, i_o());
4467      result_mem ->set_req(_instance_path, reset_memory());
4468    }
4469
4470    // Generate code for the slow case.  We make a call to clone().
4471    set_control(_gvn.transform(slow_region));
4472    if (!stopped()) {
4473      PreserveJVMState pjvms(this);
4474      CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);
4475      Node* slow_result = set_results_for_java_call(slow_call);
4476      // this->control() comes from set_results_for_java_call
4477      result_reg->init_req(_slow_path, control());
4478      result_val->init_req(_slow_path, slow_result);
4479      result_i_o ->set_req(_slow_path, i_o());
4480      result_mem ->set_req(_slow_path, reset_memory());
4481    }
4482
4483    // Return the combined state.
4484    set_control(    _gvn.transform(result_reg));
4485    set_i_o(        _gvn.transform(result_i_o));
4486    set_all_memory( _gvn.transform(result_mem));
4487  } // original reexecute is set back here
4488
4489  set_result(_gvn.transform(result_val));
4490  return true;
4491}
4492
4493//------------------------------basictype2arraycopy----------------------------
4494address LibraryCallKit::basictype2arraycopy(BasicType t,
4495                                            Node* src_offset,
4496                                            Node* dest_offset,
4497                                            bool disjoint_bases,
4498                                            const char* &name,
4499                                            bool dest_uninitialized) {
4500  const TypeInt* src_offset_inttype  = gvn().find_int_type(src_offset);;
4501  const TypeInt* dest_offset_inttype = gvn().find_int_type(dest_offset);;
4502
4503  bool aligned = false;
4504  bool disjoint = disjoint_bases;
4505
4506  // if the offsets are the same, we can treat the memory regions as
4507  // disjoint, because either the memory regions are in different arrays,
4508  // or they are identical (which we can treat as disjoint.)  We can also
4509  // treat a copy with a destination index  less that the source index
4510  // as disjoint since a low->high copy will work correctly in this case.
4511  if (src_offset_inttype != NULL && src_offset_inttype->is_con() &&
4512      dest_offset_inttype != NULL && dest_offset_inttype->is_con()) {
4513    // both indices are constants
4514    int s_offs = src_offset_inttype->get_con();
4515    int d_offs = dest_offset_inttype->get_con();
4516    int element_size = type2aelembytes(t);
4517    aligned = ((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) &&
4518              ((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0);
4519    if (s_offs >= d_offs)  disjoint = true;
4520  } else if (src_offset == dest_offset && src_offset != NULL) {
4521    // This can occur if the offsets are identical non-constants.
4522    disjoint = true;
4523  }
4524
4525  return StubRoutines::select_arraycopy_function(t, aligned, disjoint, name, dest_uninitialized);
4526}
4527
4528
4529//------------------------------inline_arraycopy-----------------------
4530// public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
4531//                                                      Object dest, int destPos,
4532//                                                      int length);
4533bool LibraryCallKit::inline_arraycopy() {
4534  // Get the arguments.
4535  Node* src         = argument(0);  // type: oop
4536  Node* src_offset  = argument(1);  // type: int
4537  Node* dest        = argument(2);  // type: oop
4538  Node* dest_offset = argument(3);  // type: int
4539  Node* length      = argument(4);  // type: int
4540
4541  // Compile time checks.  If any of these checks cannot be verified at compile time,
4542  // we do not make a fast path for this call.  Instead, we let the call remain as it
4543  // is.  The checks we choose to mandate at compile time are:
4544  //
4545  // (1) src and dest are arrays.
4546  const Type* src_type  = src->Value(&_gvn);
4547  const Type* dest_type = dest->Value(&_gvn);
4548  const TypeAryPtr* top_src  = src_type->isa_aryptr();
4549  const TypeAryPtr* top_dest = dest_type->isa_aryptr();
4550  if (top_src  == NULL || top_src->klass()  == NULL ||
4551      top_dest == NULL || top_dest->klass() == NULL) {
4552    // Conservatively insert a memory barrier on all memory slices.
4553    // Do not let writes into the source float below the arraycopy.
4554    insert_mem_bar(Op_MemBarCPUOrder);
4555
4556    // Call StubRoutines::generic_arraycopy stub.
4557    generate_arraycopy(TypeRawPtr::BOTTOM, T_CONFLICT,
4558                       src, src_offset, dest, dest_offset, length);
4559
4560    // Do not let reads from the destination float above the arraycopy.
4561    // Since we cannot type the arrays, we don't know which slices
4562    // might be affected.  We could restrict this barrier only to those
4563    // memory slices which pertain to array elements--but don't bother.
4564    if (!InsertMemBarAfterArraycopy)
4565      // (If InsertMemBarAfterArraycopy, there is already one in place.)
4566      insert_mem_bar(Op_MemBarCPUOrder);
4567    return true;
4568  }
4569
4570  // (2) src and dest arrays must have elements of the same BasicType
4571  // Figure out the size and type of the elements we will be copying.
4572  BasicType src_elem  =  top_src->klass()->as_array_klass()->element_type()->basic_type();
4573  BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
4574  if (src_elem  == T_ARRAY)  src_elem  = T_OBJECT;
4575  if (dest_elem == T_ARRAY)  dest_elem = T_OBJECT;
4576
4577  if (src_elem != dest_elem || dest_elem == T_VOID) {
4578    // The component types are not the same or are not recognized.  Punt.
4579    // (But, avoid the native method wrapper to JVM_ArrayCopy.)
4580    generate_slow_arraycopy(TypePtr::BOTTOM,
4581                            src, src_offset, dest, dest_offset, length,
4582                            /*dest_uninitialized*/false);
4583    return true;
4584  }
4585
4586  //---------------------------------------------------------------------------
4587  // We will make a fast path for this call to arraycopy.
4588
4589  // We have the following tests left to perform:
4590  //
4591  // (3) src and dest must not be null.
4592  // (4) src_offset must not be negative.
4593  // (5) dest_offset must not be negative.
4594  // (6) length must not be negative.
4595  // (7) src_offset + length must not exceed length of src.
4596  // (8) dest_offset + length must not exceed length of dest.
4597  // (9) each element of an oop array must be assignable
4598
4599  RegionNode* slow_region = new (C) RegionNode(1);
4600  record_for_igvn(slow_region);
4601
4602  // (3) operands must not be null
4603  // We currently perform our null checks with the null_check routine.
4604  // This means that the null exceptions will be reported in the caller
4605  // rather than (correctly) reported inside of the native arraycopy call.
4606  // This should be corrected, given time.  We do our null check with the
4607  // stack pointer restored.
4608  src  = null_check(src,  T_ARRAY);
4609  dest = null_check(dest, T_ARRAY);
4610
4611  // (4) src_offset must not be negative.
4612  generate_negative_guard(src_offset, slow_region);
4613
4614  // (5) dest_offset must not be negative.
4615  generate_negative_guard(dest_offset, slow_region);
4616
4617  // (6) length must not be negative (moved to generate_arraycopy()).
4618  // generate_negative_guard(length, slow_region);
4619
4620  // (7) src_offset + length must not exceed length of src.
4621  generate_limit_guard(src_offset, length,
4622                       load_array_length(src),
4623                       slow_region);
4624
4625  // (8) dest_offset + length must not exceed length of dest.
4626  generate_limit_guard(dest_offset, length,
4627                       load_array_length(dest),
4628                       slow_region);
4629
4630  // (9) each element of an oop array must be assignable
4631  // The generate_arraycopy subroutine checks this.
4632
4633  // This is where the memory effects are placed:
4634  const TypePtr* adr_type = TypeAryPtr::get_array_body_type(dest_elem);
4635  generate_arraycopy(adr_type, dest_elem,
4636                     src, src_offset, dest, dest_offset, length,
4637                     false, false, slow_region);
4638
4639  return true;
4640}
4641
4642//-----------------------------generate_arraycopy----------------------
4643// Generate an optimized call to arraycopy.
4644// Caller must guard against non-arrays.
4645// Caller must determine a common array basic-type for both arrays.
4646// Caller must validate offsets against array bounds.
4647// The slow_region has already collected guard failure paths
4648// (such as out of bounds length or non-conformable array types).
4649// The generated code has this shape, in general:
4650//
4651//     if (length == 0)  return   // via zero_path
4652//     slowval = -1
4653//     if (types unknown) {
4654//       slowval = call generic copy loop
4655//       if (slowval == 0)  return  // via checked_path
4656//     } else if (indexes in bounds) {
4657//       if ((is object array) && !(array type check)) {
4658//         slowval = call checked copy loop
4659//         if (slowval == 0)  return  // via checked_path
4660//       } else {
4661//         call bulk copy loop
4662//         return  // via fast_path
4663//       }
4664//     }
4665//     // adjust params for remaining work:
4666//     if (slowval != -1) {
4667//       n = -1^slowval; src_offset += n; dest_offset += n; length -= n
4668//     }
4669//   slow_region:
4670//     call slow arraycopy(src, src_offset, dest, dest_offset, length)
4671//     return  // via slow_call_path
4672//
4673// This routine is used from several intrinsics:  System.arraycopy,
4674// Object.clone (the array subcase), and Arrays.copyOf[Range].
4675//
4676void
4677LibraryCallKit::generate_arraycopy(const TypePtr* adr_type,
4678                                   BasicType basic_elem_type,
4679                                   Node* src,  Node* src_offset,
4680                                   Node* dest, Node* dest_offset,
4681                                   Node* copy_length,
4682                                   bool disjoint_bases,
4683                                   bool length_never_negative,
4684                                   RegionNode* slow_region) {
4685
4686  if (slow_region == NULL) {
4687    slow_region = new(C) RegionNode(1);
4688    record_for_igvn(slow_region);
4689  }
4690
4691  Node* original_dest      = dest;
4692  AllocateArrayNode* alloc = NULL;  // used for zeroing, if needed
4693  bool  dest_uninitialized = false;
4694
4695  // See if this is the initialization of a newly-allocated array.
4696  // If so, we will take responsibility here for initializing it to zero.
4697  // (Note:  Because tightly_coupled_allocation performs checks on the
4698  // out-edges of the dest, we need to avoid making derived pointers
4699  // from it until we have checked its uses.)
4700  if (ReduceBulkZeroing
4701      && !ZeroTLAB              // pointless if already zeroed
4702      && basic_elem_type != T_CONFLICT // avoid corner case
4703      && !src->eqv_uncast(dest)
4704      && ((alloc = tightly_coupled_allocation(dest, slow_region))
4705          != NULL)
4706      && _gvn.find_int_con(alloc->in(AllocateNode::ALength), 1) > 0
4707      && alloc->maybe_set_complete(&_gvn)) {
4708    // "You break it, you buy it."
4709    InitializeNode* init = alloc->initialization();
4710    assert(init->is_complete(), "we just did this");
4711    init->set_complete_with_arraycopy();
4712    assert(dest->is_CheckCastPP(), "sanity");
4713    assert(dest->in(0)->in(0) == init, "dest pinned");
4714    adr_type = TypeRawPtr::BOTTOM;  // all initializations are into raw memory
4715    // From this point on, every exit path is responsible for
4716    // initializing any non-copied parts of the object to zero.
4717    // Also, if this flag is set we make sure that arraycopy interacts properly
4718    // with G1, eliding pre-barriers. See CR 6627983.
4719    dest_uninitialized = true;
4720  } else {
4721    // No zeroing elimination here.
4722    alloc             = NULL;
4723    //original_dest   = dest;
4724    //dest_uninitialized = false;
4725  }
4726
4727  // Results are placed here:
4728  enum { fast_path        = 1,  // normal void-returning assembly stub
4729         checked_path     = 2,  // special assembly stub with cleanup
4730         slow_call_path   = 3,  // something went wrong; call the VM
4731         zero_path        = 4,  // bypass when length of copy is zero
4732         bcopy_path       = 5,  // copy primitive array by 64-bit blocks
4733         PATH_LIMIT       = 6
4734  };
4735  RegionNode* result_region = new(C) RegionNode(PATH_LIMIT);
4736  PhiNode*    result_i_o    = new(C) PhiNode(result_region, Type::ABIO);
4737  PhiNode*    result_memory = new(C) PhiNode(result_region, Type::MEMORY, adr_type);
4738  record_for_igvn(result_region);
4739  _gvn.set_type_bottom(result_i_o);
4740  _gvn.set_type_bottom(result_memory);
4741  assert(adr_type != TypePtr::BOTTOM, "must be RawMem or a T[] slice");
4742
4743  // The slow_control path:
4744  Node* slow_control;
4745  Node* slow_i_o = i_o();
4746  Node* slow_mem = memory(adr_type);
4747  debug_only(slow_control = (Node*) badAddress);
4748
4749  // Checked control path:
4750  Node* checked_control = top();
4751  Node* checked_mem     = NULL;
4752  Node* checked_i_o     = NULL;
4753  Node* checked_value   = NULL;
4754
4755  if (basic_elem_type == T_CONFLICT) {
4756    assert(!dest_uninitialized, "");
4757    Node* cv = generate_generic_arraycopy(adr_type,
4758                                          src, src_offset, dest, dest_offset,
4759                                          copy_length, dest_uninitialized);
4760    if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
4761    checked_control = control();
4762    checked_i_o     = i_o();
4763    checked_mem     = memory(adr_type);
4764    checked_value   = cv;
4765    set_control(top());         // no fast path
4766  }
4767
4768  Node* not_pos = generate_nonpositive_guard(copy_length, length_never_negative);
4769  if (not_pos != NULL) {
4770    PreserveJVMState pjvms(this);
4771    set_control(not_pos);
4772
4773    // (6) length must not be negative.
4774    if (!length_never_negative) {
4775      generate_negative_guard(copy_length, slow_region);
4776    }
4777
4778    // copy_length is 0.
4779    if (!stopped() && dest_uninitialized) {
4780      Node* dest_length = alloc->in(AllocateNode::ALength);
4781      if (copy_length->eqv_uncast(dest_length)
4782          || _gvn.find_int_con(dest_length, 1) <= 0) {
4783        // There is no zeroing to do. No need for a secondary raw memory barrier.
4784      } else {
4785        // Clear the whole thing since there are no source elements to copy.
4786        generate_clear_array(adr_type, dest, basic_elem_type,
4787                             intcon(0), NULL,
4788                             alloc->in(AllocateNode::AllocSize));
4789        // Use a secondary InitializeNode as raw memory barrier.
4790        // Currently it is needed only on this path since other
4791        // paths have stub or runtime calls as raw memory barriers.
4792        InitializeNode* init = insert_mem_bar_volatile(Op_Initialize,
4793                                                       Compile::AliasIdxRaw,
4794                                                       top())->as_Initialize();
4795        init->set_complete(&_gvn);  // (there is no corresponding AllocateNode)
4796      }
4797    }
4798
4799    // Present the results of the fast call.
4800    result_region->init_req(zero_path, control());
4801    result_i_o   ->init_req(zero_path, i_o());
4802    result_memory->init_req(zero_path, memory(adr_type));
4803  }
4804
4805  if (!stopped() && dest_uninitialized) {
4806    // We have to initialize the *uncopied* part of the array to zero.
4807    // The copy destination is the slice dest[off..off+len].  The other slices
4808    // are dest_head = dest[0..off] and dest_tail = dest[off+len..dest.length].
4809    Node* dest_size   = alloc->in(AllocateNode::AllocSize);
4810    Node* dest_length = alloc->in(AllocateNode::ALength);
4811    Node* dest_tail   = _gvn.transform(new(C) AddINode(dest_offset,
4812                                                          copy_length));
4813
4814    // If there is a head section that needs zeroing, do it now.
4815    if (find_int_con(dest_offset, -1) != 0) {
4816      generate_clear_array(adr_type, dest, basic_elem_type,
4817                           intcon(0), dest_offset,
4818                           NULL);
4819    }
4820
4821    // Next, perform a dynamic check on the tail length.
4822    // It is often zero, and we can win big if we prove this.
4823    // There are two wins:  Avoid generating the ClearArray
4824    // with its attendant messy index arithmetic, and upgrade
4825    // the copy to a more hardware-friendly word size of 64 bits.
4826    Node* tail_ctl = NULL;
4827    if (!stopped() && !dest_tail->eqv_uncast(dest_length)) {
4828      Node* cmp_lt   = _gvn.transform(new(C) CmpINode(dest_tail, dest_length));
4829      Node* bol_lt   = _gvn.transform(new(C) BoolNode(cmp_lt, BoolTest::lt));
4830      tail_ctl = generate_slow_guard(bol_lt, NULL);
4831      assert(tail_ctl != NULL || !stopped(), "must be an outcome");
4832    }
4833
4834    // At this point, let's assume there is no tail.
4835    if (!stopped() && alloc != NULL && basic_elem_type != T_OBJECT) {
4836      // There is no tail.  Try an upgrade to a 64-bit copy.
4837      bool didit = false;
4838      { PreserveJVMState pjvms(this);
4839        didit = generate_block_arraycopy(adr_type, basic_elem_type, alloc,
4840                                         src, src_offset, dest, dest_offset,
4841                                         dest_size, dest_uninitialized);
4842        if (didit) {
4843          // Present the results of the block-copying fast call.
4844          result_region->init_req(bcopy_path, control());
4845          result_i_o   ->init_req(bcopy_path, i_o());
4846          result_memory->init_req(bcopy_path, memory(adr_type));
4847        }
4848      }
4849      if (didit)
4850        set_control(top());     // no regular fast path
4851    }
4852
4853    // Clear the tail, if any.
4854    if (tail_ctl != NULL) {
4855      Node* notail_ctl = stopped() ? NULL : control();
4856      set_control(tail_ctl);
4857      if (notail_ctl == NULL) {
4858        generate_clear_array(adr_type, dest, basic_elem_type,
4859                             dest_tail, NULL,
4860                             dest_size);
4861      } else {
4862        // Make a local merge.
4863        Node* done_ctl = new(C) RegionNode(3);
4864        Node* done_mem = new(C) PhiNode(done_ctl, Type::MEMORY, adr_type);
4865        done_ctl->init_req(1, notail_ctl);
4866        done_mem->init_req(1, memory(adr_type));
4867        generate_clear_array(adr_type, dest, basic_elem_type,
4868                             dest_tail, NULL,
4869                             dest_size);
4870        done_ctl->init_req(2, control());
4871        done_mem->init_req(2, memory(adr_type));
4872        set_control( _gvn.transform(done_ctl));
4873        set_memory(  _gvn.transform(done_mem), adr_type );
4874      }
4875    }
4876  }
4877
4878  BasicType copy_type = basic_elem_type;
4879  assert(basic_elem_type != T_ARRAY, "caller must fix this");
4880  if (!stopped() && copy_type == T_OBJECT) {
4881    // If src and dest have compatible element types, we can copy bits.
4882    // Types S[] and D[] are compatible if D is a supertype of S.
4883    //
4884    // If they are not, we will use checked_oop_disjoint_arraycopy,
4885    // which performs a fast optimistic per-oop check, and backs off
4886    // further to JVM_ArrayCopy on the first per-oop check that fails.
4887    // (Actually, we don't move raw bits only; the GC requires card marks.)
4888
4889    // Get the Klass* for both src and dest
4890    Node* src_klass  = load_object_klass(src);
4891    Node* dest_klass = load_object_klass(dest);
4892
4893    // Generate the subtype check.
4894    // This might fold up statically, or then again it might not.
4895    //
4896    // Non-static example:  Copying List<String>.elements to a new String[].
4897    // The backing store for a List<String> is always an Object[],
4898    // but its elements are always type String, if the generic types
4899    // are correct at the source level.
4900    //
4901    // Test S[] against D[], not S against D, because (probably)
4902    // the secondary supertype cache is less busy for S[] than S.
4903    // This usually only matters when D is an interface.
4904    Node* not_subtype_ctrl = gen_subtype_check(src_klass, dest_klass);
4905    // Plug failing path into checked_oop_disjoint_arraycopy
4906    if (not_subtype_ctrl != top()) {
4907      PreserveJVMState pjvms(this);
4908      set_control(not_subtype_ctrl);
4909      // (At this point we can assume disjoint_bases, since types differ.)
4910      int ek_offset = in_bytes(ObjArrayKlass::element_klass_offset());
4911      Node* p1 = basic_plus_adr(dest_klass, ek_offset);
4912      Node* n1 = LoadKlassNode::make(_gvn, immutable_memory(), p1, TypeRawPtr::BOTTOM);
4913      Node* dest_elem_klass = _gvn.transform(n1);
4914      Node* cv = generate_checkcast_arraycopy(adr_type,
4915                                              dest_elem_klass,
4916                                              src, src_offset, dest, dest_offset,
4917                                              ConvI2X(copy_length), dest_uninitialized);
4918      if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
4919      checked_control = control();
4920      checked_i_o     = i_o();
4921      checked_mem     = memory(adr_type);
4922      checked_value   = cv;
4923    }
4924    // At this point we know we do not need type checks on oop stores.
4925
4926    // Let's see if we need card marks:
4927    if (alloc != NULL && use_ReduceInitialCardMarks()) {
4928      // If we do not need card marks, copy using the jint or jlong stub.
4929      copy_type = LP64_ONLY(UseCompressedOops ? T_INT : T_LONG) NOT_LP64(T_INT);
4930      assert(type2aelembytes(basic_elem_type) == type2aelembytes(copy_type),
4931             "sizes agree");
4932    }
4933  }
4934
4935  if (!stopped()) {
4936    // Generate the fast path, if possible.
4937    PreserveJVMState pjvms(this);
4938    generate_unchecked_arraycopy(adr_type, copy_type, disjoint_bases,
4939                                 src, src_offset, dest, dest_offset,
4940                                 ConvI2X(copy_length), dest_uninitialized);
4941
4942    // Present the results of the fast call.
4943    result_region->init_req(fast_path, control());
4944    result_i_o   ->init_req(fast_path, i_o());
4945    result_memory->init_req(fast_path, memory(adr_type));
4946  }
4947
4948  // Here are all the slow paths up to this point, in one bundle:
4949  slow_control = top();
4950  if (slow_region != NULL)
4951    slow_control = _gvn.transform(slow_region);
4952  DEBUG_ONLY(slow_region = (RegionNode*)badAddress);
4953
4954  set_control(checked_control);
4955  if (!stopped()) {
4956    // Clean up after the checked call.
4957    // The returned value is either 0 or -1^K,
4958    // where K = number of partially transferred array elements.
4959    Node* cmp = _gvn.transform(new(C) CmpINode(checked_value, intcon(0)));
4960    Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::eq));
4961    IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);
4962
4963    // If it is 0, we are done, so transfer to the end.
4964    Node* checks_done = _gvn.transform(new(C) IfTrueNode(iff));
4965    result_region->init_req(checked_path, checks_done);
4966    result_i_o   ->init_req(checked_path, checked_i_o);
4967    result_memory->init_req(checked_path, checked_mem);
4968
4969    // If it is not zero, merge into the slow call.
4970    set_control( _gvn.transform(new(C) IfFalseNode(iff) ));
4971    RegionNode* slow_reg2 = new(C) RegionNode(3);
4972    PhiNode*    slow_i_o2 = new(C) PhiNode(slow_reg2, Type::ABIO);
4973    PhiNode*    slow_mem2 = new(C) PhiNode(slow_reg2, Type::MEMORY, adr_type);
4974    record_for_igvn(slow_reg2);
4975    slow_reg2  ->init_req(1, slow_control);
4976    slow_i_o2  ->init_req(1, slow_i_o);
4977    slow_mem2  ->init_req(1, slow_mem);
4978    slow_reg2  ->init_req(2, control());
4979    slow_i_o2  ->init_req(2, checked_i_o);
4980    slow_mem2  ->init_req(2, checked_mem);
4981
4982    slow_control = _gvn.transform(slow_reg2);
4983    slow_i_o     = _gvn.transform(slow_i_o2);
4984    slow_mem     = _gvn.transform(slow_mem2);
4985
4986    if (alloc != NULL) {
4987      // We'll restart from the very beginning, after zeroing the whole thing.
4988      // This can cause double writes, but that's OK since dest is brand new.
4989      // So we ignore the low 31 bits of the value returned from the stub.
4990    } else {
4991      // We must continue the copy exactly where it failed, or else
4992      // another thread might see the wrong number of writes to dest.
4993      Node* checked_offset = _gvn.transform(new(C) XorINode(checked_value, intcon(-1)));
4994      Node* slow_offset    = new(C) PhiNode(slow_reg2, TypeInt::INT);
4995      slow_offset->init_req(1, intcon(0));
4996      slow_offset->init_req(2, checked_offset);
4997      slow_offset  = _gvn.transform(slow_offset);
4998
4999      // Adjust the arguments by the conditionally incoming offset.
5000      Node* src_off_plus  = _gvn.transform(new(C) AddINode(src_offset,  slow_offset));
5001      Node* dest_off_plus = _gvn.transform(new(C) AddINode(dest_offset, slow_offset));
5002      Node* length_minus  = _gvn.transform(new(C) SubINode(copy_length, slow_offset));
5003
5004      // Tweak the node variables to adjust the code produced below:
5005      src_offset  = src_off_plus;
5006      dest_offset = dest_off_plus;
5007      copy_length = length_minus;
5008    }
5009  }
5010
5011  set_control(slow_control);
5012  if (!stopped()) {
5013    // Generate the slow path, if needed.
5014    PreserveJVMState pjvms(this);   // replace_in_map may trash the map
5015
5016    set_memory(slow_mem, adr_type);
5017    set_i_o(slow_i_o);
5018
5019    if (dest_uninitialized) {
5020      generate_clear_array(adr_type, dest, basic_elem_type,
5021                           intcon(0), NULL,
5022                           alloc->in(AllocateNode::AllocSize));
5023    }
5024
5025    generate_slow_arraycopy(adr_type,
5026                            src, src_offset, dest, dest_offset,
5027                            copy_length, /*dest_uninitialized*/false);
5028
5029    result_region->init_req(slow_call_path, control());
5030    result_i_o   ->init_req(slow_call_path, i_o());
5031    result_memory->init_req(slow_call_path, memory(adr_type));
5032  }
5033
5034  // Remove unused edges.
5035  for (uint i = 1; i < result_region->req(); i++) {
5036    if (result_region->in(i) == NULL)
5037      result_region->init_req(i, top());
5038  }
5039
5040  // Finished; return the combined state.
5041  set_control( _gvn.transform(result_region));
5042  set_i_o(     _gvn.transform(result_i_o)    );
5043  set_memory(  _gvn.transform(result_memory), adr_type );
5044
5045  // The memory edges above are precise in order to model effects around
5046  // array copies accurately to allow value numbering of field loads around
5047  // arraycopy.  Such field loads, both before and after, are common in Java
5048  // collections and similar classes involving header/array data structures.
5049  //
5050  // But with low number of register or when some registers are used or killed
5051  // by arraycopy calls it causes registers spilling on stack. See 6544710.
5052  // The next memory barrier is added to avoid it. If the arraycopy can be
5053  // optimized away (which it can, sometimes) then we can manually remove
5054  // the membar also.
5055  //
5056  // Do not let reads from the cloned object float above the arraycopy.
5057  if (alloc != NULL) {
5058    // Do not let stores that initialize this object be reordered with
5059    // a subsequent store that would make this object accessible by
5060    // other threads.
5061    // Record what AllocateNode this StoreStore protects so that
5062    // escape analysis can go from the MemBarStoreStoreNode to the
5063    // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5064    // based on the escape status of the AllocateNode.
5065    insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
5066  } else if (InsertMemBarAfterArraycopy)
5067    insert_mem_bar(Op_MemBarCPUOrder);
5068}
5069
5070
5071// Helper function which determines if an arraycopy immediately follows
5072// an allocation, with no intervening tests or other escapes for the object.
5073AllocateArrayNode*
5074LibraryCallKit::tightly_coupled_allocation(Node* ptr,
5075                                           RegionNode* slow_region) {
5076  if (stopped())             return NULL;  // no fast path
5077  if (C->AliasLevel() == 0)  return NULL;  // no MergeMems around
5078
5079  AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
5080  if (alloc == NULL)  return NULL;
5081
5082  Node* rawmem = memory(Compile::AliasIdxRaw);
5083  // Is the allocation's memory state untouched?
5084  if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
5085    // Bail out if there have been raw-memory effects since the allocation.
5086    // (Example:  There might have been a call or safepoint.)
5087    return NULL;
5088  }
5089  rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
5090  if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
5091    return NULL;
5092  }
5093
5094  // There must be no unexpected observers of this allocation.
5095  for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
5096    Node* obs = ptr->fast_out(i);
5097    if (obs != this->map()) {
5098      return NULL;
5099    }
5100  }
5101
5102  // This arraycopy must unconditionally follow the allocation of the ptr.
5103  Node* alloc_ctl = ptr->in(0);
5104  assert(just_allocated_object(alloc_ctl) == ptr, "most recent allo");
5105
5106  Node* ctl = control();
5107  while (ctl != alloc_ctl) {
5108    // There may be guards which feed into the slow_region.
5109    // Any other control flow means that we might not get a chance
5110    // to finish initializing the allocated object.
5111    if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
5112      IfNode* iff = ctl->in(0)->as_If();
5113      Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);
5114      assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
5115      if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {
5116        ctl = iff->in(0);       // This test feeds the known slow_region.
5117        continue;
5118      }
5119      // One more try:  Various low-level checks bottom out in
5120      // uncommon traps.  If the debug-info of the trap omits
5121      // any reference to the allocation, as we've already
5122      // observed, then there can be no objection to the trap.
5123      bool found_trap = false;
5124      for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {
5125        Node* obs = not_ctl->fast_out(j);
5126        if (obs->in(0) == not_ctl && obs->is_Call() &&
5127            (obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {
5128          found_trap = true; break;
5129        }
5130      }
5131      if (found_trap) {
5132        ctl = iff->in(0);       // This test feeds a harmless uncommon trap.
5133        continue;
5134      }
5135    }
5136    return NULL;
5137  }
5138
5139  // If we get this far, we have an allocation which immediately
5140  // precedes the arraycopy, and we can take over zeroing the new object.
5141  // The arraycopy will finish the initialization, and provide
5142  // a new control state to which we will anchor the destination pointer.
5143
5144  return alloc;
5145}
5146
5147// Helper for initialization of arrays, creating a ClearArray.
5148// It writes zero bits in [start..end), within the body of an array object.
5149// The memory effects are all chained onto the 'adr_type' alias category.
5150//
5151// Since the object is otherwise uninitialized, we are free
5152// to put a little "slop" around the edges of the cleared area,
5153// as long as it does not go back into the array's header,
5154// or beyond the array end within the heap.
5155//
5156// The lower edge can be rounded down to the nearest jint and the
5157// upper edge can be rounded up to the nearest MinObjAlignmentInBytes.
5158//
5159// Arguments:
5160//   adr_type           memory slice where writes are generated
5161//   dest               oop of the destination array
5162//   basic_elem_type    element type of the destination
5163//   slice_idx          array index of first element to store
5164//   slice_len          number of elements to store (or NULL)
5165//   dest_size          total size in bytes of the array object
5166//
5167// Exactly one of slice_len or dest_size must be non-NULL.
5168// If dest_size is non-NULL, zeroing extends to the end of the object.
5169// If slice_len is non-NULL, the slice_idx value must be a constant.
5170void
5171LibraryCallKit::generate_clear_array(const TypePtr* adr_type,
5172                                     Node* dest,
5173                                     BasicType basic_elem_type,
5174                                     Node* slice_idx,
5175                                     Node* slice_len,
5176                                     Node* dest_size) {
5177  // one or the other but not both of slice_len and dest_size:
5178  assert((slice_len != NULL? 1: 0) + (dest_size != NULL? 1: 0) == 1, "");
5179  if (slice_len == NULL)  slice_len = top();
5180  if (dest_size == NULL)  dest_size = top();
5181
5182  // operate on this memory slice:
5183  Node* mem = memory(adr_type); // memory slice to operate on
5184
5185  // scaling and rounding of indexes:
5186  int scale = exact_log2(type2aelembytes(basic_elem_type));
5187  int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
5188  int clear_low = (-1 << scale) & (BytesPerInt  - 1);
5189  int bump_bit  = (-1 << scale) & BytesPerInt;
5190
5191  // determine constant starts and ends
5192  const intptr_t BIG_NEG = -128;
5193  assert(BIG_NEG + 2*abase < 0, "neg enough");
5194  intptr_t slice_idx_con = (intptr_t) find_int_con(slice_idx, BIG_NEG);
5195  intptr_t slice_len_con = (intptr_t) find_int_con(slice_len, BIG_NEG);
5196  if (slice_len_con == 0) {
5197    return;                     // nothing to do here
5198  }
5199  intptr_t start_con = (abase + (slice_idx_con << scale)) & ~clear_low;
5200  intptr_t end_con   = find_intptr_t_con(dest_size, -1);
5201  if (slice_idx_con >= 0 && slice_len_con >= 0) {
5202    assert(end_con < 0, "not two cons");
5203    end_con = round_to(abase + ((slice_idx_con + slice_len_con) << scale),
5204                       BytesPerLong);
5205  }
5206
5207  if (start_con >= 0 && end_con >= 0) {
5208    // Constant start and end.  Simple.
5209    mem = ClearArrayNode::clear_memory(control(), mem, dest,
5210                                       start_con, end_con, &_gvn);
5211  } else if (start_con >= 0 && dest_size != top()) {
5212    // Constant start, pre-rounded end after the tail of the array.
5213    Node* end = dest_size;
5214    mem = ClearArrayNode::clear_memory(control(), mem, dest,
5215                                       start_con, end, &_gvn);
5216  } else if (start_con >= 0 && slice_len != top()) {
5217    // Constant start, non-constant end.  End needs rounding up.
5218    // End offset = round_up(abase + ((slice_idx_con + slice_len) << scale), 8)
5219    intptr_t end_base  = abase + (slice_idx_con << scale);
5220    int      end_round = (-1 << scale) & (BytesPerLong  - 1);
5221    Node*    end       = ConvI2X(slice_len);
5222    if (scale != 0)
5223      end = _gvn.transform(new(C) LShiftXNode(end, intcon(scale) ));
5224    end_base += end_round;
5225    end = _gvn.transform(new(C) AddXNode(end, MakeConX(end_base)));
5226    end = _gvn.transform(new(C) AndXNode(end, MakeConX(~end_round)));
5227    mem = ClearArrayNode::clear_memory(control(), mem, dest,
5228                                       start_con, end, &_gvn);
5229  } else if (start_con < 0 && dest_size != top()) {
5230    // Non-constant start, pre-rounded end after the tail of the array.
5231    // This is almost certainly a "round-to-end" operation.
5232    Node* start = slice_idx;
5233    start = ConvI2X(start);
5234    if (scale != 0)
5235      start = _gvn.transform(new(C) LShiftXNode( start, intcon(scale) ));
5236    start = _gvn.transform(new(C) AddXNode(start, MakeConX(abase)));
5237    if ((bump_bit | clear_low) != 0) {
5238      int to_clear = (bump_bit | clear_low);
5239      // Align up mod 8, then store a jint zero unconditionally
5240      // just before the mod-8 boundary.
5241      if (((abase + bump_bit) & ~to_clear) - bump_bit
5242          < arrayOopDesc::length_offset_in_bytes() + BytesPerInt) {
5243        bump_bit = 0;
5244        assert((abase & to_clear) == 0, "array base must be long-aligned");
5245      } else {
5246        // Bump 'start' up to (or past) the next jint boundary:
5247        start = _gvn.transform(new(C) AddXNode(start, MakeConX(bump_bit)));
5248        assert((abase & clear_low) == 0, "array base must be int-aligned");
5249      }
5250      // Round bumped 'start' down to jlong boundary in body of array.
5251      start = _gvn.transform(new(C) AndXNode(start, MakeConX(~to_clear)));
5252      if (bump_bit != 0) {
5253        // Store a zero to the immediately preceding jint:
5254        Node* x1 = _gvn.transform(new(C) AddXNode(start, MakeConX(-bump_bit)));
5255        Node* p1 = basic_plus_adr(dest, x1);
5256        mem = StoreNode::make(_gvn, control(), mem, p1, adr_type, intcon(0), T_INT);
5257        mem = _gvn.transform(mem);
5258      }
5259    }
5260    Node* end = dest_size; // pre-rounded
5261    mem = ClearArrayNode::clear_memory(control(), mem, dest,
5262                                       start, end, &_gvn);
5263  } else {
5264    // Non-constant start, unrounded non-constant end.
5265    // (Nobody zeroes a random midsection of an array using this routine.)
5266    ShouldNotReachHere();       // fix caller
5267  }
5268
5269  // Done.
5270  set_memory(mem, adr_type);
5271}
5272
5273
5274bool
5275LibraryCallKit::generate_block_arraycopy(const TypePtr* adr_type,
5276                                         BasicType basic_elem_type,
5277                                         AllocateNode* alloc,
5278                                         Node* src,  Node* src_offset,
5279                                         Node* dest, Node* dest_offset,
5280                                         Node* dest_size, bool dest_uninitialized) {
5281  // See if there is an advantage from block transfer.
5282  int scale = exact_log2(type2aelembytes(basic_elem_type));
5283  if (scale >= LogBytesPerLong)
5284    return false;               // it is already a block transfer
5285
5286  // Look at the alignment of the starting offsets.
5287  int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
5288
5289  intptr_t src_off_con  = (intptr_t) find_int_con(src_offset, -1);
5290  intptr_t dest_off_con = (intptr_t) find_int_con(dest_offset, -1);
5291  if (src_off_con < 0 || dest_off_con < 0)
5292    // At present, we can only understand constants.
5293    return false;
5294
5295  intptr_t src_off  = abase + (src_off_con  << scale);
5296  intptr_t dest_off = abase + (dest_off_con << scale);
5297
5298  if (((src_off | dest_off) & (BytesPerLong-1)) != 0) {
5299    // Non-aligned; too bad.
5300    // One more chance:  Pick off an initial 32-bit word.
5301    // This is a common case, since abase can be odd mod 8.
5302    if (((src_off | dest_off) & (BytesPerLong-1)) == BytesPerInt &&
5303        ((src_off ^ dest_off) & (BytesPerLong-1)) == 0) {
5304      Node* sptr = basic_plus_adr(src,  src_off);
5305      Node* dptr = basic_plus_adr(dest, dest_off);
5306      Node* sval = make_load(control(), sptr, TypeInt::INT, T_INT, adr_type);
5307      store_to_memory(control(), dptr, sval, T_INT, adr_type);
5308      src_off += BytesPerInt;
5309      dest_off += BytesPerInt;
5310    } else {
5311      return false;
5312    }
5313  }
5314  assert(src_off % BytesPerLong == 0, "");
5315  assert(dest_off % BytesPerLong == 0, "");
5316
5317  // Do this copy by giant steps.
5318  Node* sptr  = basic_plus_adr(src,  src_off);
5319  Node* dptr  = basic_plus_adr(dest, dest_off);
5320  Node* countx = dest_size;
5321  countx = _gvn.transform(new (C) SubXNode(countx, MakeConX(dest_off)));
5322  countx = _gvn.transform(new (C) URShiftXNode(countx, intcon(LogBytesPerLong)));
5323
5324  bool disjoint_bases = true;   // since alloc != NULL
5325  generate_unchecked_arraycopy(adr_type, T_LONG, disjoint_bases,
5326                               sptr, NULL, dptr, NULL, countx, dest_uninitialized);
5327
5328  return true;
5329}
5330
5331
5332// Helper function; generates code for the slow case.
5333// We make a call to a runtime method which emulates the native method,
5334// but without the native wrapper overhead.
5335void
5336LibraryCallKit::generate_slow_arraycopy(const TypePtr* adr_type,
5337                                        Node* src,  Node* src_offset,
5338                                        Node* dest, Node* dest_offset,
5339                                        Node* copy_length, bool dest_uninitialized) {
5340  assert(!dest_uninitialized, "Invariant");
5341  Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON,
5342                                 OptoRuntime::slow_arraycopy_Type(),
5343                                 OptoRuntime::slow_arraycopy_Java(),
5344                                 "slow_arraycopy", adr_type,
5345                                 src, src_offset, dest, dest_offset,
5346                                 copy_length);
5347
5348  // Handle exceptions thrown by this fellow:
5349  make_slow_call_ex(call, env()->Throwable_klass(), false);
5350}
5351
5352// Helper function; generates code for cases requiring runtime checks.
5353Node*
5354LibraryCallKit::generate_checkcast_arraycopy(const TypePtr* adr_type,
5355                                             Node* dest_elem_klass,
5356                                             Node* src,  Node* src_offset,
5357                                             Node* dest, Node* dest_offset,
5358                                             Node* copy_length, bool dest_uninitialized) {
5359  if (stopped())  return NULL;
5360
5361  address copyfunc_addr = StubRoutines::checkcast_arraycopy(dest_uninitialized);
5362  if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
5363    return NULL;
5364  }
5365
5366  // Pick out the parameters required to perform a store-check
5367  // for the target array.  This is an optimistic check.  It will
5368  // look in each non-null element's class, at the desired klass's
5369  // super_check_offset, for the desired klass.
5370  int sco_offset = in_bytes(Klass::super_check_offset_offset());
5371  Node* p3 = basic_plus_adr(dest_elem_klass, sco_offset);
5372  Node* n3 = new(C) LoadINode(NULL, memory(p3), p3, _gvn.type(p3)->is_ptr());
5373  Node* check_offset = ConvI2X(_gvn.transform(n3));
5374  Node* check_value  = dest_elem_klass;
5375
5376  Node* src_start  = array_element_address(src,  src_offset,  T_OBJECT);
5377  Node* dest_start = array_element_address(dest, dest_offset, T_OBJECT);
5378
5379  // (We know the arrays are never conjoint, because their types differ.)
5380  Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
5381                                 OptoRuntime::checkcast_arraycopy_Type(),
5382                                 copyfunc_addr, "checkcast_arraycopy", adr_type,
5383                                 // five arguments, of which two are
5384                                 // intptr_t (jlong in LP64)
5385                                 src_start, dest_start,
5386                                 copy_length XTOP,
5387                                 check_offset XTOP,
5388                                 check_value);
5389
5390  return _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
5391}
5392
5393
5394// Helper function; generates code for cases requiring runtime checks.
5395Node*
5396LibraryCallKit::generate_generic_arraycopy(const TypePtr* adr_type,
5397                                           Node* src,  Node* src_offset,
5398                                           Node* dest, Node* dest_offset,
5399                                           Node* copy_length, bool dest_uninitialized) {
5400  assert(!dest_uninitialized, "Invariant");
5401  if (stopped())  return NULL;
5402  address copyfunc_addr = StubRoutines::generic_arraycopy();
5403  if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
5404    return NULL;
5405  }
5406
5407  Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
5408                    OptoRuntime::generic_arraycopy_Type(),
5409                    copyfunc_addr, "generic_arraycopy", adr_type,
5410                    src, src_offset, dest, dest_offset, copy_length);
5411
5412  return _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
5413}
5414
5415// Helper function; generates the fast out-of-line call to an arraycopy stub.
5416void
5417LibraryCallKit::generate_unchecked_arraycopy(const TypePtr* adr_type,
5418                                             BasicType basic_elem_type,
5419                                             bool disjoint_bases,
5420                                             Node* src,  Node* src_offset,
5421                                             Node* dest, Node* dest_offset,
5422                                             Node* copy_length, bool dest_uninitialized) {
5423  if (stopped())  return;               // nothing to do
5424
5425  Node* src_start  = src;
5426  Node* dest_start = dest;
5427  if (src_offset != NULL || dest_offset != NULL) {
5428    assert(src_offset != NULL && dest_offset != NULL, "");
5429    src_start  = array_element_address(src,  src_offset,  basic_elem_type);
5430    dest_start = array_element_address(dest, dest_offset, basic_elem_type);
5431  }
5432
5433  // Figure out which arraycopy runtime method to call.
5434  const char* copyfunc_name = "arraycopy";
5435  address     copyfunc_addr =
5436      basictype2arraycopy(basic_elem_type, src_offset, dest_offset,
5437                          disjoint_bases, copyfunc_name, dest_uninitialized);
5438
5439  // Call it.  Note that the count_ix value is not scaled to a byte-size.
5440  make_runtime_call(RC_LEAF|RC_NO_FP,
5441                    OptoRuntime::fast_arraycopy_Type(),
5442                    copyfunc_addr, copyfunc_name, adr_type,
5443                    src_start, dest_start, copy_length XTOP);
5444}
5445
5446//-------------inline_encodeISOArray-----------------------------------
5447// encode char[] to byte[] in ISO_8859_1
5448bool LibraryCallKit::inline_encodeISOArray() {
5449  assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
5450  // no receiver since it is static method
5451  Node *src         = argument(0);
5452  Node *src_offset  = argument(1);
5453  Node *dst         = argument(2);
5454  Node *dst_offset  = argument(3);
5455  Node *length      = argument(4);
5456
5457  const Type* src_type = src->Value(&_gvn);
5458  const Type* dst_type = dst->Value(&_gvn);
5459  const TypeAryPtr* top_src = src_type->isa_aryptr();
5460  const TypeAryPtr* top_dest = dst_type->isa_aryptr();
5461  if (top_src  == NULL || top_src->klass()  == NULL ||
5462      top_dest == NULL || top_dest->klass() == NULL) {
5463    // failed array check
5464    return false;
5465  }
5466
5467  // Figure out the size and type of the elements we will be copying.
5468  BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5469  BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5470  if (src_elem != T_CHAR || dst_elem != T_BYTE) {
5471    return false;
5472  }
5473  Node* src_start = array_element_address(src, src_offset, src_elem);
5474  Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
5475  // 'src_start' points to src array + scaled offset
5476  // 'dst_start' points to dst array + scaled offset
5477
5478  const TypeAryPtr* mtype = TypeAryPtr::BYTES;
5479  Node* enc = new (C) EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length);
5480  enc = _gvn.transform(enc);
5481  Node* res_mem = _gvn.transform(new (C) SCMemProjNode(enc));
5482  set_memory(res_mem, mtype);
5483  set_result(enc);
5484  return true;
5485}
5486
5487/**
5488 * Calculate CRC32 for byte.
5489 * int java.util.zip.CRC32.update(int crc, int b)
5490 */
5491bool LibraryCallKit::inline_updateCRC32() {
5492  assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5493  assert(callee()->signature()->size() == 2, "update has 2 parameters");
5494  // no receiver since it is static method
5495  Node* crc  = argument(0); // type: int
5496  Node* b    = argument(1); // type: int
5497
5498  /*
5499   *    int c = ~ crc;
5500   *    b = timesXtoThe32[(b ^ c) & 0xFF];
5501   *    b = b ^ (c >>> 8);
5502   *    crc = ~b;
5503   */
5504
5505  Node* M1 = intcon(-1);
5506  crc = _gvn.transform(new (C) XorINode(crc, M1));
5507  Node* result = _gvn.transform(new (C) XorINode(crc, b));
5508  result = _gvn.transform(new (C) AndINode(result, intcon(0xFF)));
5509
5510  Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
5511  Node* offset = _gvn.transform(new (C) LShiftINode(result, intcon(0x2)));
5512  Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
5513  result = make_load(control(), adr, TypeInt::INT, T_INT);
5514
5515  crc = _gvn.transform(new (C) URShiftINode(crc, intcon(8)));
5516  result = _gvn.transform(new (C) XorINode(crc, result));
5517  result = _gvn.transform(new (C) XorINode(result, M1));
5518  set_result(result);
5519  return true;
5520}
5521
5522/**
5523 * Calculate CRC32 for byte[] array.
5524 * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
5525 */
5526bool LibraryCallKit::inline_updateBytesCRC32() {
5527  assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5528  assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5529  // no receiver since it is static method
5530  Node* crc     = argument(0); // type: int
5531  Node* src     = argument(1); // type: oop
5532  Node* offset  = argument(2); // type: int
5533  Node* length  = argument(3); // type: int
5534
5535  const Type* src_type = src->Value(&_gvn);
5536  const TypeAryPtr* top_src = src_type->isa_aryptr();
5537  if (top_src  == NULL || top_src->klass()  == NULL) {
5538    // failed array check
5539    return false;
5540  }
5541
5542  // Figure out the size and type of the elements we will be copying.
5543  BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5544  if (src_elem != T_BYTE) {
5545    return false;
5546  }
5547
5548  // 'src_start' points to src array + scaled offset
5549  Node* src_start = array_element_address(src, offset, src_elem);
5550
5551  // We assume that range check is done by caller.
5552  // TODO: generate range check (offset+length < src.length) in debug VM.
5553
5554  // Call the stub.
5555  address stubAddr = StubRoutines::updateBytesCRC32();
5556  const char *stubName = "updateBytesCRC32";
5557
5558  Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5559                                 stubAddr, stubName, TypePtr::BOTTOM,
5560                                 crc, src_start, length);
5561  Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
5562  set_result(result);
5563  return true;
5564}
5565
5566/**
5567 * Calculate CRC32 for ByteBuffer.
5568 * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
5569 */
5570bool LibraryCallKit::inline_updateByteBufferCRC32() {
5571  assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5572  assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
5573  // no receiver since it is static method
5574  Node* crc     = argument(0); // type: int
5575  Node* src     = argument(1); // type: long
5576  Node* offset  = argument(3); // type: int
5577  Node* length  = argument(4); // type: int
5578
5579  src = ConvL2X(src);  // adjust Java long to machine word
5580  Node* base = _gvn.transform(new (C) CastX2PNode(src));
5581  offset = ConvI2X(offset);
5582
5583  // 'src_start' points to src array + scaled offset
5584  Node* src_start = basic_plus_adr(top(), base, offset);
5585
5586  // Call the stub.
5587  address stubAddr = StubRoutines::updateBytesCRC32();
5588  const char *stubName = "updateBytesCRC32";
5589
5590  Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5591                                 stubAddr, stubName, TypePtr::BOTTOM,
5592                                 crc, src_start, length);
5593  Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
5594  set_result(result);
5595  return true;
5596}
5597
5598//----------------------------inline_reference_get----------------------------
5599// public T java.lang.ref.Reference.get();
5600bool LibraryCallKit::inline_reference_get() {
5601  const int referent_offset = java_lang_ref_Reference::referent_offset;
5602  guarantee(referent_offset > 0, "should have already been set");
5603
5604  // Get the argument:
5605  Node* reference_obj = null_check_receiver();
5606  if (stopped()) return true;
5607
5608  Node* adr = basic_plus_adr(reference_obj, reference_obj, referent_offset);
5609
5610  ciInstanceKlass* klass = env()->Object_klass();
5611  const TypeOopPtr* object_type = TypeOopPtr::make_from_klass(klass);
5612
5613  Node* no_ctrl = NULL;
5614  Node* result = make_load(no_ctrl, adr, object_type, T_OBJECT);
5615
5616  // Use the pre-barrier to record the value in the referent field
5617  pre_barrier(false /* do_load */,
5618              control(),
5619              NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
5620              result /* pre_val */,
5621              T_OBJECT);
5622
5623  // Add memory barrier to prevent commoning reads from this field
5624  // across safepoint since GC can change its value.
5625  insert_mem_bar(Op_MemBarCPUOrder);
5626
5627  set_result(result);
5628  return true;
5629}
5630
5631
5632Node * LibraryCallKit::load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
5633                                              bool is_exact=true, bool is_static=false) {
5634
5635  const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
5636  assert(tinst != NULL, "obj is null");
5637  assert(tinst->klass()->is_loaded(), "obj is not loaded");
5638  assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
5639
5640  ciField* field = tinst->klass()->as_instance_klass()->get_field_by_name(ciSymbol::make(fieldName),
5641                                                                          ciSymbol::make(fieldTypeString),
5642                                                                          is_static);
5643  if (field == NULL) return (Node *) NULL;
5644  assert (field != NULL, "undefined field");
5645
5646  // Next code  copied from Parse::do_get_xxx():
5647
5648  // Compute address and memory type.
5649  int offset  = field->offset_in_bytes();
5650  bool is_vol = field->is_volatile();
5651  ciType* field_klass = field->type();
5652  assert(field_klass->is_loaded(), "should be loaded");
5653  const TypePtr* adr_type = C->alias_type(field)->adr_type();
5654  Node *adr = basic_plus_adr(fromObj, fromObj, offset);
5655  BasicType bt = field->layout_type();
5656
5657  // Build the resultant type of the load
5658  const Type *type = TypeOopPtr::make_from_klass(field_klass->as_klass());
5659
5660  // Build the load.
5661  Node* loadedField = make_load(NULL, adr, type, bt, adr_type, is_vol);
5662  return loadedField;
5663}
5664
5665
5666//------------------------------inline_aescrypt_Block-----------------------
5667bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
5668  address stubAddr;
5669  const char *stubName;
5670  assert(UseAES, "need AES instruction support");
5671
5672  switch(id) {
5673  case vmIntrinsics::_aescrypt_encryptBlock:
5674    stubAddr = StubRoutines::aescrypt_encryptBlock();
5675    stubName = "aescrypt_encryptBlock";
5676    break;
5677  case vmIntrinsics::_aescrypt_decryptBlock:
5678    stubAddr = StubRoutines::aescrypt_decryptBlock();
5679    stubName = "aescrypt_decryptBlock";
5680    break;
5681  }
5682  if (stubAddr == NULL) return false;
5683
5684  Node* aescrypt_object = argument(0);
5685  Node* src             = argument(1);
5686  Node* src_offset      = argument(2);
5687  Node* dest            = argument(3);
5688  Node* dest_offset     = argument(4);
5689
5690  // (1) src and dest are arrays.
5691  const Type* src_type = src->Value(&_gvn);
5692  const Type* dest_type = dest->Value(&_gvn);
5693  const TypeAryPtr* top_src = src_type->isa_aryptr();
5694  const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5695  assert (top_src  != NULL && top_src->klass()  != NULL &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
5696
5697  // for the quick and dirty code we will skip all the checks.
5698  // we are just trying to get the call to be generated.
5699  Node* src_start  = src;
5700  Node* dest_start = dest;
5701  if (src_offset != NULL || dest_offset != NULL) {
5702    assert(src_offset != NULL && dest_offset != NULL, "");
5703    src_start  = array_element_address(src,  src_offset,  T_BYTE);
5704    dest_start = array_element_address(dest, dest_offset, T_BYTE);
5705  }
5706
5707  // now need to get the start of its expanded key array
5708  // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
5709  Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
5710  if (k_start == NULL) return false;
5711
5712  // Call the stub.
5713  make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
5714                    stubAddr, stubName, TypePtr::BOTTOM,
5715                    src_start, dest_start, k_start);
5716
5717  return true;
5718}
5719
5720//------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
5721bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
5722  address stubAddr;
5723  const char *stubName;
5724
5725  assert(UseAES, "need AES instruction support");
5726
5727  switch(id) {
5728  case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
5729    stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
5730    stubName = "cipherBlockChaining_encryptAESCrypt";
5731    break;
5732  case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
5733    stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
5734    stubName = "cipherBlockChaining_decryptAESCrypt";
5735    break;
5736  }
5737  if (stubAddr == NULL) return false;
5738
5739  Node* cipherBlockChaining_object = argument(0);
5740  Node* src                        = argument(1);
5741  Node* src_offset                 = argument(2);
5742  Node* len                        = argument(3);
5743  Node* dest                       = argument(4);
5744  Node* dest_offset                = argument(5);
5745
5746  // (1) src and dest are arrays.
5747  const Type* src_type = src->Value(&_gvn);
5748  const Type* dest_type = dest->Value(&_gvn);
5749  const TypeAryPtr* top_src = src_type->isa_aryptr();
5750  const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5751  assert (top_src  != NULL && top_src->klass()  != NULL
5752          &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
5753
5754  // checks are the responsibility of the caller
5755  Node* src_start  = src;
5756  Node* dest_start = dest;
5757  if (src_offset != NULL || dest_offset != NULL) {
5758    assert(src_offset != NULL && dest_offset != NULL, "");
5759    src_start  = array_element_address(src,  src_offset,  T_BYTE);
5760    dest_start = array_element_address(dest, dest_offset, T_BYTE);
5761  }
5762
5763  // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
5764  // (because of the predicated logic executed earlier).
5765  // so we cast it here safely.
5766  // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
5767
5768  Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
5769  if (embeddedCipherObj == NULL) return false;
5770
5771  // cast it to what we know it will be at runtime
5772  const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
5773  assert(tinst != NULL, "CBC obj is null");
5774  assert(tinst->klass()->is_loaded(), "CBC obj is not loaded");
5775  ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
5776  if (!klass_AESCrypt->is_loaded()) return false;
5777
5778  ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
5779  const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
5780  const TypeOopPtr* xtype = aklass->as_instance_type();
5781  Node* aescrypt_object = new(C) CheckCastPPNode(control(), embeddedCipherObj, xtype);
5782  aescrypt_object = _gvn.transform(aescrypt_object);
5783
5784  // we need to get the start of the aescrypt_object's expanded key array
5785  Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
5786  if (k_start == NULL) return false;
5787
5788  // similarly, get the start address of the r vector
5789  Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B", /*is_exact*/ false);
5790  if (objRvec == NULL) return false;
5791  Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
5792
5793  // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
5794  make_runtime_call(RC_LEAF|RC_NO_FP,
5795                    OptoRuntime::cipherBlockChaining_aescrypt_Type(),
5796                    stubAddr, stubName, TypePtr::BOTTOM,
5797                    src_start, dest_start, k_start, r_start, len);
5798
5799  // return is void so no result needs to be pushed
5800
5801  return true;
5802}
5803
5804//------------------------------get_key_start_from_aescrypt_object-----------------------
5805Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
5806  Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I", /*is_exact*/ false);
5807  assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
5808  if (objAESCryptKey == NULL) return (Node *) NULL;
5809
5810  // now have the array, need to get the start address of the K array
5811  Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
5812  return k_start;
5813}
5814
5815//----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
5816// Return node representing slow path of predicate check.
5817// the pseudo code we want to emulate with this predicate is:
5818// for encryption:
5819//    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
5820// for decryption:
5821//    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
5822//    note cipher==plain is more conservative than the original java code but that's OK
5823//
5824Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
5825  // First, check receiver for NULL since it is virtual method.
5826  Node* objCBC = argument(0);
5827  objCBC = null_check(objCBC);
5828
5829  if (stopped()) return NULL; // Always NULL
5830
5831  // Load embeddedCipher field of CipherBlockChaining object.
5832  Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
5833
5834  // get AESCrypt klass for instanceOf check
5835  // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
5836  // will have same classloader as CipherBlockChaining object
5837  const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
5838  assert(tinst != NULL, "CBCobj is null");
5839  assert(tinst->klass()->is_loaded(), "CBCobj is not loaded");
5840
5841  // we want to do an instanceof comparison against the AESCrypt class
5842  ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
5843  if (!klass_AESCrypt->is_loaded()) {
5844    // if AESCrypt is not even loaded, we never take the intrinsic fast path
5845    Node* ctrl = control();
5846    set_control(top()); // no regular fast path
5847    return ctrl;
5848  }
5849  ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
5850
5851  Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
5852  Node* cmp_instof  = _gvn.transform(new (C) CmpINode(instof, intcon(1)));
5853  Node* bool_instof  = _gvn.transform(new (C) BoolNode(cmp_instof, BoolTest::ne));
5854
5855  Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
5856
5857  // for encryption, we are done
5858  if (!decrypting)
5859    return instof_false;  // even if it is NULL
5860
5861  // for decryption, we need to add a further check to avoid
5862  // taking the intrinsic path when cipher and plain are the same
5863  // see the original java code for why.
5864  RegionNode* region = new(C) RegionNode(3);
5865  region->init_req(1, instof_false);
5866  Node* src = argument(1);
5867  Node* dest = argument(4);
5868  Node* cmp_src_dest = _gvn.transform(new (C) CmpPNode(src, dest));
5869  Node* bool_src_dest = _gvn.transform(new (C) BoolNode(cmp_src_dest, BoolTest::eq));
5870  Node* src_dest_conjoint = generate_guard(bool_src_dest, NULL, PROB_MIN);
5871  region->init_req(2, src_dest_conjoint);
5872
5873  record_for_igvn(region);
5874  return _gvn.transform(region);
5875}
5876