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