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