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