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