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