6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "asm/macroAssembler.hpp"
26 #include "ci/ciUtilities.inline.hpp"
27 #include "ci/ciSymbols.hpp"
28 #include "classfile/vmIntrinsics.hpp"
29 #include "compiler/compileBroker.hpp"
30 #include "compiler/compileLog.hpp"
31 #include "gc/shared/barrierSet.hpp"
32 #include "jfr/support/jfrIntrinsics.hpp"
33 #include "memory/resourceArea.hpp"
34 #include "oops/klass.inline.hpp"
35 #include "oops/objArrayKlass.hpp"
36 #include "opto/addnode.hpp"
37 #include "opto/arraycopynode.hpp"
38 #include "opto/c2compiler.hpp"
39 #include "opto/castnode.hpp"
40 #include "opto/cfgnode.hpp"
41 #include "opto/convertnode.hpp"
42 #include "opto/countbitsnode.hpp"
43 #include "opto/idealKit.hpp"
44 #include "opto/library_call.hpp"
45 #include "opto/mathexactnode.hpp"
298 case vmIntrinsics::_indexOfIL: return inline_string_indexOfI(StrIntrinsicNode::LL);
299 case vmIntrinsics::_indexOfIU: return inline_string_indexOfI(StrIntrinsicNode::UU);
300 case vmIntrinsics::_indexOfIUL: return inline_string_indexOfI(StrIntrinsicNode::UL);
301 case vmIntrinsics::_indexOfU_char: return inline_string_indexOfChar(StrIntrinsicNode::U);
302 case vmIntrinsics::_indexOfL_char: return inline_string_indexOfChar(StrIntrinsicNode::L);
303
304 case vmIntrinsics::_equalsL: return inline_string_equals(StrIntrinsicNode::LL);
305
306 case vmIntrinsics::_vectorizedHashCode: return inline_vectorizedHashCode();
307
308 case vmIntrinsics::_toBytesStringU: return inline_string_toBytesU();
309 case vmIntrinsics::_getCharsStringU: return inline_string_getCharsU();
310 case vmIntrinsics::_getCharStringU: return inline_string_char_access(!is_store);
311 case vmIntrinsics::_putCharStringU: return inline_string_char_access( is_store);
312
313 case vmIntrinsics::_compressStringC:
314 case vmIntrinsics::_compressStringB: return inline_string_copy( is_compress);
315 case vmIntrinsics::_inflateStringC:
316 case vmIntrinsics::_inflateStringB: return inline_string_copy(!is_compress);
317
318 case vmIntrinsics::_getReference: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false);
319 case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_store, T_BOOLEAN, Relaxed, false);
320 case vmIntrinsics::_getByte: return inline_unsafe_access(!is_store, T_BYTE, Relaxed, false);
321 case vmIntrinsics::_getShort: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, false);
322 case vmIntrinsics::_getChar: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, false);
323 case vmIntrinsics::_getInt: return inline_unsafe_access(!is_store, T_INT, Relaxed, false);
324 case vmIntrinsics::_getLong: return inline_unsafe_access(!is_store, T_LONG, Relaxed, false);
325 case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_store, T_FLOAT, Relaxed, false);
326 case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_store, T_DOUBLE, Relaxed, false);
327
328 case vmIntrinsics::_putReference: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false);
329 case vmIntrinsics::_putBoolean: return inline_unsafe_access( is_store, T_BOOLEAN, Relaxed, false);
330 case vmIntrinsics::_putByte: return inline_unsafe_access( is_store, T_BYTE, Relaxed, false);
331 case vmIntrinsics::_putShort: return inline_unsafe_access( is_store, T_SHORT, Relaxed, false);
332 case vmIntrinsics::_putChar: return inline_unsafe_access( is_store, T_CHAR, Relaxed, false);
333 case vmIntrinsics::_putInt: return inline_unsafe_access( is_store, T_INT, Relaxed, false);
334 case vmIntrinsics::_putLong: return inline_unsafe_access( is_store, T_LONG, Relaxed, false);
335 case vmIntrinsics::_putFloat: return inline_unsafe_access( is_store, T_FLOAT, Relaxed, false);
336 case vmIntrinsics::_putDouble: return inline_unsafe_access( is_store, T_DOUBLE, Relaxed, false);
337
338 case vmIntrinsics::_getReferenceVolatile: return inline_unsafe_access(!is_store, T_OBJECT, Volatile, false);
339 case vmIntrinsics::_getBooleanVolatile: return inline_unsafe_access(!is_store, T_BOOLEAN, Volatile, false);
340 case vmIntrinsics::_getByteVolatile: return inline_unsafe_access(!is_store, T_BYTE, Volatile, false);
341 case vmIntrinsics::_getShortVolatile: return inline_unsafe_access(!is_store, T_SHORT, Volatile, false);
342 case vmIntrinsics::_getCharVolatile: return inline_unsafe_access(!is_store, T_CHAR, Volatile, false);
343 case vmIntrinsics::_getIntVolatile: return inline_unsafe_access(!is_store, T_INT, Volatile, false);
344 case vmIntrinsics::_getLongVolatile: return inline_unsafe_access(!is_store, T_LONG, Volatile, false);
345 case vmIntrinsics::_getFloatVolatile: return inline_unsafe_access(!is_store, T_FLOAT, Volatile, false);
346 case vmIntrinsics::_getDoubleVolatile: return inline_unsafe_access(!is_store, T_DOUBLE, Volatile, false);
347
348 case vmIntrinsics::_putReferenceVolatile: return inline_unsafe_access( is_store, T_OBJECT, Volatile, false);
349 case vmIntrinsics::_putBooleanVolatile: return inline_unsafe_access( is_store, T_BOOLEAN, Volatile, false);
350 case vmIntrinsics::_putByteVolatile: return inline_unsafe_access( is_store, T_BYTE, Volatile, false);
351 case vmIntrinsics::_putShortVolatile: return inline_unsafe_access( is_store, T_SHORT, Volatile, false);
352 case vmIntrinsics::_putCharVolatile: return inline_unsafe_access( is_store, T_CHAR, Volatile, false);
353 case vmIntrinsics::_putIntVolatile: return inline_unsafe_access( is_store, T_INT, Volatile, false);
354 case vmIntrinsics::_putLongVolatile: return inline_unsafe_access( is_store, T_LONG, Volatile, false);
355 case vmIntrinsics::_putFloatVolatile: return inline_unsafe_access( is_store, T_FLOAT, Volatile, false);
356 case vmIntrinsics::_putDoubleVolatile: return inline_unsafe_access( is_store, T_DOUBLE, Volatile, false);
483 "notifyJvmtiEnd", false, true);
484 case vmIntrinsics::_notifyJvmtiVThreadMount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_mount()),
485 "notifyJvmtiMount", false, false);
486 case vmIntrinsics::_notifyJvmtiVThreadUnmount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_unmount()),
487 "notifyJvmtiUnmount", false, false);
488 case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
489 #endif
490
491 #ifdef JFR_HAVE_INTRINSICS
492 case vmIntrinsics::_counterTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
493 case vmIntrinsics::_getEventWriter: return inline_native_getEventWriter();
494 case vmIntrinsics::_jvm_commit: return inline_native_jvm_commit();
495 #endif
496 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
497 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
498 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
499 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
500 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
501 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
502 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
503 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
504 case vmIntrinsics::_getLength: return inline_native_getLength();
505 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
506 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
507 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
508 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
509 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
510 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
511 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
512
513 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
514 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
515
516 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
517
518 case vmIntrinsics::_isInstance:
519 case vmIntrinsics::_isHidden:
520 case vmIntrinsics::_getSuperclass:
521 case vmIntrinsics::_getClassAccessFlags: return inline_native_Class_query(intrinsic_id());
522
523 case vmIntrinsics::_floatToRawIntBits:
524 case vmIntrinsics::_floatToIntBits:
525 case vmIntrinsics::_intBitsToFloat:
526 case vmIntrinsics::_doubleToRawLongBits:
527 case vmIntrinsics::_doubleToLongBits:
528 case vmIntrinsics::_longBitsToDouble:
529 case vmIntrinsics::_floatToFloat16:
530 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
531 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
532 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
533 case vmIntrinsics::_floatIsFinite:
534 case vmIntrinsics::_floatIsInfinite:
2288 case vmIntrinsics::_remainderUnsigned_l: {
2289 zero_check_long(argument(2));
2290 // Compile-time detect of null-exception
2291 if (stopped()) {
2292 return true; // keep the graph constructed so far
2293 }
2294 n = new UModLNode(control(), argument(0), argument(2));
2295 break;
2296 }
2297 default: fatal_unexpected_iid(id); break;
2298 }
2299 set_result(_gvn.transform(n));
2300 return true;
2301 }
2302
2303 //----------------------------inline_unsafe_access----------------------------
2304
2305 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2306 // Attempt to infer a sharper value type from the offset and base type.
2307 ciKlass* sharpened_klass = nullptr;
2308
2309 // See if it is an instance field, with an object type.
2310 if (alias_type->field() != nullptr) {
2311 if (alias_type->field()->type()->is_klass()) {
2312 sharpened_klass = alias_type->field()->type()->as_klass();
2313 }
2314 }
2315
2316 const TypeOopPtr* result = nullptr;
2317 // See if it is a narrow oop array.
2318 if (adr_type->isa_aryptr()) {
2319 if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2320 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2321 if (elem_type != nullptr && elem_type->is_loaded()) {
2322 // Sharpen the value type.
2323 result = elem_type;
2324 }
2325 }
2326 }
2327
2328 // The sharpened class might be unloaded if there is no class loader
2329 // contraint in place.
2330 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2331 // Sharpen the value type.
2332 result = TypeOopPtr::make_from_klass(sharpened_klass);
2333 }
2334 if (result != nullptr) {
2335 #ifndef PRODUCT
2336 if (C->print_intrinsics() || C->print_inlining()) {
2337 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2338 tty->print(" sharpened value: "); result->dump(); tty->cr();
2339 }
2340 #endif
2341 }
2342 return result;
2343 }
2344
2345 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2346 switch (kind) {
2347 case Relaxed:
2348 return MO_UNORDERED;
2349 case Opaque:
2350 return MO_RELAXED;
2351 case Acquire:
2352 return MO_ACQUIRE;
2353 case Release:
2354 return MO_RELEASE;
2355 case Volatile:
2356 return MO_SEQ_CST;
2357 default:
2358 ShouldNotReachHere();
2359 return 0;
2360 }
2361 }
2362
2363 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2364 if (callee()->is_static()) return false; // caller must have the capability!
2365 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2366 guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2367 guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2368 assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2369
2370 if (is_reference_type(type)) {
2371 decorators |= ON_UNKNOWN_OOP_REF;
2372 }
2373
2374 if (unaligned) {
2375 decorators |= C2_UNALIGNED;
2376 }
2377
2378 #ifndef PRODUCT
2379 {
2380 ResourceMark rm;
2381 // Check the signatures.
2382 ciSignature* sig = callee()->signature();
2383 #ifdef ASSERT
2384 if (!is_store) {
2385 // Object getReference(Object base, int/long offset), etc.
2386 BasicType rtype = sig->return_type()->basic_type();
2387 assert(rtype == type, "getter must return the expected value");
2388 assert(sig->count() == 2, "oop getter has 2 arguments");
2389 assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2390 assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2391 } else {
2392 // void putReference(Object base, int/long offset, Object x), etc.
2393 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2394 assert(sig->count() == 3, "oop putter has 3 arguments");
2395 assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2396 assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2397 BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2398 assert(vtype == type, "putter must accept the expected value");
2399 }
2400 #endif // ASSERT
2401 }
2402 #endif //PRODUCT
2403
2404 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2405
2406 Node* receiver = argument(0); // type: oop
2407
2408 // Build address expression.
2409 Node* heap_base_oop = top();
2410
2411 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2412 Node* base = argument(1); // type: oop
2413 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2414 Node* offset = argument(2); // type: long
2415 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2416 // to be plain byte offsets, which are also the same as those accepted
2417 // by oopDesc::field_addr.
2418 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2419 "fieldOffset must be byte-scaled");
2420 // 32-bit machines ignore the high half!
2421 offset = ConvL2X(offset);
2422
2423 // Save state and restore on bailout
2424 uint old_sp = sp();
2425 SafePointNode* old_map = clone_map();
2426
2427 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2428 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2429
2430 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2431 if (type != T_OBJECT) {
2432 decorators |= IN_NATIVE; // off-heap primitive access
2433 } else {
2434 set_map(old_map);
2435 set_sp(old_sp);
2436 return false; // off-heap oop accesses are not supported
2437 }
2438 } else {
2439 heap_base_oop = base; // on-heap or mixed access
2440 }
2441
2442 // Can base be null? Otherwise, always on-heap access.
2443 bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2444
2445 if (!can_access_non_heap) {
2446 decorators |= IN_HEAP;
2447 }
2448
2449 Node* val = is_store ? argument(4) : nullptr;
2450
2451 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2452 if (adr_type == TypePtr::NULL_PTR) {
2453 set_map(old_map);
2454 set_sp(old_sp);
2455 return false; // off-heap access with zero address
2456 }
2457
2458 // Try to categorize the address.
2459 Compile::AliasType* alias_type = C->alias_type(adr_type);
2460 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2461
2462 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2463 alias_type->adr_type() == TypeAryPtr::RANGE) {
2464 set_map(old_map);
2465 set_sp(old_sp);
2466 return false; // not supported
2467 }
2468
2469 bool mismatched = false;
2470 BasicType bt = alias_type->basic_type();
2471 if (bt != T_ILLEGAL) {
2472 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2473 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2474 // Alias type doesn't differentiate between byte[] and boolean[]).
2475 // Use address type to get the element type.
2476 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2477 }
2478 if (is_reference_type(bt, true)) {
2479 // accessing an array field with getReference is not a mismatch
2480 bt = T_OBJECT;
2481 }
2482 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2483 // Don't intrinsify mismatched object accesses
2484 set_map(old_map);
2485 set_sp(old_sp);
2486 return false;
2487 }
2488 mismatched = (bt != type);
2489 } else if (alias_type->adr_type()->isa_oopptr()) {
2490 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2491 }
2492
2493 destruct_map_clone(old_map);
2494 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2495
2496 if (mismatched) {
2497 decorators |= C2_MISMATCHED;
2498 }
2499
2500 // First guess at the value type.
2501 const Type *value_type = Type::get_const_basic_type(type);
2502
2503 // Figure out the memory ordering.
2504 decorators |= mo_decorator_for_access_kind(kind);
2505
2506 if (!is_store && type == T_OBJECT) {
2507 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2508 if (tjp != nullptr) {
2509 value_type = tjp;
2510 }
2511 }
2512
2513 receiver = null_check(receiver);
2514 if (stopped()) {
2515 return true;
2516 }
2517 // Heap pointers get a null-check from the interpreter,
2518 // as a courtesy. However, this is not guaranteed by Unsafe,
2519 // and it is not possible to fully distinguish unintended nulls
2520 // from intended ones in this API.
2521
2522 if (!is_store) {
2523 Node* p = nullptr;
2524 // Try to constant fold a load from a constant field
2525 ciField* field = alias_type->field();
2526 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !mismatched) {
2527 // final or stable field
2528 p = make_constant_from_field(field, heap_base_oop);
2529 }
2530
2531 if (p == nullptr) { // Could not constant fold the load
2532 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2533 // Normalize the value returned by getBoolean in the following cases
2534 if (type == T_BOOLEAN &&
2535 (mismatched ||
2536 heap_base_oop == top() || // - heap_base_oop is null or
2537 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2538 // and the unsafe access is made to large offset
2539 // (i.e., larger than the maximum offset necessary for any
2540 // field access)
2541 ) {
2542 IdealKit ideal = IdealKit(this);
2543 #define __ ideal.
2544 IdealVariable normalized_result(ideal);
2545 __ declarations_done();
2546 __ set(normalized_result, p);
2547 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2548 __ set(normalized_result, ideal.ConI(1));
2549 ideal.end_if();
2550 final_sync(ideal);
2551 p = __ value(normalized_result);
2552 #undef __
2553 }
2554 }
2555 if (type == T_ADDRESS) {
2556 p = gvn().transform(new CastP2XNode(nullptr, p));
2557 p = ConvX2UL(p);
2558 }
2559 // The load node has the control of the preceding MemBarCPUOrder. All
2560 // following nodes will have the control of the MemBarCPUOrder inserted at
2561 // the end of this method. So, pushing the load onto the stack at a later
2562 // point is fine.
2563 set_result(p);
2564 } else {
2565 if (bt == T_ADDRESS) {
2566 // Repackage the long as a pointer.
2567 val = ConvL2X(val);
2568 val = gvn().transform(new CastX2PNode(val));
2569 }
2570 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2571 }
2572
2573 return true;
2574 }
2575
2576 //----------------------------inline_unsafe_load_store----------------------------
2577 // This method serves a couple of different customers (depending on LoadStoreKind):
2578 //
2579 // LS_cmp_swap:
2580 //
2581 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2582 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2583 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2584 //
2585 // LS_cmp_swap_weak:
2586 //
2587 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2588 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2589 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2590 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2591 //
2592 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2593 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2594 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2595 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
2761 }
2762 case LS_cmp_swap:
2763 case LS_cmp_swap_weak:
2764 case LS_get_add:
2765 break;
2766 default:
2767 ShouldNotReachHere();
2768 }
2769
2770 // Null check receiver.
2771 receiver = null_check(receiver);
2772 if (stopped()) {
2773 return true;
2774 }
2775
2776 int alias_idx = C->get_alias_index(adr_type);
2777
2778 if (is_reference_type(type)) {
2779 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2780
2781 // Transformation of a value which could be null pointer (CastPP #null)
2782 // could be delayed during Parse (for example, in adjust_map_after_if()).
2783 // Execute transformation here to avoid barrier generation in such case.
2784 if (_gvn.type(newval) == TypePtr::NULL_PTR)
2785 newval = _gvn.makecon(TypePtr::NULL_PTR);
2786
2787 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2788 // Refine the value to a null constant, when it is known to be null
2789 oldval = _gvn.makecon(TypePtr::NULL_PTR);
2790 }
2791 }
2792
2793 Node* result = nullptr;
2794 switch (kind) {
2795 case LS_cmp_exchange: {
2796 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2797 oldval, newval, value_type, type, decorators);
2798 break;
2799 }
2800 case LS_cmp_swap_weak:
2947 Deoptimization::Action_make_not_entrant);
2948 }
2949 if (stopped()) {
2950 return true;
2951 }
2952 #endif //INCLUDE_JVMTI
2953
2954 Node* test = nullptr;
2955 if (LibraryCallKit::klass_needs_init_guard(kls)) {
2956 // Note: The argument might still be an illegal value like
2957 // Serializable.class or Object[].class. The runtime will handle it.
2958 // But we must make an explicit check for initialization.
2959 Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
2960 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
2961 // can generate code to load it as unsigned byte.
2962 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
2963 Node* bits = intcon(InstanceKlass::fully_initialized);
2964 test = _gvn.transform(new SubINode(inst, bits));
2965 // The 'test' is non-zero if we need to take a slow path.
2966 }
2967
2968 Node* obj = new_instance(kls, test);
2969 set_result(obj);
2970 return true;
2971 }
2972
2973 //------------------------inline_native_time_funcs--------------
2974 // inline code for System.currentTimeMillis() and System.nanoTime()
2975 // these have the same type and signature
2976 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
2977 const TypeFunc* tf = OptoRuntime::void_long_Type();
2978 const TypePtr* no_memory_effects = nullptr;
2979 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
2980 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
2981 #ifdef ASSERT
2982 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
2983 assert(value_top == top(), "second value must be top");
2984 #endif
2985 set_result(value);
2986 return true;
2987 }
2988
3729 Node* thread = _gvn.transform(new ThreadLocalNode());
3730 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
3731 Node* thread_obj_handle
3732 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3733 thread_obj_handle = _gvn.transform(thread_obj_handle);
3734 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3735 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3736
3737 // Change the _monitor_owner_id of the JavaThread
3738 Node* tid = load_field_from_object(arr, "tid", "J");
3739 Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3740 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3741
3742 JFR_ONLY(extend_setCurrentThread(thread, arr);)
3743 return true;
3744 }
3745
3746 const Type* LibraryCallKit::scopedValueCache_type() {
3747 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3748 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3749 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS);
3750
3751 // Because we create the scopedValue cache lazily we have to make the
3752 // type of the result BotPTR.
3753 bool xk = etype->klass_is_exact();
3754 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, 0);
3755 return objects_type;
3756 }
3757
3758 Node* LibraryCallKit::scopedValueCache_helper() {
3759 Node* thread = _gvn.transform(new ThreadLocalNode());
3760 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
3761 // We cannot use immutable_memory() because we might flip onto a
3762 // different carrier thread, at which point we'll need to use that
3763 // carrier thread's cache.
3764 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3765 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3766 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3767 }
3768
3769 //------------------------inline_native_scopedValueCache------------------
3770 bool LibraryCallKit::inline_native_scopedValueCache() {
3771 Node* cache_obj_handle = scopedValueCache_helper();
3772 const Type* objects_type = scopedValueCache_type();
3773 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3774
3858 store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
3859
3860 // Result of top level CFG and Memory.
3861 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3862 record_for_igvn(result_rgn);
3863 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3864 record_for_igvn(result_mem);
3865
3866 result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
3867 result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
3868 result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3869 result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
3870
3871 // Set output state.
3872 set_control(_gvn.transform(result_rgn));
3873 set_all_memory(_gvn.transform(result_mem));
3874
3875 return true;
3876 }
3877
3878 //---------------------------load_mirror_from_klass----------------------------
3879 // Given a klass oop, load its java mirror (a java.lang.Class oop).
3880 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
3881 Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
3882 Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3883 // mirror = ((OopHandle)mirror)->resolve();
3884 return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
3885 }
3886
3887 //-----------------------load_klass_from_mirror_common-------------------------
3888 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
3889 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
3890 // and branch to the given path on the region.
3891 // If never_see_null, take an uncommon trap on null, so we can optimistically
3892 // compile for the non-null case.
3893 // If the region is null, force never_see_null = true.
3894 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
3895 bool never_see_null,
3896 RegionNode* region,
3897 int null_path,
3898 int offset) {
3899 if (region == nullptr) never_see_null = true;
3900 Node* p = basic_plus_adr(mirror, offset);
3901 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
3902 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
3903 Node* null_ctl = top();
3904 kls = null_check_oop(kls, &null_ctl, never_see_null);
3905 if (region != nullptr) {
3906 // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
3910 }
3911 return kls;
3912 }
3913
3914 //--------------------(inline_native_Class_query helpers)---------------------
3915 // Use this for JVM_ACC_INTERFACE.
3916 // Fall through if (mods & mask) == bits, take the guard otherwise.
3917 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
3918 ByteSize offset, const Type* type, BasicType bt) {
3919 // Branch around if the given klass has the given modifier bit set.
3920 // Like generate_guard, adds a new path onto the region.
3921 Node* modp = basic_plus_adr(kls, in_bytes(offset));
3922 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
3923 Node* mask = intcon(modifier_mask);
3924 Node* bits = intcon(modifier_bits);
3925 Node* mbit = _gvn.transform(new AndINode(mods, mask));
3926 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
3927 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3928 return generate_fair_guard(bol, region);
3929 }
3930 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3931 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
3932 Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
3933 }
3934
3935 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
3936 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3937 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
3938 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
3939 }
3940
3941 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
3942 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
3943 }
3944
3945 //-------------------------inline_native_Class_query-------------------
3946 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
3947 const Type* return_type = TypeInt::BOOL;
3948 Node* prim_return_value = top(); // what happens if it's a primitive class?
3949 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4068
4069 case vmIntrinsics::_getClassAccessFlags:
4070 p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
4071 query_value = make_load(nullptr, p, TypeInt::CHAR, T_CHAR, MemNode::unordered);
4072 break;
4073
4074 default:
4075 fatal_unexpected_iid(id);
4076 break;
4077 }
4078
4079 // Fall-through is the normal case of a query to a real class.
4080 phi->init_req(1, query_value);
4081 region->init_req(1, control());
4082
4083 C->set_has_split_ifs(true); // Has chance for split-if optimization
4084 set_result(region, phi);
4085 return true;
4086 }
4087
4088 //-------------------------inline_Class_cast-------------------
4089 bool LibraryCallKit::inline_Class_cast() {
4090 Node* mirror = argument(0); // Class
4091 Node* obj = argument(1);
4092 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4093 if (mirror_con == nullptr) {
4094 return false; // dead path (mirror->is_top()).
4095 }
4096 if (obj == nullptr || obj->is_top()) {
4097 return false; // dead path
4098 }
4099 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4100
4101 // First, see if Class.cast() can be folded statically.
4102 // java_mirror_type() returns non-null for compile-time Class constants.
4103 ciType* tm = mirror_con->java_mirror_type();
4104 if (tm != nullptr && tm->is_klass() &&
4105 tp != nullptr) {
4106 if (!tp->is_loaded()) {
4107 // Don't use intrinsic when class is not loaded.
4108 return false;
4109 } else {
4110 int static_res = C->static_subtype_check(TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces), tp->as_klass_type());
4111 if (static_res == Compile::SSC_always_true) {
4112 // isInstance() is true - fold the code.
4113 set_result(obj);
4114 return true;
4115 } else if (static_res == Compile::SSC_always_false) {
4116 // Don't use intrinsic, have to throw ClassCastException.
4117 // If the reference is null, the non-intrinsic bytecode will
4118 // be optimized appropriately.
4119 return false;
4120 }
4121 }
4122 }
4123
4124 // Bailout intrinsic and do normal inlining if exception path is frequent.
4125 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4126 return false;
4127 }
4128
4129 // Generate dynamic checks.
4130 // Class.cast() is java implementation of _checkcast bytecode.
4131 // Do checkcast (Parse::do_checkcast()) optimizations here.
4132
4133 mirror = null_check(mirror);
4134 // If mirror is dead, only null-path is taken.
4135 if (stopped()) {
4136 return true;
4137 }
4138
4139 // Not-subtype or the mirror's klass ptr is null (in case it is a primitive).
4140 enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
4141 RegionNode* region = new RegionNode(PATH_LIMIT);
4142 record_for_igvn(region);
4143
4144 // Now load the mirror's klass metaobject, and null-check it.
4145 // If kls is null, we have a primitive mirror and
4146 // nothing is an instance of a primitive type.
4147 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4148
4149 Node* res = top();
4150 if (!stopped()) {
4151 Node* bad_type_ctrl = top();
4152 // Do checkcast optimizations.
4153 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4154 region->init_req(_bad_type_path, bad_type_ctrl);
4155 }
4156 if (region->in(_prim_path) != top() ||
4157 region->in(_bad_type_path) != top()) {
4158 // Let Interpreter throw ClassCastException.
4159 PreserveJVMState pjvms(this);
4160 set_control(_gvn.transform(region));
4161 uncommon_trap(Deoptimization::Reason_intrinsic,
4162 Deoptimization::Action_maybe_recompile);
4163 }
4164 if (!stopped()) {
4165 set_result(res);
4166 }
4167 return true;
4168 }
4169
4170
4171 //--------------------------inline_native_subtype_check------------------------
4172 // This intrinsic takes the JNI calls out of the heart of
4173 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4174 bool LibraryCallKit::inline_native_subtype_check() {
4175 // Pull both arguments off the stack.
4176 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4177 args[0] = argument(0);
4178 args[1] = argument(1);
4179 Node* klasses[2]; // corresponding Klasses: superk, subk
4180 klasses[0] = klasses[1] = top();
4181
4182 enum {
4183 // A full decision tree on {superc is prim, subc is prim}:
4184 _prim_0_path = 1, // {P,N} => false
4185 // {P,P} & superc!=subc => false
4186 _prim_same_path, // {P,P} & superc==subc => true
4187 _prim_1_path, // {N,P} => false
4188 _ref_subtype_path, // {N,N} & subtype check wins => true
4189 _both_ref_path, // {N,N} & subtype check loses => false
4190 PATH_LIMIT
4191 };
4192
4193 RegionNode* region = new RegionNode(PATH_LIMIT);
4194 Node* phi = new PhiNode(region, TypeInt::BOOL);
4195 record_for_igvn(region);
4196
4197 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4198 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4199 int class_klass_offset = java_lang_Class::klass_offset();
4200
4201 // First null-check both mirrors and load each mirror's klass metaobject.
4202 int which_arg;
4203 for (which_arg = 0; which_arg <= 1; which_arg++) {
4204 Node* arg = args[which_arg];
4205 arg = null_check(arg);
4206 if (stopped()) break;
4207 args[which_arg] = arg;
4208
4209 Node* p = basic_plus_adr(arg, class_klass_offset);
4210 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4211 klasses[which_arg] = _gvn.transform(kls);
4212 }
4213
4214 // Having loaded both klasses, test each for null.
4215 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4216 for (which_arg = 0; which_arg <= 1; which_arg++) {
4217 Node* kls = klasses[which_arg];
4218 Node* null_ctl = top();
4219 kls = null_check_oop(kls, &null_ctl, never_see_null);
4220 int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
4221 region->init_req(prim_path, null_ctl);
4222 if (stopped()) break;
4223 klasses[which_arg] = kls;
4224 }
4225
4226 if (!stopped()) {
4227 // now we have two reference types, in klasses[0..1]
4228 Node* subk = klasses[1]; // the argument to isAssignableFrom
4229 Node* superk = klasses[0]; // the receiver
4230 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4231 // now we have a successful reference subtype check
4232 region->set_req(_ref_subtype_path, control());
4233 }
4234
4235 // If both operands are primitive (both klasses null), then
4236 // we must return true when they are identical primitives.
4237 // It is convenient to test this after the first null klass check.
4238 set_control(region->in(_prim_0_path)); // go back to first null check
4239 if (!stopped()) {
4240 // Since superc is primitive, make a guard for the superc==subc case.
4241 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4242 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4243 generate_guard(bol_eq, region, PROB_FAIR);
4244 if (region->req() == PATH_LIMIT+1) {
4245 // A guard was added. If the added guard is taken, superc==subc.
4246 region->swap_edges(PATH_LIMIT, _prim_same_path);
4247 region->del_req(PATH_LIMIT);
4248 }
4249 region->set_req(_prim_0_path, control()); // Not equal after all.
4250 }
4251
4252 // these are the only paths that produce 'true':
4253 phi->set_req(_prim_same_path, intcon(1));
4254 phi->set_req(_ref_subtype_path, intcon(1));
4255
4256 // pull together the cases:
4257 assert(region->req() == PATH_LIMIT, "sane region");
4258 for (uint i = 1; i < region->req(); i++) {
4259 Node* ctl = region->in(i);
4260 if (ctl == nullptr || ctl == top()) {
4261 region->set_req(i, top());
4262 phi ->set_req(i, top());
4263 } else if (phi->in(i) == nullptr) {
4264 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4265 }
4266 }
4267
4268 set_control(_gvn.transform(region));
4269 set_result(_gvn.transform(phi));
4270 return true;
4271 }
4272
4273 //---------------------generate_array_guard_common------------------------
4274 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
4275 bool obj_array, bool not_array, Node** obj) {
4276
4277 if (stopped()) {
4278 return nullptr;
4279 }
4280
4281 // If obj_array/non_array==false/false:
4282 // Branch around if the given klass is in fact an array (either obj or prim).
4283 // If obj_array/non_array==false/true:
4284 // Branch around if the given klass is not an array klass of any kind.
4285 // If obj_array/non_array==true/true:
4286 // Branch around if the kls is not an oop array (kls is int[], String, etc.)
4287 // If obj_array/non_array==true/false:
4288 // Branch around if the kls is an oop array (Object[] or subtype)
4289 //
4290 // Like generate_guard, adds a new path onto the region.
4291 jint layout_con = 0;
4292 Node* layout_val = get_layout_helper(kls, layout_con);
4293 if (layout_val == nullptr) {
4294 bool query = (obj_array
4295 ? Klass::layout_helper_is_objArray(layout_con)
4296 : Klass::layout_helper_is_array(layout_con));
4297 if (query == not_array) {
4298 return nullptr; // never a branch
4299 } else { // always a branch
4300 Node* always_branch = control();
4301 if (region != nullptr)
4302 region->add_req(always_branch);
4303 set_control(top());
4304 return always_branch;
4305 }
4306 }
4307 // Now test the correct condition.
4308 jint nval = (obj_array
4309 ? (jint)(Klass::_lh_array_tag_type_value
4310 << Klass::_lh_array_tag_shift)
4311 : Klass::_lh_neutral_value);
4312 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4313 BoolTest::mask btest = BoolTest::lt; // correct for testing is_[obj]array
4314 // invert the test if we are looking for a non-array
4315 if (not_array) btest = BoolTest(btest).negate();
4316 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4317 Node* ctrl = generate_fair_guard(bol, region);
4318 Node* is_array_ctrl = not_array ? control() : ctrl;
4319 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4320 // Keep track of the fact that 'obj' is an array to prevent
4321 // array specific accesses from floating above the guard.
4322 *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4323 }
4324 return ctrl;
4325 }
4326
4327
4328 //-----------------------inline_native_newArray--------------------------
4329 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
4330 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4331 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4332 Node* mirror;
4333 Node* count_val;
4334 if (uninitialized) {
4335 null_check_receiver();
4336 mirror = argument(1);
4337 count_val = argument(2);
4338 } else {
4339 mirror = argument(0);
4340 count_val = argument(1);
4341 }
4342
4343 mirror = null_check(mirror);
4344 // If mirror or obj is dead, only null-path is taken.
4345 if (stopped()) return true;
4346
4347 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4348 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4349 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4455 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4456 { PreserveReexecuteState preexecs(this);
4457 jvms()->set_should_reexecute(true);
4458
4459 array_type_mirror = null_check(array_type_mirror);
4460 original = null_check(original);
4461
4462 // Check if a null path was taken unconditionally.
4463 if (stopped()) return true;
4464
4465 Node* orig_length = load_array_length(original);
4466
4467 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4468 klass_node = null_check(klass_node);
4469
4470 RegionNode* bailout = new RegionNode(1);
4471 record_for_igvn(bailout);
4472
4473 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4474 // Bail out if that is so.
4475 Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
4476 if (not_objArray != nullptr) {
4477 // Improve the klass node's type from the new optimistic assumption:
4478 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4479 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
4480 Node* cast = new CastPPNode(control(), klass_node, akls);
4481 klass_node = _gvn.transform(cast);
4482 }
4483
4484 // Bail out if either start or end is negative.
4485 generate_negative_guard(start, bailout, &start);
4486 generate_negative_guard(end, bailout, &end);
4487
4488 Node* length = end;
4489 if (_gvn.type(start) != TypeInt::ZERO) {
4490 length = _gvn.transform(new SubINode(end, start));
4491 }
4492
4493 // Bail out if length is negative (i.e., if start > end).
4494 // Without this the new_array would throw
4495 // NegativeArraySizeException but IllegalArgumentException is what
4496 // should be thrown
4497 generate_negative_guard(length, bailout, &length);
4498
4499 // Bail out if start is larger than the original length
4500 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4501 generate_negative_guard(orig_tail, bailout, &orig_tail);
4502
4503 if (bailout->req() > 1) {
4504 PreserveJVMState pjvms(this);
4505 set_control(_gvn.transform(bailout));
4506 uncommon_trap(Deoptimization::Reason_intrinsic,
4507 Deoptimization::Action_maybe_recompile);
4508 }
4509
4510 if (!stopped()) {
4511 // How many elements will we copy from the original?
4512 // The answer is MinI(orig_tail, length).
4513 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4514
4515 // Generate a direct call to the right arraycopy function(s).
4516 // We know the copy is disjoint but we might not know if the
4517 // oop stores need checking.
4518 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
4524 // to the copyOf to be validated, including that the copy to the
4525 // new array won't trigger an ArrayStoreException. That subtype
4526 // check can be optimized if we know something on the type of
4527 // the input array from type speculation.
4528 if (_gvn.type(klass_node)->singleton()) {
4529 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
4530 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
4531
4532 int test = C->static_subtype_check(superk, subk);
4533 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4534 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4535 if (t_original->speculative_type() != nullptr) {
4536 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4537 }
4538 }
4539 }
4540
4541 bool validated = false;
4542 // Reason_class_check rather than Reason_intrinsic because we
4543 // want to intrinsify even if this traps.
4544 if (!too_many_traps(Deoptimization::Reason_class_check)) {
4545 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4546
4547 if (not_subtype_ctrl != top()) {
4548 PreserveJVMState pjvms(this);
4549 set_control(not_subtype_ctrl);
4550 uncommon_trap(Deoptimization::Reason_class_check,
4551 Deoptimization::Action_make_not_entrant);
4552 assert(stopped(), "Should be stopped");
4553 }
4554 validated = true;
4555 }
4556
4557 if (!stopped()) {
4558 newcopy = new_array(klass_node, length, 0); // no arguments to push
4559
4560 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4561 load_object_klass(original), klass_node);
4562 if (!is_copyOfRange) {
4563 ac->set_copyof(validated);
4564 } else {
4610
4611 //-----------------------generate_method_call----------------------------
4612 // Use generate_method_call to make a slow-call to the real
4613 // method if the fast path fails. An alternative would be to
4614 // use a stub like OptoRuntime::slow_arraycopy_Java.
4615 // This only works for expanding the current library call,
4616 // not another intrinsic. (E.g., don't use this for making an
4617 // arraycopy call inside of the copyOf intrinsic.)
4618 CallJavaNode*
4619 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4620 // When compiling the intrinsic method itself, do not use this technique.
4621 guarantee(callee() != C->method(), "cannot make slow-call to self");
4622
4623 ciMethod* method = callee();
4624 // ensure the JVMS we have will be correct for this call
4625 guarantee(method_id == method->intrinsic_id(), "must match");
4626
4627 const TypeFunc* tf = TypeFunc::make(method);
4628 if (res_not_null) {
4629 assert(tf->return_type() == T_OBJECT, "");
4630 const TypeTuple* range = tf->range();
4631 const Type** fields = TypeTuple::fields(range->cnt());
4632 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4633 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4634 tf = TypeFunc::make(tf->domain(), new_range);
4635 }
4636 CallJavaNode* slow_call;
4637 if (is_static) {
4638 assert(!is_virtual, "");
4639 slow_call = new CallStaticJavaNode(C, tf,
4640 SharedRuntime::get_resolve_static_call_stub(), method);
4641 } else if (is_virtual) {
4642 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4643 int vtable_index = Method::invalid_vtable_index;
4644 if (UseInlineCaches) {
4645 // Suppress the vtable call
4646 } else {
4647 // hashCode and clone are not a miranda methods,
4648 // so the vtable index is fixed.
4649 // No need to use the linkResolver to get it.
4650 vtable_index = method->vtable_index();
4651 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4652 "bad index %d", vtable_index);
4653 }
4654 slow_call = new CallDynamicJavaNode(tf,
4671 set_edges_for_java_call(slow_call);
4672 return slow_call;
4673 }
4674
4675
4676 /**
4677 * Build special case code for calls to hashCode on an object. This call may
4678 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4679 * slightly different code.
4680 */
4681 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4682 assert(is_static == callee()->is_static(), "correct intrinsic selection");
4683 assert(!(is_virtual && is_static), "either virtual, special, or static");
4684
4685 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4686
4687 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4688 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
4689 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
4690 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4691 Node* obj = nullptr;
4692 if (!is_static) {
4693 // Check for hashing null object
4694 obj = null_check_receiver();
4695 if (stopped()) return true; // unconditionally null
4696 result_reg->init_req(_null_path, top());
4697 result_val->init_req(_null_path, top());
4698 } else {
4699 // Do a null check, and return zero if null.
4700 // System.identityHashCode(null) == 0
4701 obj = argument(0);
4702 Node* null_ctl = top();
4703 obj = null_check_oop(obj, &null_ctl);
4704 result_reg->init_req(_null_path, null_ctl);
4705 result_val->init_req(_null_path, _gvn.intcon(0));
4706 }
4707
4708 // Unconditionally null? Then return right away.
4709 if (stopped()) {
4710 set_control( result_reg->in(_null_path));
4711 if (!stopped())
4712 set_result(result_val->in(_null_path));
4713 return true;
4714 }
4715
4716 // We only go to the fast case code if we pass a number of guards. The
4717 // paths which do not pass are accumulated in the slow_region.
4718 RegionNode* slow_region = new RegionNode(1);
4719 record_for_igvn(slow_region);
4720
4721 // If this is a virtual call, we generate a funny guard. We pull out
4722 // the vtable entry corresponding to hashCode() from the target object.
4723 // If the target method which we are calling happens to be the native
4724 // Object hashCode() method, we pass the guard. We do not need this
4725 // guard for non-virtual calls -- the caller is known to be the native
4726 // Object hashCode().
4727 if (is_virtual) {
4728 // After null check, get the object's klass.
4729 Node* obj_klass = load_object_klass(obj);
4730 generate_virtual_guard(obj_klass, slow_region);
4731 }
4732
4733 // Get the header out of the object, use LoadMarkNode when available
4734 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4735 // The control of the load must be null. Otherwise, the load can move before
4736 // the null check after castPP removal.
4737 Node* no_ctrl = nullptr;
4738 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4739
4740 if (!UseObjectMonitorTable) {
4741 // Test the header to see if it is safe to read w.r.t. locking.
4742 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
4743 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4744 if (LockingMode == LM_LIGHTWEIGHT) {
4745 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
4746 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
4747 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
4748
4749 generate_slow_guard(test_monitor, slow_region);
4750 } else {
4751 Node *unlocked_val = _gvn.MakeConX(markWord::unlocked_value);
4752 Node *chk_unlocked = _gvn.transform(new CmpXNode(lmasked_header, unlocked_val));
4753 Node *test_not_unlocked = _gvn.transform(new BoolNode(chk_unlocked, BoolTest::ne));
4754
4755 generate_slow_guard(test_not_unlocked, slow_region);
4756 }
4757 }
4758
4759 // Get the hash value and check to see that it has been properly assigned.
4760 // We depend on hash_mask being at most 32 bits and avoid the use of
4761 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4762 // vm: see markWord.hpp.
4797 // this->control() comes from set_results_for_java_call
4798 result_reg->init_req(_slow_path, control());
4799 result_val->init_req(_slow_path, slow_result);
4800 result_io ->set_req(_slow_path, i_o());
4801 result_mem ->set_req(_slow_path, reset_memory());
4802 }
4803
4804 // Return the combined state.
4805 set_i_o( _gvn.transform(result_io) );
4806 set_all_memory( _gvn.transform(result_mem));
4807
4808 set_result(result_reg, result_val);
4809 return true;
4810 }
4811
4812 //---------------------------inline_native_getClass----------------------------
4813 // public final native Class<?> java.lang.Object.getClass();
4814 //
4815 // Build special case code for calls to getClass on an object.
4816 bool LibraryCallKit::inline_native_getClass() {
4817 Node* obj = null_check_receiver();
4818 if (stopped()) return true;
4819 set_result(load_mirror_from_klass(load_object_klass(obj)));
4820 return true;
4821 }
4822
4823 //-----------------inline_native_Reflection_getCallerClass---------------------
4824 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4825 //
4826 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4827 //
4828 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4829 // in that it must skip particular security frames and checks for
4830 // caller sensitive methods.
4831 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4832 #ifndef PRODUCT
4833 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4834 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4835 }
4836 #endif
4837
5149 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5150
5151 flags |= RC_NARROW_MEM; // narrow in memory
5152 }
5153
5154 // Call it. Note that the length argument is not scaled.
5155 make_runtime_call(flags,
5156 OptoRuntime::unsafe_setmemory_Type(),
5157 StubRoutines::unsafe_setmemory(),
5158 "unsafe_setmemory",
5159 dst_type,
5160 dst_addr, size XTOP, byte);
5161
5162 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5163
5164 return true;
5165 }
5166
5167 #undef XTOP
5168
5169 //------------------------clone_coping-----------------------------------
5170 // Helper function for inline_native_clone.
5171 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5172 assert(obj_size != nullptr, "");
5173 Node* raw_obj = alloc_obj->in(1);
5174 assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5175
5176 AllocateNode* alloc = nullptr;
5177 if (ReduceBulkZeroing &&
5178 // If we are implementing an array clone without knowing its source type
5179 // (can happen when compiling the array-guarded branch of a reflective
5180 // Object.clone() invocation), initialize the array within the allocation.
5181 // This is needed because some GCs (e.g. ZGC) might fall back in this case
5182 // to a runtime clone call that assumes fully initialized source arrays.
5183 (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5184 // We will be completely responsible for initializing this object -
5185 // mark Initialize node as complete.
5186 alloc = AllocateNode::Ideal_allocation(alloc_obj);
5187 // The object was just allocated - there should be no any stores!
5188 guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5219 // not cloneable or finalizer => slow path to out-of-line Object.clone
5220 //
5221 // The general case has two steps, allocation and copying.
5222 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5223 //
5224 // Copying also has two cases, oop arrays and everything else.
5225 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5226 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5227 //
5228 // These steps fold up nicely if and when the cloned object's klass
5229 // can be sharply typed as an object array, a type array, or an instance.
5230 //
5231 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5232 PhiNode* result_val;
5233
5234 // Set the reexecute bit for the interpreter to reexecute
5235 // the bytecode that invokes Object.clone if deoptimization happens.
5236 { PreserveReexecuteState preexecs(this);
5237 jvms()->set_should_reexecute(true);
5238
5239 Node* obj = null_check_receiver();
5240 if (stopped()) return true;
5241
5242 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5243
5244 // If we are going to clone an instance, we need its exact type to
5245 // know the number and types of fields to convert the clone to
5246 // loads/stores. Maybe a speculative type can help us.
5247 if (!obj_type->klass_is_exact() &&
5248 obj_type->speculative_type() != nullptr &&
5249 obj_type->speculative_type()->is_instance_klass()) {
5250 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5251 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5252 !spec_ik->has_injected_fields()) {
5253 if (!obj_type->isa_instptr() ||
5254 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5255 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5256 }
5257 }
5258 }
5259
5260 // Conservatively insert a memory barrier on all memory slices.
5261 // Do not let writes into the original float below the clone.
5262 insert_mem_bar(Op_MemBarCPUOrder);
5263
5264 // paths into result_reg:
5265 enum {
5266 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5267 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5268 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5269 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5270 PATH_LIMIT
5271 };
5272 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5273 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5274 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5275 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5276 record_for_igvn(result_reg);
5277
5278 Node* obj_klass = load_object_klass(obj);
5279 Node* array_obj = obj;
5280 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5281 if (array_ctl != nullptr) {
5282 // It's an array.
5283 PreserveJVMState pjvms(this);
5284 set_control(array_ctl);
5285 Node* obj_length = load_array_length(array_obj);
5286 Node* array_size = nullptr; // Size of the array without object alignment padding.
5287 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5288
5289 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5290 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5291 // If it is an oop array, it requires very special treatment,
5292 // because gc barriers are required when accessing the array.
5293 Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5294 if (is_obja != nullptr) {
5295 PreserveJVMState pjvms2(this);
5296 set_control(is_obja);
5297 // Generate a direct call to the right arraycopy function(s).
5298 // Clones are always tightly coupled.
5299 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5300 ac->set_clone_oop_array();
5301 Node* n = _gvn.transform(ac);
5302 assert(n == ac, "cannot disappear");
5303 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5304
5305 result_reg->init_req(_objArray_path, control());
5306 result_val->init_req(_objArray_path, alloc_obj);
5307 result_i_o ->set_req(_objArray_path, i_o());
5308 result_mem ->set_req(_objArray_path, reset_memory());
5309 }
5310 }
5311 // Otherwise, there are no barriers to worry about.
5312 // (We can dispense with card marks if we know the allocation
5313 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5314 // causes the non-eden paths to take compensating steps to
5315 // simulate a fresh allocation, so that no further
5316 // card marks are required in compiled code to initialize
5317 // the object.)
5318
5319 if (!stopped()) {
5320 copy_to_clone(array_obj, alloc_obj, array_size, true);
5321
5322 // Present the results of the copy.
5323 result_reg->init_req(_array_path, control());
5324 result_val->init_req(_array_path, alloc_obj);
5325 result_i_o ->set_req(_array_path, i_o());
5326 result_mem ->set_req(_array_path, reset_memory());
5327 }
5328 }
5329
5330 // We only go to the instance fast case code if we pass a number of guards.
5331 // The paths which do not pass are accumulated in the slow_region.
5332 RegionNode* slow_region = new RegionNode(1);
5333 record_for_igvn(slow_region);
5334 if (!stopped()) {
5335 // It's an instance (we did array above). Make the slow-path tests.
5336 // If this is a virtual call, we generate a funny guard. We grab
5337 // the vtable entry corresponding to clone() from the target object.
5338 // If the target method which we are calling happens to be the
5339 // Object clone() method, we pass the guard. We do not need this
5340 // guard for non-virtual calls; the caller is known to be the native
5341 // Object clone().
5342 if (is_virtual) {
5343 generate_virtual_guard(obj_klass, slow_region);
5344 }
5345
5346 // The object must be easily cloneable and must not have a finalizer.
5347 // Both of these conditions may be checked in a single test.
5348 // We could optimize the test further, but we don't care.
5349 generate_misc_flags_guard(obj_klass,
5350 // Test both conditions:
5351 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5352 // Must be cloneable but not finalizer:
5353 KlassFlags::_misc_is_cloneable_fast,
5445 set_jvms(sfpt->jvms());
5446 _reexecute_sp = jvms()->sp();
5447
5448 return saved_jvms;
5449 }
5450 }
5451 }
5452 return nullptr;
5453 }
5454
5455 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5456 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5457 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5458 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5459 uint size = alloc->req();
5460 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5461 old_jvms->set_map(sfpt);
5462 for (uint i = 0; i < size; i++) {
5463 sfpt->init_req(i, alloc->in(i));
5464 }
5465 // re-push array length for deoptimization
5466 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
5467 old_jvms->set_sp(old_jvms->sp()+1);
5468 old_jvms->set_monoff(old_jvms->monoff()+1);
5469 old_jvms->set_scloff(old_jvms->scloff()+1);
5470 old_jvms->set_endoff(old_jvms->endoff()+1);
5471 old_jvms->set_should_reexecute(true);
5472
5473 sfpt->set_i_o(map()->i_o());
5474 sfpt->set_memory(map()->memory());
5475 sfpt->set_control(map()->control());
5476 return sfpt;
5477 }
5478
5479 // In case of a deoptimization, we restart execution at the
5480 // allocation, allocating a new array. We would leave an uninitialized
5481 // array in the heap that GCs wouldn't expect. Move the allocation
5482 // after the traps so we don't allocate the array if we
5483 // deoptimize. This is possible because tightly_coupled_allocation()
5484 // guarantees there's no observer of the allocated array at this point
5485 // and the control flow is simple enough.
5486 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5487 int saved_reexecute_sp, uint new_idx) {
5488 if (saved_jvms_before_guards != nullptr && !stopped()) {
5489 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5490
5491 assert(alloc != nullptr, "only with a tightly coupled allocation");
5492 // restore JVM state to the state at the arraycopy
5493 saved_jvms_before_guards->map()->set_control(map()->control());
5494 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5495 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5496 // If we've improved the types of some nodes (null check) while
5497 // emitting the guards, propagate them to the current state
5498 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5499 set_jvms(saved_jvms_before_guards);
5500 _reexecute_sp = saved_reexecute_sp;
5501
5502 // Remove the allocation from above the guards
5503 CallProjections callprojs;
5504 alloc->extract_projections(&callprojs, true);
5505 InitializeNode* init = alloc->initialization();
5506 Node* alloc_mem = alloc->in(TypeFunc::Memory);
5507 C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5508 C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
5509
5510 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5511 // the allocation (i.e. is only valid if the allocation succeeds):
5512 // 1) replace CastIINode with AllocateArrayNode's length here
5513 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5514 //
5515 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5516 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5517 Node* init_control = init->proj_out(TypeFunc::Control);
5518 Node* alloc_length = alloc->Ideal_length();
5519 #ifdef ASSERT
5520 Node* prev_cast = nullptr;
5521 #endif
5522 for (uint i = 0; i < init_control->outcnt(); i++) {
5523 Node* init_out = init_control->raw_out(i);
5524 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5525 #ifdef ASSERT
5526 if (prev_cast == nullptr) {
5527 prev_cast = init_out;
5529 if (prev_cast->cmp(*init_out) == false) {
5530 prev_cast->dump();
5531 init_out->dump();
5532 assert(false, "not equal CastIINode");
5533 }
5534 }
5535 #endif
5536 C->gvn_replace_by(init_out, alloc_length);
5537 }
5538 }
5539 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5540
5541 // move the allocation here (after the guards)
5542 _gvn.hash_delete(alloc);
5543 alloc->set_req(TypeFunc::Control, control());
5544 alloc->set_req(TypeFunc::I_O, i_o());
5545 Node *mem = reset_memory();
5546 set_all_memory(mem);
5547 alloc->set_req(TypeFunc::Memory, mem);
5548 set_control(init->proj_out_or_null(TypeFunc::Control));
5549 set_i_o(callprojs.fallthrough_ioproj);
5550
5551 // Update memory as done in GraphKit::set_output_for_allocation()
5552 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5553 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5554 if (ary_type->isa_aryptr() && length_type != nullptr) {
5555 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5556 }
5557 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5558 int elemidx = C->get_alias_index(telemref);
5559 set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
5560 set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
5561
5562 Node* allocx = _gvn.transform(alloc);
5563 assert(allocx == alloc, "where has the allocation gone?");
5564 assert(dest->is_CheckCastPP(), "not an allocation result?");
5565
5566 _gvn.hash_delete(dest);
5567 dest->set_req(0, control());
5568 Node* destx = _gvn.transform(dest);
5569 assert(destx == dest, "where has the allocation result gone?");
5867 top_src = src_type->isa_aryptr();
5868 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5869 src_spec = true;
5870 }
5871 if (!has_dest) {
5872 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5873 dest_type = _gvn.type(dest);
5874 top_dest = dest_type->isa_aryptr();
5875 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5876 dest_spec = true;
5877 }
5878 }
5879 }
5880
5881 if (has_src && has_dest && can_emit_guards) {
5882 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
5883 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
5884 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
5885 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
5886
5887 if (src_elem == dest_elem && src_elem == T_OBJECT) {
5888 // If both arrays are object arrays then having the exact types
5889 // for both will remove the need for a subtype check at runtime
5890 // before the call and may make it possible to pick a faster copy
5891 // routine (without a subtype check on every element)
5892 // Do we have the exact type of src?
5893 bool could_have_src = src_spec;
5894 // Do we have the exact type of dest?
5895 bool could_have_dest = dest_spec;
5896 ciKlass* src_k = nullptr;
5897 ciKlass* dest_k = nullptr;
5898 if (!src_spec) {
5899 src_k = src_type->speculative_type_not_null();
5900 if (src_k != nullptr && src_k->is_array_klass()) {
5901 could_have_src = true;
5902 }
5903 }
5904 if (!dest_spec) {
5905 dest_k = dest_type->speculative_type_not_null();
5906 if (dest_k != nullptr && dest_k->is_array_klass()) {
5907 could_have_dest = true;
5908 }
5909 }
5910 if (could_have_src && could_have_dest) {
5911 // If we can have both exact types, emit the missing guards
5912 if (could_have_src && !src_spec) {
5913 src = maybe_cast_profiled_obj(src, src_k, true);
5914 }
5915 if (could_have_dest && !dest_spec) {
5916 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5917 }
5918 }
5919 }
5920 }
5921
5922 ciMethod* trap_method = method();
5923 int trap_bci = bci();
5924 if (saved_jvms_before_guards != nullptr) {
5925 trap_method = alloc->jvms()->method();
5926 trap_bci = alloc->jvms()->bci();
5927 }
5928
5929 bool negative_length_guard_generated = false;
5930
5931 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5932 can_emit_guards &&
5933 !src->is_top() && !dest->is_top()) {
5934 // validate arguments: enables transformation the ArrayCopyNode
5935 validated = true;
5936
5937 RegionNode* slow_region = new RegionNode(1);
5938 record_for_igvn(slow_region);
5939
5940 // (1) src and dest are arrays.
5941 generate_non_array_guard(load_object_klass(src), slow_region, &src);
5942 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
5943
5944 // (2) src and dest arrays must have elements of the same BasicType
5945 // done at macro expansion or at Ideal transformation time
5946
5947 // (4) src_offset must not be negative.
5948 generate_negative_guard(src_offset, slow_region);
5949
5950 // (5) dest_offset must not be negative.
5951 generate_negative_guard(dest_offset, slow_region);
5952
5953 // (7) src_offset + length must not exceed length of src.
5956 slow_region);
5957
5958 // (8) dest_offset + length must not exceed length of dest.
5959 generate_limit_guard(dest_offset, length,
5960 load_array_length(dest),
5961 slow_region);
5962
5963 // (6) length must not be negative.
5964 // This is also checked in generate_arraycopy() during macro expansion, but
5965 // we also have to check it here for the case where the ArrayCopyNode will
5966 // be eliminated by Escape Analysis.
5967 if (EliminateAllocations) {
5968 generate_negative_guard(length, slow_region);
5969 negative_length_guard_generated = true;
5970 }
5971
5972 // (9) each element of an oop array must be assignable
5973 Node* dest_klass = load_object_klass(dest);
5974 if (src != dest) {
5975 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
5976
5977 if (not_subtype_ctrl != top()) {
5978 PreserveJVMState pjvms(this);
5979 set_control(not_subtype_ctrl);
5980 uncommon_trap(Deoptimization::Reason_intrinsic,
5981 Deoptimization::Action_make_not_entrant);
5982 assert(stopped(), "Should be stopped");
5983 }
5984 }
5985 {
5986 PreserveJVMState pjvms(this);
5987 set_control(_gvn.transform(slow_region));
5988 uncommon_trap(Deoptimization::Reason_intrinsic,
5989 Deoptimization::Action_make_not_entrant);
5990 assert(stopped(), "Should be stopped");
5991 }
5992
5993 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
5994 const Type *toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
5995 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
5996 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
5997 }
5998
5999 if (stopped()) {
6000 return true;
6001 }
6002
6003 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6004 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6005 // so the compiler has a chance to eliminate them: during macro expansion,
6006 // we have to set their control (CastPP nodes are eliminated).
6007 load_object_klass(src), load_object_klass(dest),
6008 load_array_length(src), load_array_length(dest));
6009
6010 ac->set_arraycopy(validated);
6011
6012 Node* n = _gvn.transform(ac);
6013 if (n == ac) {
6014 ac->connect_outputs(this);
6015 } else {
|
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "asm/macroAssembler.hpp"
26 #include "ci/ciFlatArrayKlass.hpp"
27 #include "ci/ciUtilities.inline.hpp"
28 #include "ci/ciSymbols.hpp"
29 #include "classfile/vmIntrinsics.hpp"
30 #include "compiler/compileBroker.hpp"
31 #include "compiler/compileLog.hpp"
32 #include "gc/shared/barrierSet.hpp"
33 #include "jfr/support/jfrIntrinsics.hpp"
34 #include "memory/resourceArea.hpp"
35 #include "oops/klass.inline.hpp"
36 #include "oops/objArrayKlass.hpp"
37 #include "opto/addnode.hpp"
38 #include "opto/arraycopynode.hpp"
39 #include "opto/c2compiler.hpp"
40 #include "opto/castnode.hpp"
41 #include "opto/cfgnode.hpp"
42 #include "opto/convertnode.hpp"
43 #include "opto/countbitsnode.hpp"
44 #include "opto/idealKit.hpp"
45 #include "opto/library_call.hpp"
46 #include "opto/mathexactnode.hpp"
299 case vmIntrinsics::_indexOfIL: return inline_string_indexOfI(StrIntrinsicNode::LL);
300 case vmIntrinsics::_indexOfIU: return inline_string_indexOfI(StrIntrinsicNode::UU);
301 case vmIntrinsics::_indexOfIUL: return inline_string_indexOfI(StrIntrinsicNode::UL);
302 case vmIntrinsics::_indexOfU_char: return inline_string_indexOfChar(StrIntrinsicNode::U);
303 case vmIntrinsics::_indexOfL_char: return inline_string_indexOfChar(StrIntrinsicNode::L);
304
305 case vmIntrinsics::_equalsL: return inline_string_equals(StrIntrinsicNode::LL);
306
307 case vmIntrinsics::_vectorizedHashCode: return inline_vectorizedHashCode();
308
309 case vmIntrinsics::_toBytesStringU: return inline_string_toBytesU();
310 case vmIntrinsics::_getCharsStringU: return inline_string_getCharsU();
311 case vmIntrinsics::_getCharStringU: return inline_string_char_access(!is_store);
312 case vmIntrinsics::_putCharStringU: return inline_string_char_access( is_store);
313
314 case vmIntrinsics::_compressStringC:
315 case vmIntrinsics::_compressStringB: return inline_string_copy( is_compress);
316 case vmIntrinsics::_inflateStringC:
317 case vmIntrinsics::_inflateStringB: return inline_string_copy(!is_compress);
318
319 case vmIntrinsics::_makePrivateBuffer: return inline_unsafe_make_private_buffer();
320 case vmIntrinsics::_finishPrivateBuffer: return inline_unsafe_finish_private_buffer();
321 case vmIntrinsics::_getReference: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false);
322 case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_store, T_BOOLEAN, Relaxed, false);
323 case vmIntrinsics::_getByte: return inline_unsafe_access(!is_store, T_BYTE, Relaxed, false);
324 case vmIntrinsics::_getShort: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, false);
325 case vmIntrinsics::_getChar: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, false);
326 case vmIntrinsics::_getInt: return inline_unsafe_access(!is_store, T_INT, Relaxed, false);
327 case vmIntrinsics::_getLong: return inline_unsafe_access(!is_store, T_LONG, Relaxed, false);
328 case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_store, T_FLOAT, Relaxed, false);
329 case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_store, T_DOUBLE, Relaxed, false);
330 case vmIntrinsics::_getValue: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false, true);
331
332 case vmIntrinsics::_putReference: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false);
333 case vmIntrinsics::_putBoolean: return inline_unsafe_access( is_store, T_BOOLEAN, Relaxed, false);
334 case vmIntrinsics::_putByte: return inline_unsafe_access( is_store, T_BYTE, Relaxed, false);
335 case vmIntrinsics::_putShort: return inline_unsafe_access( is_store, T_SHORT, Relaxed, false);
336 case vmIntrinsics::_putChar: return inline_unsafe_access( is_store, T_CHAR, Relaxed, false);
337 case vmIntrinsics::_putInt: return inline_unsafe_access( is_store, T_INT, Relaxed, false);
338 case vmIntrinsics::_putLong: return inline_unsafe_access( is_store, T_LONG, Relaxed, false);
339 case vmIntrinsics::_putFloat: return inline_unsafe_access( is_store, T_FLOAT, Relaxed, false);
340 case vmIntrinsics::_putDouble: return inline_unsafe_access( is_store, T_DOUBLE, Relaxed, false);
341 case vmIntrinsics::_putValue: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false, true);
342
343 case vmIntrinsics::_getReferenceVolatile: return inline_unsafe_access(!is_store, T_OBJECT, Volatile, false);
344 case vmIntrinsics::_getBooleanVolatile: return inline_unsafe_access(!is_store, T_BOOLEAN, Volatile, false);
345 case vmIntrinsics::_getByteVolatile: return inline_unsafe_access(!is_store, T_BYTE, Volatile, false);
346 case vmIntrinsics::_getShortVolatile: return inline_unsafe_access(!is_store, T_SHORT, Volatile, false);
347 case vmIntrinsics::_getCharVolatile: return inline_unsafe_access(!is_store, T_CHAR, Volatile, false);
348 case vmIntrinsics::_getIntVolatile: return inline_unsafe_access(!is_store, T_INT, Volatile, false);
349 case vmIntrinsics::_getLongVolatile: return inline_unsafe_access(!is_store, T_LONG, Volatile, false);
350 case vmIntrinsics::_getFloatVolatile: return inline_unsafe_access(!is_store, T_FLOAT, Volatile, false);
351 case vmIntrinsics::_getDoubleVolatile: return inline_unsafe_access(!is_store, T_DOUBLE, Volatile, false);
352
353 case vmIntrinsics::_putReferenceVolatile: return inline_unsafe_access( is_store, T_OBJECT, Volatile, false);
354 case vmIntrinsics::_putBooleanVolatile: return inline_unsafe_access( is_store, T_BOOLEAN, Volatile, false);
355 case vmIntrinsics::_putByteVolatile: return inline_unsafe_access( is_store, T_BYTE, Volatile, false);
356 case vmIntrinsics::_putShortVolatile: return inline_unsafe_access( is_store, T_SHORT, Volatile, false);
357 case vmIntrinsics::_putCharVolatile: return inline_unsafe_access( is_store, T_CHAR, Volatile, false);
358 case vmIntrinsics::_putIntVolatile: return inline_unsafe_access( is_store, T_INT, Volatile, false);
359 case vmIntrinsics::_putLongVolatile: return inline_unsafe_access( is_store, T_LONG, Volatile, false);
360 case vmIntrinsics::_putFloatVolatile: return inline_unsafe_access( is_store, T_FLOAT, Volatile, false);
361 case vmIntrinsics::_putDoubleVolatile: return inline_unsafe_access( is_store, T_DOUBLE, Volatile, false);
488 "notifyJvmtiEnd", false, true);
489 case vmIntrinsics::_notifyJvmtiVThreadMount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_mount()),
490 "notifyJvmtiMount", false, false);
491 case vmIntrinsics::_notifyJvmtiVThreadUnmount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_unmount()),
492 "notifyJvmtiUnmount", false, false);
493 case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
494 #endif
495
496 #ifdef JFR_HAVE_INTRINSICS
497 case vmIntrinsics::_counterTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
498 case vmIntrinsics::_getEventWriter: return inline_native_getEventWriter();
499 case vmIntrinsics::_jvm_commit: return inline_native_jvm_commit();
500 #endif
501 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
502 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
503 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
504 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
505 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
506 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
507 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
508 case vmIntrinsics::_isFlatArray: return inline_unsafe_isFlatArray();
509 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
510 case vmIntrinsics::_getLength: return inline_native_getLength();
511 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
512 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
513 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
514 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
515 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
516 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
517 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
518
519 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
520 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
521 case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
522 case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
523 case vmIntrinsics::_newNullableAtomicArray: return inline_newArray(/* null_free */ false, /* atomic */ true);
524
525 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
526
527 case vmIntrinsics::_isInstance:
528 case vmIntrinsics::_isHidden:
529 case vmIntrinsics::_getSuperclass:
530 case vmIntrinsics::_getClassAccessFlags: return inline_native_Class_query(intrinsic_id());
531
532 case vmIntrinsics::_floatToRawIntBits:
533 case vmIntrinsics::_floatToIntBits:
534 case vmIntrinsics::_intBitsToFloat:
535 case vmIntrinsics::_doubleToRawLongBits:
536 case vmIntrinsics::_doubleToLongBits:
537 case vmIntrinsics::_longBitsToDouble:
538 case vmIntrinsics::_floatToFloat16:
539 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
540 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
541 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
542 case vmIntrinsics::_floatIsFinite:
543 case vmIntrinsics::_floatIsInfinite:
2297 case vmIntrinsics::_remainderUnsigned_l: {
2298 zero_check_long(argument(2));
2299 // Compile-time detect of null-exception
2300 if (stopped()) {
2301 return true; // keep the graph constructed so far
2302 }
2303 n = new UModLNode(control(), argument(0), argument(2));
2304 break;
2305 }
2306 default: fatal_unexpected_iid(id); break;
2307 }
2308 set_result(_gvn.transform(n));
2309 return true;
2310 }
2311
2312 //----------------------------inline_unsafe_access----------------------------
2313
2314 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2315 // Attempt to infer a sharper value type from the offset and base type.
2316 ciKlass* sharpened_klass = nullptr;
2317 bool null_free = false;
2318
2319 // See if it is an instance field, with an object type.
2320 if (alias_type->field() != nullptr) {
2321 if (alias_type->field()->type()->is_klass()) {
2322 sharpened_klass = alias_type->field()->type()->as_klass();
2323 null_free = alias_type->field()->is_null_free();
2324 }
2325 }
2326
2327 const TypeOopPtr* result = nullptr;
2328 // See if it is a narrow oop array.
2329 if (adr_type->isa_aryptr()) {
2330 if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2331 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2332 null_free = adr_type->is_aryptr()->is_null_free();
2333 if (elem_type != nullptr && elem_type->is_loaded()) {
2334 // Sharpen the value type.
2335 result = elem_type;
2336 }
2337 }
2338 }
2339
2340 // The sharpened class might be unloaded if there is no class loader
2341 // contraint in place.
2342 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2343 // Sharpen the value type.
2344 result = TypeOopPtr::make_from_klass(sharpened_klass);
2345 if (null_free) {
2346 result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2347 }
2348 }
2349 if (result != nullptr) {
2350 #ifndef PRODUCT
2351 if (C->print_intrinsics() || C->print_inlining()) {
2352 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2353 tty->print(" sharpened value: "); result->dump(); tty->cr();
2354 }
2355 #endif
2356 }
2357 return result;
2358 }
2359
2360 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2361 switch (kind) {
2362 case Relaxed:
2363 return MO_UNORDERED;
2364 case Opaque:
2365 return MO_RELAXED;
2366 case Acquire:
2367 return MO_ACQUIRE;
2368 case Release:
2369 return MO_RELEASE;
2370 case Volatile:
2371 return MO_SEQ_CST;
2372 default:
2373 ShouldNotReachHere();
2374 return 0;
2375 }
2376 }
2377
2378 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned, const bool is_flat) {
2379 if (callee()->is_static()) return false; // caller must have the capability!
2380 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2381 guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2382 guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2383 assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2384
2385 if (is_reference_type(type)) {
2386 decorators |= ON_UNKNOWN_OOP_REF;
2387 }
2388
2389 if (unaligned) {
2390 decorators |= C2_UNALIGNED;
2391 }
2392
2393 #ifndef PRODUCT
2394 {
2395 ResourceMark rm;
2396 // Check the signatures.
2397 ciSignature* sig = callee()->signature();
2398 #ifdef ASSERT
2399 if (!is_store) {
2400 // Object getReference(Object base, int/long offset), etc.
2401 BasicType rtype = sig->return_type()->basic_type();
2402 assert(rtype == type, "getter must return the expected value");
2403 assert(sig->count() == 2 || (is_flat && sig->count() == 3), "oop getter has 2 or 3 arguments");
2404 assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2405 assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2406 } else {
2407 // void putReference(Object base, int/long offset, Object x), etc.
2408 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2409 assert(sig->count() == 3 || (is_flat && sig->count() == 4), "oop putter has 3 arguments");
2410 assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2411 assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2412 BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2413 assert(vtype == type, "putter must accept the expected value");
2414 }
2415 #endif // ASSERT
2416 }
2417 #endif //PRODUCT
2418
2419 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2420
2421 Node* receiver = argument(0); // type: oop
2422
2423 // Build address expression.
2424 Node* heap_base_oop = top();
2425
2426 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2427 Node* base = argument(1); // type: oop
2428 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2429 Node* offset = argument(2); // type: long
2430 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2431 // to be plain byte offsets, which are also the same as those accepted
2432 // by oopDesc::field_addr.
2433 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2434 "fieldOffset must be byte-scaled");
2435
2436 ciInlineKlass* inline_klass = nullptr;
2437 if (is_flat) {
2438 const TypeInstPtr* cls = _gvn.type(argument(4))->isa_instptr();
2439 if (cls == nullptr || cls->const_oop() == nullptr) {
2440 return false;
2441 }
2442 ciType* mirror_type = cls->const_oop()->as_instance()->java_mirror_type();
2443 if (!mirror_type->is_inlinetype()) {
2444 return false;
2445 }
2446 inline_klass = mirror_type->as_inline_klass();
2447 }
2448
2449 if (base->is_InlineType()) {
2450 assert(!is_store, "InlineTypeNodes are non-larval value objects");
2451 InlineTypeNode* vt = base->as_InlineType();
2452 if (offset->is_Con()) {
2453 long off = find_long_con(offset, 0);
2454 ciInlineKlass* vk = vt->type()->inline_klass();
2455 if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2456 return false;
2457 }
2458
2459 ciField* field = vk->get_non_flat_field_by_offset(off);
2460 if (field != nullptr) {
2461 BasicType bt = type2field[field->type()->basic_type()];
2462 if (bt == T_ARRAY || bt == T_NARROWOOP) {
2463 bt = T_OBJECT;
2464 }
2465 if (bt == type && (!field->is_flat() || field->type() == inline_klass)) {
2466 Node* value = vt->field_value_by_offset(off, false);
2467 if (value->is_InlineType()) {
2468 value = value->as_InlineType()->adjust_scalarization_depth(this);
2469 }
2470 set_result(value);
2471 return true;
2472 }
2473 }
2474 }
2475 {
2476 // Re-execute the unsafe access if allocation triggers deoptimization.
2477 PreserveReexecuteState preexecs(this);
2478 jvms()->set_should_reexecute(true);
2479 vt = vt->buffer(this);
2480 }
2481 base = vt->get_oop();
2482 }
2483
2484 // 32-bit machines ignore the high half!
2485 offset = ConvL2X(offset);
2486
2487 // Save state and restore on bailout
2488 uint old_sp = sp();
2489 SafePointNode* old_map = clone_map();
2490
2491 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2492 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2493
2494 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2495 if (type != T_OBJECT && (inline_klass == nullptr || !inline_klass->has_object_fields())) {
2496 decorators |= IN_NATIVE; // off-heap primitive access
2497 } else {
2498 set_map(old_map);
2499 set_sp(old_sp);
2500 return false; // off-heap oop accesses are not supported
2501 }
2502 } else {
2503 heap_base_oop = base; // on-heap or mixed access
2504 }
2505
2506 // Can base be null? Otherwise, always on-heap access.
2507 bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2508
2509 if (!can_access_non_heap) {
2510 decorators |= IN_HEAP;
2511 }
2512
2513 Node* val = is_store ? argument(4 + (is_flat ? 1 : 0)) : nullptr;
2514
2515 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2516 if (adr_type == TypePtr::NULL_PTR) {
2517 set_map(old_map);
2518 set_sp(old_sp);
2519 return false; // off-heap access with zero address
2520 }
2521
2522 // Try to categorize the address.
2523 Compile::AliasType* alias_type = C->alias_type(adr_type);
2524 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2525
2526 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2527 alias_type->adr_type() == TypeAryPtr::RANGE) {
2528 set_map(old_map);
2529 set_sp(old_sp);
2530 return false; // not supported
2531 }
2532
2533 bool mismatched = false;
2534 BasicType bt = T_ILLEGAL;
2535 ciField* field = nullptr;
2536 if (adr_type->isa_instptr()) {
2537 const TypeInstPtr* instptr = adr_type->is_instptr();
2538 ciInstanceKlass* k = instptr->instance_klass();
2539 int off = instptr->offset();
2540 if (instptr->const_oop() != nullptr &&
2541 k == ciEnv::current()->Class_klass() &&
2542 instptr->offset() >= (k->size_helper() * wordSize)) {
2543 k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2544 field = k->get_field_by_offset(off, true);
2545 } else {
2546 field = k->get_non_flat_field_by_offset(off);
2547 }
2548 if (field != nullptr) {
2549 bt = type2field[field->type()->basic_type()];
2550 }
2551 if (bt != alias_type->basic_type()) {
2552 // Type mismatch. Is it an access to a nested flat field?
2553 field = k->get_field_by_offset(off, false);
2554 if (field != nullptr) {
2555 bt = type2field[field->type()->basic_type()];
2556 }
2557 }
2558 assert(bt == alias_type->basic_type() || is_flat, "should match");
2559 } else {
2560 bt = alias_type->basic_type();
2561 }
2562
2563 if (bt != T_ILLEGAL) {
2564 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2565 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2566 // Alias type doesn't differentiate between byte[] and boolean[]).
2567 // Use address type to get the element type.
2568 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2569 }
2570 if (is_reference_type(bt, true)) {
2571 // accessing an array field with getReference is not a mismatch
2572 bt = T_OBJECT;
2573 }
2574 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2575 // Don't intrinsify mismatched object accesses
2576 set_map(old_map);
2577 set_sp(old_sp);
2578 return false;
2579 }
2580 mismatched = (bt != type);
2581 } else if (alias_type->adr_type()->isa_oopptr()) {
2582 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2583 }
2584
2585 if (is_flat) {
2586 if (adr_type->isa_instptr()) {
2587 if (field == nullptr || field->type() != inline_klass) {
2588 mismatched = true;
2589 }
2590 } else if (adr_type->isa_aryptr()) {
2591 const Type* elem = adr_type->is_aryptr()->elem();
2592 if (!adr_type->is_flat() || elem->inline_klass() != inline_klass) {
2593 mismatched = true;
2594 }
2595 } else {
2596 mismatched = true;
2597 }
2598 if (is_store) {
2599 const Type* val_t = _gvn.type(val);
2600 if (!val_t->is_inlinetypeptr() || val_t->inline_klass() != inline_klass) {
2601 set_map(old_map);
2602 set_sp(old_sp);
2603 return false;
2604 }
2605 }
2606 }
2607
2608 destruct_map_clone(old_map);
2609 assert(!mismatched || is_flat || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2610
2611 if (mismatched) {
2612 decorators |= C2_MISMATCHED;
2613 }
2614
2615 // First guess at the value type.
2616 const Type *value_type = Type::get_const_basic_type(type);
2617
2618 // Figure out the memory ordering.
2619 decorators |= mo_decorator_for_access_kind(kind);
2620
2621 if (!is_store) {
2622 if (type == T_OBJECT && !is_flat) {
2623 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2624 if (tjp != nullptr) {
2625 value_type = tjp;
2626 }
2627 }
2628 }
2629
2630 receiver = null_check(receiver);
2631 if (stopped()) {
2632 return true;
2633 }
2634 // Heap pointers get a null-check from the interpreter,
2635 // as a courtesy. However, this is not guaranteed by Unsafe,
2636 // and it is not possible to fully distinguish unintended nulls
2637 // from intended ones in this API.
2638
2639 if (!is_store) {
2640 Node* p = nullptr;
2641 // Try to constant fold a load from a constant field
2642
2643 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2644 // final or stable field
2645 p = make_constant_from_field(field, heap_base_oop);
2646 }
2647
2648 if (p == nullptr) { // Could not constant fold the load
2649 if (is_flat) {
2650 if (adr_type->isa_instptr() && !mismatched) {
2651 ciInstanceKlass* holder = adr_type->is_instptr()->instance_klass();
2652 int offset = adr_type->is_instptr()->offset();
2653 p = InlineTypeNode::make_from_flat(this, inline_klass, base, base, nullptr, holder, offset, false, -1, decorators);
2654 } else {
2655 p = InlineTypeNode::make_from_flat(this, inline_klass, base, adr, nullptr, nullptr, 0, false, -1, decorators);
2656 }
2657 } else {
2658 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2659 const TypeOopPtr* ptr = value_type->make_oopptr();
2660 if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2661 // Load a non-flattened inline type from memory
2662 p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2663 }
2664 }
2665 // Normalize the value returned by getBoolean in the following cases
2666 if (type == T_BOOLEAN &&
2667 (mismatched ||
2668 heap_base_oop == top() || // - heap_base_oop is null or
2669 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2670 // and the unsafe access is made to large offset
2671 // (i.e., larger than the maximum offset necessary for any
2672 // field access)
2673 ) {
2674 IdealKit ideal = IdealKit(this);
2675 #define __ ideal.
2676 IdealVariable normalized_result(ideal);
2677 __ declarations_done();
2678 __ set(normalized_result, p);
2679 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2680 __ set(normalized_result, ideal.ConI(1));
2681 ideal.end_if();
2682 final_sync(ideal);
2683 p = __ value(normalized_result);
2684 #undef __
2685 }
2686 }
2687 if (type == T_ADDRESS) {
2688 p = gvn().transform(new CastP2XNode(nullptr, p));
2689 p = ConvX2UL(p);
2690 }
2691 // The load node has the control of the preceding MemBarCPUOrder. All
2692 // following nodes will have the control of the MemBarCPUOrder inserted at
2693 // the end of this method. So, pushing the load onto the stack at a later
2694 // point is fine.
2695 set_result(p);
2696 } else {
2697 if (bt == T_ADDRESS) {
2698 // Repackage the long as a pointer.
2699 val = ConvL2X(val);
2700 val = gvn().transform(new CastX2PNode(val));
2701 }
2702 if (is_flat) {
2703 if (adr_type->isa_instptr() && !mismatched) {
2704 ciInstanceKlass* holder = adr_type->is_instptr()->instance_klass();
2705 int offset = adr_type->is_instptr()->offset();
2706 val->as_InlineType()->store_flat(this, base, base, nullptr, holder, offset, false, -1, decorators);
2707 } else {
2708 val->as_InlineType()->store_flat(this, base, adr, nullptr, val->bottom_type()->inline_klass(), 0, false, -1, decorators);
2709 }
2710 } else {
2711 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2712 }
2713 }
2714
2715 return true;
2716 }
2717
2718 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2719 Node* receiver = argument(0);
2720 Node* value = argument(1);
2721
2722 const Type* type = gvn().type(value);
2723 if (!type->is_inlinetypeptr()) {
2724 C->record_method_not_compilable("value passed to Unsafe::makePrivateBuffer is not of a constant value type");
2725 return false;
2726 }
2727
2728 null_check(receiver);
2729 if (stopped()) {
2730 return true;
2731 }
2732
2733 value = null_check(value);
2734 if (stopped()) {
2735 return true;
2736 }
2737
2738 ciInlineKlass* vk = type->inline_klass();
2739 Node* klass = makecon(TypeKlassPtr::make(vk));
2740 Node* obj = new_instance(klass);
2741 AllocateNode::Ideal_allocation(obj)->_larval = true;
2742
2743 assert(value->is_InlineType(), "must be an InlineTypeNode");
2744 value->as_InlineType()->store(this, obj, obj, vk);
2745
2746 set_result(obj);
2747 return true;
2748 }
2749
2750 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2751 Node* receiver = argument(0);
2752 Node* buffer = argument(1);
2753
2754 const Type* type = gvn().type(buffer);
2755 if (!type->is_inlinetypeptr()) {
2756 C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer is not of a constant value type");
2757 return false;
2758 }
2759
2760 AllocateNode* alloc = AllocateNode::Ideal_allocation(buffer);
2761 if (alloc == nullptr) {
2762 C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer must be allocated by Unsafe::makePrivateBuffer");
2763 return false;
2764 }
2765
2766 null_check(receiver);
2767 if (stopped()) {
2768 return true;
2769 }
2770
2771 // Unset the larval bit in the object header
2772 Node* old_header = make_load(control(), buffer, TypeX_X, TypeX_X->basic_type(), MemNode::unordered, LoadNode::Pinned);
2773 Node* new_header = gvn().transform(new AndXNode(old_header, MakeConX(~markWord::larval_bit_in_place)));
2774 access_store_at(buffer, buffer, type->is_ptr(), new_header, TypeX_X, TypeX_X->basic_type(), MO_UNORDERED | IN_HEAP);
2775
2776 // We must ensure that the buffer is properly published
2777 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
2778 assert(!type->maybe_null(), "result of an allocation should not be null");
2779 set_result(InlineTypeNode::make_from_oop(this, buffer, type->inline_klass()));
2780 return true;
2781 }
2782
2783 //----------------------------inline_unsafe_load_store----------------------------
2784 // This method serves a couple of different customers (depending on LoadStoreKind):
2785 //
2786 // LS_cmp_swap:
2787 //
2788 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2789 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2790 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2791 //
2792 // LS_cmp_swap_weak:
2793 //
2794 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2795 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2796 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2797 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2798 //
2799 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2800 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2801 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2802 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
2968 }
2969 case LS_cmp_swap:
2970 case LS_cmp_swap_weak:
2971 case LS_get_add:
2972 break;
2973 default:
2974 ShouldNotReachHere();
2975 }
2976
2977 // Null check receiver.
2978 receiver = null_check(receiver);
2979 if (stopped()) {
2980 return true;
2981 }
2982
2983 int alias_idx = C->get_alias_index(adr_type);
2984
2985 if (is_reference_type(type)) {
2986 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2987
2988 if (oldval != nullptr && oldval->is_InlineType()) {
2989 // Re-execute the unsafe access if allocation triggers deoptimization.
2990 PreserveReexecuteState preexecs(this);
2991 jvms()->set_should_reexecute(true);
2992 oldval = oldval->as_InlineType()->buffer(this)->get_oop();
2993 }
2994 if (newval != nullptr && newval->is_InlineType()) {
2995 // Re-execute the unsafe access if allocation triggers deoptimization.
2996 PreserveReexecuteState preexecs(this);
2997 jvms()->set_should_reexecute(true);
2998 newval = newval->as_InlineType()->buffer(this)->get_oop();
2999 }
3000
3001 // Transformation of a value which could be null pointer (CastPP #null)
3002 // could be delayed during Parse (for example, in adjust_map_after_if()).
3003 // Execute transformation here to avoid barrier generation in such case.
3004 if (_gvn.type(newval) == TypePtr::NULL_PTR)
3005 newval = _gvn.makecon(TypePtr::NULL_PTR);
3006
3007 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3008 // Refine the value to a null constant, when it is known to be null
3009 oldval = _gvn.makecon(TypePtr::NULL_PTR);
3010 }
3011 }
3012
3013 Node* result = nullptr;
3014 switch (kind) {
3015 case LS_cmp_exchange: {
3016 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3017 oldval, newval, value_type, type, decorators);
3018 break;
3019 }
3020 case LS_cmp_swap_weak:
3167 Deoptimization::Action_make_not_entrant);
3168 }
3169 if (stopped()) {
3170 return true;
3171 }
3172 #endif //INCLUDE_JVMTI
3173
3174 Node* test = nullptr;
3175 if (LibraryCallKit::klass_needs_init_guard(kls)) {
3176 // Note: The argument might still be an illegal value like
3177 // Serializable.class or Object[].class. The runtime will handle it.
3178 // But we must make an explicit check for initialization.
3179 Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3180 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3181 // can generate code to load it as unsigned byte.
3182 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3183 Node* bits = intcon(InstanceKlass::fully_initialized);
3184 test = _gvn.transform(new SubINode(inst, bits));
3185 // The 'test' is non-zero if we need to take a slow path.
3186 }
3187 Node* obj = nullptr;
3188 const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3189 if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3190 obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3191 } else {
3192 obj = new_instance(kls, test);
3193 }
3194 set_result(obj);
3195 return true;
3196 }
3197
3198 //------------------------inline_native_time_funcs--------------
3199 // inline code for System.currentTimeMillis() and System.nanoTime()
3200 // these have the same type and signature
3201 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3202 const TypeFunc* tf = OptoRuntime::void_long_Type();
3203 const TypePtr* no_memory_effects = nullptr;
3204 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3205 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3206 #ifdef ASSERT
3207 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3208 assert(value_top == top(), "second value must be top");
3209 #endif
3210 set_result(value);
3211 return true;
3212 }
3213
3954 Node* thread = _gvn.transform(new ThreadLocalNode());
3955 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
3956 Node* thread_obj_handle
3957 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3958 thread_obj_handle = _gvn.transform(thread_obj_handle);
3959 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3960 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3961
3962 // Change the _monitor_owner_id of the JavaThread
3963 Node* tid = load_field_from_object(arr, "tid", "J");
3964 Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3965 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3966
3967 JFR_ONLY(extend_setCurrentThread(thread, arr);)
3968 return true;
3969 }
3970
3971 const Type* LibraryCallKit::scopedValueCache_type() {
3972 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3973 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3974 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true);
3975
3976 // Because we create the scopedValue cache lazily we have to make the
3977 // type of the result BotPTR.
3978 bool xk = etype->klass_is_exact();
3979 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
3980 return objects_type;
3981 }
3982
3983 Node* LibraryCallKit::scopedValueCache_helper() {
3984 Node* thread = _gvn.transform(new ThreadLocalNode());
3985 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
3986 // We cannot use immutable_memory() because we might flip onto a
3987 // different carrier thread, at which point we'll need to use that
3988 // carrier thread's cache.
3989 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3990 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3991 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3992 }
3993
3994 //------------------------inline_native_scopedValueCache------------------
3995 bool LibraryCallKit::inline_native_scopedValueCache() {
3996 Node* cache_obj_handle = scopedValueCache_helper();
3997 const Type* objects_type = scopedValueCache_type();
3998 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3999
4083 store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4084
4085 // Result of top level CFG and Memory.
4086 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4087 record_for_igvn(result_rgn);
4088 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4089 record_for_igvn(result_mem);
4090
4091 result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4092 result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4093 result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4094 result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4095
4096 // Set output state.
4097 set_control(_gvn.transform(result_rgn));
4098 set_all_memory(_gvn.transform(result_mem));
4099
4100 return true;
4101 }
4102
4103 //-----------------------load_klass_from_mirror_common-------------------------
4104 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4105 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4106 // and branch to the given path on the region.
4107 // If never_see_null, take an uncommon trap on null, so we can optimistically
4108 // compile for the non-null case.
4109 // If the region is null, force never_see_null = true.
4110 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4111 bool never_see_null,
4112 RegionNode* region,
4113 int null_path,
4114 int offset) {
4115 if (region == nullptr) never_see_null = true;
4116 Node* p = basic_plus_adr(mirror, offset);
4117 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4118 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4119 Node* null_ctl = top();
4120 kls = null_check_oop(kls, &null_ctl, never_see_null);
4121 if (region != nullptr) {
4122 // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4126 }
4127 return kls;
4128 }
4129
4130 //--------------------(inline_native_Class_query helpers)---------------------
4131 // Use this for JVM_ACC_INTERFACE.
4132 // Fall through if (mods & mask) == bits, take the guard otherwise.
4133 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4134 ByteSize offset, const Type* type, BasicType bt) {
4135 // Branch around if the given klass has the given modifier bit set.
4136 // Like generate_guard, adds a new path onto the region.
4137 Node* modp = basic_plus_adr(kls, in_bytes(offset));
4138 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4139 Node* mask = intcon(modifier_mask);
4140 Node* bits = intcon(modifier_bits);
4141 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4142 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4143 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4144 return generate_fair_guard(bol, region);
4145 }
4146
4147 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4148 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4149 Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4150 }
4151
4152 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4153 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4154 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4155 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4156 }
4157
4158 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4159 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4160 }
4161
4162 //-------------------------inline_native_Class_query-------------------
4163 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4164 const Type* return_type = TypeInt::BOOL;
4165 Node* prim_return_value = top(); // what happens if it's a primitive class?
4166 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4285
4286 case vmIntrinsics::_getClassAccessFlags:
4287 p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
4288 query_value = make_load(nullptr, p, TypeInt::CHAR, T_CHAR, MemNode::unordered);
4289 break;
4290
4291 default:
4292 fatal_unexpected_iid(id);
4293 break;
4294 }
4295
4296 // Fall-through is the normal case of a query to a real class.
4297 phi->init_req(1, query_value);
4298 region->init_req(1, control());
4299
4300 C->set_has_split_ifs(true); // Has chance for split-if optimization
4301 set_result(region, phi);
4302 return true;
4303 }
4304
4305
4306 //-------------------------inline_Class_cast-------------------
4307 bool LibraryCallKit::inline_Class_cast() {
4308 Node* mirror = argument(0); // Class
4309 Node* obj = argument(1);
4310 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4311 if (mirror_con == nullptr) {
4312 return false; // dead path (mirror->is_top()).
4313 }
4314 if (obj == nullptr || obj->is_top()) {
4315 return false; // dead path
4316 }
4317 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4318
4319 // First, see if Class.cast() can be folded statically.
4320 // java_mirror_type() returns non-null for compile-time Class constants.
4321 bool is_null_free_array = false;
4322 ciType* tm = mirror_con->java_mirror_type(&is_null_free_array);
4323 if (tm != nullptr && tm->is_klass() &&
4324 tp != nullptr) {
4325 if (!tp->is_loaded()) {
4326 // Don't use intrinsic when class is not loaded.
4327 return false;
4328 } else {
4329 const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4330 if (is_null_free_array) {
4331 tklass = tklass->is_aryklassptr()->cast_to_null_free();
4332 }
4333 int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4334 if (static_res == Compile::SSC_always_true) {
4335 // isInstance() is true - fold the code.
4336 set_result(obj);
4337 return true;
4338 } else if (static_res == Compile::SSC_always_false) {
4339 // Don't use intrinsic, have to throw ClassCastException.
4340 // If the reference is null, the non-intrinsic bytecode will
4341 // be optimized appropriately.
4342 return false;
4343 }
4344 }
4345 }
4346
4347 // Bailout intrinsic and do normal inlining if exception path is frequent.
4348 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4349 return false;
4350 }
4351
4352 // Generate dynamic checks.
4353 // Class.cast() is java implementation of _checkcast bytecode.
4354 // Do checkcast (Parse::do_checkcast()) optimizations here.
4355
4356 mirror = null_check(mirror);
4357 // If mirror is dead, only null-path is taken.
4358 if (stopped()) {
4359 return true;
4360 }
4361
4362 // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4363 enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4364 RegionNode* region = new RegionNode(PATH_LIMIT);
4365 record_for_igvn(region);
4366
4367 // Now load the mirror's klass metaobject, and null-check it.
4368 // If kls is null, we have a primitive mirror and
4369 // nothing is an instance of a primitive type.
4370 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4371
4372 Node* res = top();
4373 Node* io = i_o();
4374 Node* mem = merged_memory();
4375 if (!stopped()) {
4376
4377 Node* bad_type_ctrl = top();
4378 // Do checkcast optimizations.
4379 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4380 region->init_req(_bad_type_path, bad_type_ctrl);
4381 }
4382 if (region->in(_prim_path) != top() ||
4383 region->in(_bad_type_path) != top() ||
4384 region->in(_npe_path) != top()) {
4385 // Let Interpreter throw ClassCastException.
4386 PreserveJVMState pjvms(this);
4387 set_control(_gvn.transform(region));
4388 // Set IO and memory because gen_checkcast may override them when buffering inline types
4389 set_i_o(io);
4390 set_all_memory(mem);
4391 uncommon_trap(Deoptimization::Reason_intrinsic,
4392 Deoptimization::Action_maybe_recompile);
4393 }
4394 if (!stopped()) {
4395 set_result(res);
4396 }
4397 return true;
4398 }
4399
4400
4401 //--------------------------inline_native_subtype_check------------------------
4402 // This intrinsic takes the JNI calls out of the heart of
4403 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4404 bool LibraryCallKit::inline_native_subtype_check() {
4405 // Pull both arguments off the stack.
4406 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4407 args[0] = argument(0);
4408 args[1] = argument(1);
4409 Node* klasses[2]; // corresponding Klasses: superk, subk
4410 klasses[0] = klasses[1] = top();
4411
4412 enum {
4413 // A full decision tree on {superc is prim, subc is prim}:
4414 _prim_0_path = 1, // {P,N} => false
4415 // {P,P} & superc!=subc => false
4416 _prim_same_path, // {P,P} & superc==subc => true
4417 _prim_1_path, // {N,P} => false
4418 _ref_subtype_path, // {N,N} & subtype check wins => true
4419 _both_ref_path, // {N,N} & subtype check loses => false
4420 PATH_LIMIT
4421 };
4422
4423 RegionNode* region = new RegionNode(PATH_LIMIT);
4424 RegionNode* prim_region = new RegionNode(2);
4425 Node* phi = new PhiNode(region, TypeInt::BOOL);
4426 record_for_igvn(region);
4427 record_for_igvn(prim_region);
4428
4429 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4430 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4431 int class_klass_offset = java_lang_Class::klass_offset();
4432
4433 // First null-check both mirrors and load each mirror's klass metaobject.
4434 int which_arg;
4435 for (which_arg = 0; which_arg <= 1; which_arg++) {
4436 Node* arg = args[which_arg];
4437 arg = null_check(arg);
4438 if (stopped()) break;
4439 args[which_arg] = arg;
4440
4441 Node* p = basic_plus_adr(arg, class_klass_offset);
4442 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4443 klasses[which_arg] = _gvn.transform(kls);
4444 }
4445
4446 // Having loaded both klasses, test each for null.
4447 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4448 for (which_arg = 0; which_arg <= 1; which_arg++) {
4449 Node* kls = klasses[which_arg];
4450 Node* null_ctl = top();
4451 kls = null_check_oop(kls, &null_ctl, never_see_null);
4452 if (which_arg == 0) {
4453 prim_region->init_req(1, null_ctl);
4454 } else {
4455 region->init_req(_prim_1_path, null_ctl);
4456 }
4457 if (stopped()) break;
4458 klasses[which_arg] = kls;
4459 }
4460
4461 if (!stopped()) {
4462 // now we have two reference types, in klasses[0..1]
4463 Node* subk = klasses[1]; // the argument to isAssignableFrom
4464 Node* superk = klasses[0]; // the receiver
4465 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4466 region->set_req(_ref_subtype_path, control());
4467 }
4468
4469 // If both operands are primitive (both klasses null), then
4470 // we must return true when they are identical primitives.
4471 // It is convenient to test this after the first null klass check.
4472 // This path is also used if superc is a value mirror.
4473 set_control(_gvn.transform(prim_region));
4474 if (!stopped()) {
4475 // Since superc is primitive, make a guard for the superc==subc case.
4476 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4477 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4478 generate_fair_guard(bol_eq, region);
4479 if (region->req() == PATH_LIMIT+1) {
4480 // A guard was added. If the added guard is taken, superc==subc.
4481 region->swap_edges(PATH_LIMIT, _prim_same_path);
4482 region->del_req(PATH_LIMIT);
4483 }
4484 region->set_req(_prim_0_path, control()); // Not equal after all.
4485 }
4486
4487 // these are the only paths that produce 'true':
4488 phi->set_req(_prim_same_path, intcon(1));
4489 phi->set_req(_ref_subtype_path, intcon(1));
4490
4491 // pull together the cases:
4492 assert(region->req() == PATH_LIMIT, "sane region");
4493 for (uint i = 1; i < region->req(); i++) {
4494 Node* ctl = region->in(i);
4495 if (ctl == nullptr || ctl == top()) {
4496 region->set_req(i, top());
4497 phi ->set_req(i, top());
4498 } else if (phi->in(i) == nullptr) {
4499 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4500 }
4501 }
4502
4503 set_control(_gvn.transform(region));
4504 set_result(_gvn.transform(phi));
4505 return true;
4506 }
4507
4508 //---------------------generate_array_guard_common------------------------
4509 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4510
4511 if (stopped()) {
4512 return nullptr;
4513 }
4514
4515 // Like generate_guard, adds a new path onto the region.
4516 jint layout_con = 0;
4517 Node* layout_val = get_layout_helper(kls, layout_con);
4518 if (layout_val == nullptr) {
4519 bool query = 0;
4520 switch(kind) {
4521 case ObjectArray: query = Klass::layout_helper_is_objArray(layout_con); break;
4522 case NonObjectArray: query = !Klass::layout_helper_is_objArray(layout_con); break;
4523 case TypeArray: query = Klass::layout_helper_is_typeArray(layout_con); break;
4524 case AnyArray: query = Klass::layout_helper_is_array(layout_con); break;
4525 case NonArray: query = !Klass::layout_helper_is_array(layout_con); break;
4526 default:
4527 ShouldNotReachHere();
4528 }
4529 if (!query) {
4530 return nullptr; // never a branch
4531 } else { // always a branch
4532 Node* always_branch = control();
4533 if (region != nullptr)
4534 region->add_req(always_branch);
4535 set_control(top());
4536 return always_branch;
4537 }
4538 }
4539 unsigned int value = 0;
4540 BoolTest::mask btest = BoolTest::illegal;
4541 switch(kind) {
4542 case ObjectArray:
4543 case NonObjectArray: {
4544 value = Klass::_lh_array_tag_obj_value;
4545 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4546 btest = (kind == ObjectArray) ? BoolTest::eq : BoolTest::ne;
4547 break;
4548 }
4549 case TypeArray: {
4550 value = Klass::_lh_array_tag_type_value;
4551 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4552 btest = BoolTest::eq;
4553 break;
4554 }
4555 case AnyArray: value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4556 case NonArray: value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4557 default:
4558 ShouldNotReachHere();
4559 }
4560 // Now test the correct condition.
4561 jint nval = (jint)value;
4562 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4563 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4564 Node* ctrl = generate_fair_guard(bol, region);
4565 Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4566 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4567 // Keep track of the fact that 'obj' is an array to prevent
4568 // array specific accesses from floating above the guard.
4569 *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4570 }
4571 return ctrl;
4572 }
4573
4574 // public static native Object[] newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4575 // public static native Object[] newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4576 // public static native Object[] newNullableAtomicArray(Class<?> componentType, int length);
4577 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4578 assert(null_free || atomic, "nullable implies atomic");
4579 Node* componentType = argument(0);
4580 Node* length = argument(1);
4581 Node* init_val = null_free ? argument(2) : nullptr;
4582
4583 const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4584 if (tp != nullptr) {
4585 ciInstanceKlass* ik = tp->instance_klass();
4586 if (ik == C->env()->Class_klass()) {
4587 ciType* t = tp->java_mirror_type();
4588 if (t != nullptr && t->is_inlinetype()) {
4589 ciInlineKlass* vk = t->as_inline_klass();
4590 bool flat = vk->maybe_flat_in_array();
4591 if (flat && atomic) {
4592 // Only flat if we have a corresponding atomic layout
4593 flat = null_free ? vk->has_atomic_layout() : vk->has_nullable_atomic_layout();
4594 }
4595 // TODO 8350865 refactor
4596 if (flat && !atomic) {
4597 flat = vk->has_non_atomic_layout();
4598 }
4599
4600 // TOOD 8350865 ZGC needs card marks on initializing oop stores
4601 if (UseZGC && null_free && !flat) {
4602 return false;
4603 }
4604
4605 ciArrayKlass* array_klass = ciArrayKlass::make(t, flat, null_free, atomic);
4606 if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4607 const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4608 if (null_free) {
4609 if (init_val->is_InlineType()) {
4610 if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4611 // Zeroing is enough because the init value is the all-zero value
4612 init_val = nullptr;
4613 } else {
4614 init_val = init_val->as_InlineType()->buffer(this);
4615 }
4616 }
4617 // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4618 }
4619 Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4620 const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4621 assert(arytype->is_null_free() == null_free, "inconsistency");
4622 assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4623 assert(arytype->is_flat() == flat, "inconsistency");
4624 assert(arytype->is_aryptr()->is_not_flat() == !flat, "inconsistency");
4625 set_result(obj);
4626 return true;
4627 }
4628 }
4629 }
4630 }
4631 return false;
4632 }
4633
4634 //-----------------------inline_native_newArray--------------------------
4635 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4636 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4637 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4638 Node* mirror;
4639 Node* count_val;
4640 if (uninitialized) {
4641 null_check_receiver();
4642 mirror = argument(1);
4643 count_val = argument(2);
4644 } else {
4645 mirror = argument(0);
4646 count_val = argument(1);
4647 }
4648
4649 mirror = null_check(mirror);
4650 // If mirror or obj is dead, only null-path is taken.
4651 if (stopped()) return true;
4652
4653 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4654 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4655 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4761 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4762 { PreserveReexecuteState preexecs(this);
4763 jvms()->set_should_reexecute(true);
4764
4765 array_type_mirror = null_check(array_type_mirror);
4766 original = null_check(original);
4767
4768 // Check if a null path was taken unconditionally.
4769 if (stopped()) return true;
4770
4771 Node* orig_length = load_array_length(original);
4772
4773 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4774 klass_node = null_check(klass_node);
4775
4776 RegionNode* bailout = new RegionNode(1);
4777 record_for_igvn(bailout);
4778
4779 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4780 // Bail out if that is so.
4781 // Inline type array may have object field that would require a
4782 // write barrier. Conservatively, go to slow path.
4783 // TODO 8251971: Optimize for the case when flat src/dst are later found
4784 // to not contain oops (i.e., move this check to the macro expansion phase).
4785 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4786 const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
4787 const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
4788 bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
4789 // Can src array be flat and contain oops?
4790 (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
4791 // Can dest array be flat and contain oops?
4792 tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
4793 Node* not_objArray = exclude_flat ? generate_non_objArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
4794 if (not_objArray != nullptr) {
4795 // Improve the klass node's type from the new optimistic assumption:
4796 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4797 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0));
4798 Node* cast = new CastPPNode(control(), klass_node, akls);
4799 klass_node = _gvn.transform(cast);
4800 }
4801
4802 // Bail out if either start or end is negative.
4803 generate_negative_guard(start, bailout, &start);
4804 generate_negative_guard(end, bailout, &end);
4805
4806 Node* length = end;
4807 if (_gvn.type(start) != TypeInt::ZERO) {
4808 length = _gvn.transform(new SubINode(end, start));
4809 }
4810
4811 // Bail out if length is negative (i.e., if start > end).
4812 // Without this the new_array would throw
4813 // NegativeArraySizeException but IllegalArgumentException is what
4814 // should be thrown
4815 generate_negative_guard(length, bailout, &length);
4816
4817 // Handle inline type arrays
4818 bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
4819 if (!stopped()) {
4820 // TODO JDK-8329224
4821 if (!orig_t->is_null_free()) {
4822 // Not statically known to be null free, add a check
4823 generate_fair_guard(null_free_array_test(original), bailout);
4824 }
4825 orig_t = _gvn.type(original)->isa_aryptr();
4826 if (orig_t != nullptr && orig_t->is_flat()) {
4827 // Src is flat, check that dest is flat as well
4828 if (exclude_flat) {
4829 // Dest can't be flat, bail out
4830 bailout->add_req(control());
4831 set_control(top());
4832 } else {
4833 generate_fair_guard(flat_array_test(klass_node, /* flat = */ false), bailout);
4834 }
4835 // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
4836 } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
4837 // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
4838 ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
4839 // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
4840 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
4841 generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
4842 if (orig_t != nullptr) {
4843 orig_t = orig_t->cast_to_not_flat();
4844 original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
4845 }
4846 }
4847 if (!can_validate) {
4848 // No validation. The subtype check emitted at macro expansion time will not go to the slow
4849 // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
4850 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
4851 generate_fair_guard(flat_array_test(klass_node), bailout);
4852 generate_fair_guard(null_free_array_test(original), bailout);
4853 }
4854 }
4855
4856 // Bail out if start is larger than the original length
4857 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4858 generate_negative_guard(orig_tail, bailout, &orig_tail);
4859
4860 if (bailout->req() > 1) {
4861 PreserveJVMState pjvms(this);
4862 set_control(_gvn.transform(bailout));
4863 uncommon_trap(Deoptimization::Reason_intrinsic,
4864 Deoptimization::Action_maybe_recompile);
4865 }
4866
4867 if (!stopped()) {
4868 // How many elements will we copy from the original?
4869 // The answer is MinI(orig_tail, length).
4870 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4871
4872 // Generate a direct call to the right arraycopy function(s).
4873 // We know the copy is disjoint but we might not know if the
4874 // oop stores need checking.
4875 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
4881 // to the copyOf to be validated, including that the copy to the
4882 // new array won't trigger an ArrayStoreException. That subtype
4883 // check can be optimized if we know something on the type of
4884 // the input array from type speculation.
4885 if (_gvn.type(klass_node)->singleton()) {
4886 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
4887 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
4888
4889 int test = C->static_subtype_check(superk, subk);
4890 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4891 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4892 if (t_original->speculative_type() != nullptr) {
4893 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4894 }
4895 }
4896 }
4897
4898 bool validated = false;
4899 // Reason_class_check rather than Reason_intrinsic because we
4900 // want to intrinsify even if this traps.
4901 if (can_validate) {
4902 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4903
4904 if (not_subtype_ctrl != top()) {
4905 PreserveJVMState pjvms(this);
4906 set_control(not_subtype_ctrl);
4907 uncommon_trap(Deoptimization::Reason_class_check,
4908 Deoptimization::Action_make_not_entrant);
4909 assert(stopped(), "Should be stopped");
4910 }
4911 validated = true;
4912 }
4913
4914 if (!stopped()) {
4915 newcopy = new_array(klass_node, length, 0); // no arguments to push
4916
4917 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4918 load_object_klass(original), klass_node);
4919 if (!is_copyOfRange) {
4920 ac->set_copyof(validated);
4921 } else {
4967
4968 //-----------------------generate_method_call----------------------------
4969 // Use generate_method_call to make a slow-call to the real
4970 // method if the fast path fails. An alternative would be to
4971 // use a stub like OptoRuntime::slow_arraycopy_Java.
4972 // This only works for expanding the current library call,
4973 // not another intrinsic. (E.g., don't use this for making an
4974 // arraycopy call inside of the copyOf intrinsic.)
4975 CallJavaNode*
4976 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4977 // When compiling the intrinsic method itself, do not use this technique.
4978 guarantee(callee() != C->method(), "cannot make slow-call to self");
4979
4980 ciMethod* method = callee();
4981 // ensure the JVMS we have will be correct for this call
4982 guarantee(method_id == method->intrinsic_id(), "must match");
4983
4984 const TypeFunc* tf = TypeFunc::make(method);
4985 if (res_not_null) {
4986 assert(tf->return_type() == T_OBJECT, "");
4987 const TypeTuple* range = tf->range_cc();
4988 const Type** fields = TypeTuple::fields(range->cnt());
4989 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4990 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4991 tf = TypeFunc::make(tf->domain_cc(), new_range);
4992 }
4993 CallJavaNode* slow_call;
4994 if (is_static) {
4995 assert(!is_virtual, "");
4996 slow_call = new CallStaticJavaNode(C, tf,
4997 SharedRuntime::get_resolve_static_call_stub(), method);
4998 } else if (is_virtual) {
4999 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5000 int vtable_index = Method::invalid_vtable_index;
5001 if (UseInlineCaches) {
5002 // Suppress the vtable call
5003 } else {
5004 // hashCode and clone are not a miranda methods,
5005 // so the vtable index is fixed.
5006 // No need to use the linkResolver to get it.
5007 vtable_index = method->vtable_index();
5008 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5009 "bad index %d", vtable_index);
5010 }
5011 slow_call = new CallDynamicJavaNode(tf,
5028 set_edges_for_java_call(slow_call);
5029 return slow_call;
5030 }
5031
5032
5033 /**
5034 * Build special case code for calls to hashCode on an object. This call may
5035 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5036 * slightly different code.
5037 */
5038 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5039 assert(is_static == callee()->is_static(), "correct intrinsic selection");
5040 assert(!(is_virtual && is_static), "either virtual, special, or static");
5041
5042 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5043
5044 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5045 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
5046 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
5047 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5048 Node* obj = argument(0);
5049
5050 // Don't intrinsify hashcode on inline types for now.
5051 // The "is locked" runtime check below also serves as inline type check and goes to the slow path.
5052 if (gvn().type(obj)->is_inlinetypeptr()) {
5053 return false;
5054 }
5055
5056 if (!is_static) {
5057 // Check for hashing null object
5058 obj = null_check_receiver();
5059 if (stopped()) return true; // unconditionally null
5060 result_reg->init_req(_null_path, top());
5061 result_val->init_req(_null_path, top());
5062 } else {
5063 // Do a null check, and return zero if null.
5064 // System.identityHashCode(null) == 0
5065 Node* null_ctl = top();
5066 obj = null_check_oop(obj, &null_ctl);
5067 result_reg->init_req(_null_path, null_ctl);
5068 result_val->init_req(_null_path, _gvn.intcon(0));
5069 }
5070
5071 // Unconditionally null? Then return right away.
5072 if (stopped()) {
5073 set_control( result_reg->in(_null_path));
5074 if (!stopped())
5075 set_result(result_val->in(_null_path));
5076 return true;
5077 }
5078
5079 // We only go to the fast case code if we pass a number of guards. The
5080 // paths which do not pass are accumulated in the slow_region.
5081 RegionNode* slow_region = new RegionNode(1);
5082 record_for_igvn(slow_region);
5083
5084 // If this is a virtual call, we generate a funny guard. We pull out
5085 // the vtable entry corresponding to hashCode() from the target object.
5086 // If the target method which we are calling happens to be the native
5087 // Object hashCode() method, we pass the guard. We do not need this
5088 // guard for non-virtual calls -- the caller is known to be the native
5089 // Object hashCode().
5090 if (is_virtual) {
5091 // After null check, get the object's klass.
5092 Node* obj_klass = load_object_klass(obj);
5093 generate_virtual_guard(obj_klass, slow_region);
5094 }
5095
5096 // Get the header out of the object, use LoadMarkNode when available
5097 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5098 // The control of the load must be null. Otherwise, the load can move before
5099 // the null check after castPP removal.
5100 Node* no_ctrl = nullptr;
5101 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5102
5103 if (!UseObjectMonitorTable) {
5104 // Test the header to see if it is safe to read w.r.t. locking.
5105 // This also serves as guard against inline types
5106 Node *lock_mask = _gvn.MakeConX(markWord::inline_type_mask_in_place);
5107 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5108 if (LockingMode == LM_LIGHTWEIGHT) {
5109 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
5110 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5111 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5112
5113 generate_slow_guard(test_monitor, slow_region);
5114 } else {
5115 Node *unlocked_val = _gvn.MakeConX(markWord::unlocked_value);
5116 Node *chk_unlocked = _gvn.transform(new CmpXNode(lmasked_header, unlocked_val));
5117 Node *test_not_unlocked = _gvn.transform(new BoolNode(chk_unlocked, BoolTest::ne));
5118
5119 generate_slow_guard(test_not_unlocked, slow_region);
5120 }
5121 }
5122
5123 // Get the hash value and check to see that it has been properly assigned.
5124 // We depend on hash_mask being at most 32 bits and avoid the use of
5125 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5126 // vm: see markWord.hpp.
5161 // this->control() comes from set_results_for_java_call
5162 result_reg->init_req(_slow_path, control());
5163 result_val->init_req(_slow_path, slow_result);
5164 result_io ->set_req(_slow_path, i_o());
5165 result_mem ->set_req(_slow_path, reset_memory());
5166 }
5167
5168 // Return the combined state.
5169 set_i_o( _gvn.transform(result_io) );
5170 set_all_memory( _gvn.transform(result_mem));
5171
5172 set_result(result_reg, result_val);
5173 return true;
5174 }
5175
5176 //---------------------------inline_native_getClass----------------------------
5177 // public final native Class<?> java.lang.Object.getClass();
5178 //
5179 // Build special case code for calls to getClass on an object.
5180 bool LibraryCallKit::inline_native_getClass() {
5181 Node* obj = argument(0);
5182 if (obj->is_InlineType()) {
5183 const Type* t = _gvn.type(obj);
5184 if (t->maybe_null()) {
5185 null_check(obj);
5186 }
5187 set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5188 return true;
5189 }
5190 obj = null_check_receiver();
5191 if (stopped()) return true;
5192 set_result(load_mirror_from_klass(load_object_klass(obj)));
5193 return true;
5194 }
5195
5196 //-----------------inline_native_Reflection_getCallerClass---------------------
5197 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5198 //
5199 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5200 //
5201 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5202 // in that it must skip particular security frames and checks for
5203 // caller sensitive methods.
5204 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5205 #ifndef PRODUCT
5206 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5207 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5208 }
5209 #endif
5210
5522 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5523
5524 flags |= RC_NARROW_MEM; // narrow in memory
5525 }
5526
5527 // Call it. Note that the length argument is not scaled.
5528 make_runtime_call(flags,
5529 OptoRuntime::unsafe_setmemory_Type(),
5530 StubRoutines::unsafe_setmemory(),
5531 "unsafe_setmemory",
5532 dst_type,
5533 dst_addr, size XTOP, byte);
5534
5535 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5536
5537 return true;
5538 }
5539
5540 #undef XTOP
5541
5542 //----------------------inline_unsafe_isFlatArray------------------------
5543 // public native boolean Unsafe.isFlatArray(Class<?> arrayClass);
5544 // This intrinsic exploits assumptions made by the native implementation
5545 // (arrayClass is neither null nor primitive) to avoid unnecessary null checks.
5546 bool LibraryCallKit::inline_unsafe_isFlatArray() {
5547 Node* cls = argument(1);
5548 Node* p = basic_plus_adr(cls, java_lang_Class::klass_offset());
5549 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p,
5550 TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
5551 Node* result = flat_array_test(kls);
5552 set_result(result);
5553 return true;
5554 }
5555
5556 //------------------------clone_coping-----------------------------------
5557 // Helper function for inline_native_clone.
5558 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5559 assert(obj_size != nullptr, "");
5560 Node* raw_obj = alloc_obj->in(1);
5561 assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5562
5563 AllocateNode* alloc = nullptr;
5564 if (ReduceBulkZeroing &&
5565 // If we are implementing an array clone without knowing its source type
5566 // (can happen when compiling the array-guarded branch of a reflective
5567 // Object.clone() invocation), initialize the array within the allocation.
5568 // This is needed because some GCs (e.g. ZGC) might fall back in this case
5569 // to a runtime clone call that assumes fully initialized source arrays.
5570 (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5571 // We will be completely responsible for initializing this object -
5572 // mark Initialize node as complete.
5573 alloc = AllocateNode::Ideal_allocation(alloc_obj);
5574 // The object was just allocated - there should be no any stores!
5575 guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5606 // not cloneable or finalizer => slow path to out-of-line Object.clone
5607 //
5608 // The general case has two steps, allocation and copying.
5609 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5610 //
5611 // Copying also has two cases, oop arrays and everything else.
5612 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5613 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5614 //
5615 // These steps fold up nicely if and when the cloned object's klass
5616 // can be sharply typed as an object array, a type array, or an instance.
5617 //
5618 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5619 PhiNode* result_val;
5620
5621 // Set the reexecute bit for the interpreter to reexecute
5622 // the bytecode that invokes Object.clone if deoptimization happens.
5623 { PreserveReexecuteState preexecs(this);
5624 jvms()->set_should_reexecute(true);
5625
5626 Node* obj = argument(0);
5627 obj = null_check_receiver();
5628 if (stopped()) return true;
5629
5630 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5631 if (obj_type->is_inlinetypeptr()) {
5632 // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5633 // no identity.
5634 set_result(obj);
5635 return true;
5636 }
5637
5638 // If we are going to clone an instance, we need its exact type to
5639 // know the number and types of fields to convert the clone to
5640 // loads/stores. Maybe a speculative type can help us.
5641 if (!obj_type->klass_is_exact() &&
5642 obj_type->speculative_type() != nullptr &&
5643 obj_type->speculative_type()->is_instance_klass() &&
5644 !obj_type->speculative_type()->is_inlinetype()) {
5645 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5646 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5647 !spec_ik->has_injected_fields()) {
5648 if (!obj_type->isa_instptr() ||
5649 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5650 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5651 }
5652 }
5653 }
5654
5655 // Conservatively insert a memory barrier on all memory slices.
5656 // Do not let writes into the original float below the clone.
5657 insert_mem_bar(Op_MemBarCPUOrder);
5658
5659 // paths into result_reg:
5660 enum {
5661 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5662 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5663 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5664 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5665 PATH_LIMIT
5666 };
5667 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5668 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5669 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5670 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5671 record_for_igvn(result_reg);
5672
5673 // TODO 8350865 For arrays, this might be folded and then not account for atomic arrays
5674 Node* obj_klass = load_object_klass(obj);
5675 // We only go to the fast case code if we pass a number of guards.
5676 // The paths which do not pass are accumulated in the slow_region.
5677 RegionNode* slow_region = new RegionNode(1);
5678 record_for_igvn(slow_region);
5679
5680 Node* array_obj = obj;
5681 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5682 if (array_ctl != nullptr) {
5683 // It's an array.
5684 PreserveJVMState pjvms(this);
5685 set_control(array_ctl);
5686
5687 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5688 const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5689 if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5690 obj_type->can_be_inline_array() &&
5691 (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5692 // Flat inline type array may have object field that would require a
5693 // write barrier. Conservatively, go to slow path.
5694 generate_fair_guard(flat_array_test(obj_klass), slow_region);
5695 }
5696
5697 if (!stopped()) {
5698 Node* obj_length = load_array_length(array_obj);
5699 Node* array_size = nullptr; // Size of the array without object alignment padding.
5700 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5701
5702 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5703 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5704 // If it is an oop array, it requires very special treatment,
5705 // because gc barriers are required when accessing the array.
5706 Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5707 if (is_obja != nullptr) {
5708 PreserveJVMState pjvms2(this);
5709 set_control(is_obja);
5710 // Generate a direct call to the right arraycopy function(s).
5711 // Clones are always tightly coupled.
5712 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5713 ac->set_clone_oop_array();
5714 Node* n = _gvn.transform(ac);
5715 assert(n == ac, "cannot disappear");
5716 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5717
5718 result_reg->init_req(_objArray_path, control());
5719 result_val->init_req(_objArray_path, alloc_obj);
5720 result_i_o ->set_req(_objArray_path, i_o());
5721 result_mem ->set_req(_objArray_path, reset_memory());
5722 }
5723 }
5724 // Otherwise, there are no barriers to worry about.
5725 // (We can dispense with card marks if we know the allocation
5726 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5727 // causes the non-eden paths to take compensating steps to
5728 // simulate a fresh allocation, so that no further
5729 // card marks are required in compiled code to initialize
5730 // the object.)
5731
5732 if (!stopped()) {
5733 copy_to_clone(obj, alloc_obj, array_size, true);
5734
5735 // Present the results of the copy.
5736 result_reg->init_req(_array_path, control());
5737 result_val->init_req(_array_path, alloc_obj);
5738 result_i_o ->set_req(_array_path, i_o());
5739 result_mem ->set_req(_array_path, reset_memory());
5740 }
5741 }
5742 }
5743
5744 if (!stopped()) {
5745 // It's an instance (we did array above). Make the slow-path tests.
5746 // If this is a virtual call, we generate a funny guard. We grab
5747 // the vtable entry corresponding to clone() from the target object.
5748 // If the target method which we are calling happens to be the
5749 // Object clone() method, we pass the guard. We do not need this
5750 // guard for non-virtual calls; the caller is known to be the native
5751 // Object clone().
5752 if (is_virtual) {
5753 generate_virtual_guard(obj_klass, slow_region);
5754 }
5755
5756 // The object must be easily cloneable and must not have a finalizer.
5757 // Both of these conditions may be checked in a single test.
5758 // We could optimize the test further, but we don't care.
5759 generate_misc_flags_guard(obj_klass,
5760 // Test both conditions:
5761 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5762 // Must be cloneable but not finalizer:
5763 KlassFlags::_misc_is_cloneable_fast,
5855 set_jvms(sfpt->jvms());
5856 _reexecute_sp = jvms()->sp();
5857
5858 return saved_jvms;
5859 }
5860 }
5861 }
5862 return nullptr;
5863 }
5864
5865 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5866 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5867 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5868 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5869 uint size = alloc->req();
5870 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5871 old_jvms->set_map(sfpt);
5872 for (uint i = 0; i < size; i++) {
5873 sfpt->init_req(i, alloc->in(i));
5874 }
5875 int adjustment = 1;
5876 const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
5877 if (ary_klass_ptr->is_null_free()) {
5878 // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
5879 // also requires the componentType and initVal on stack for re-execution.
5880 // Re-create and push the componentType.
5881 ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
5882 ciInstance* instance = klass->component_mirror_instance();
5883 const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
5884 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
5885 adjustment++;
5886 }
5887 // re-push array length for deoptimization
5888 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
5889 if (ary_klass_ptr->is_null_free()) {
5890 // Re-create and push the initVal.
5891 Node* init_val = alloc->in(AllocateNode::InitValue);
5892 if (init_val == nullptr) {
5893 init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
5894 } else if (UseCompressedOops) {
5895 init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
5896 }
5897 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
5898 adjustment++;
5899 }
5900 old_jvms->set_sp(old_jvms->sp() + adjustment);
5901 old_jvms->set_monoff(old_jvms->monoff() + adjustment);
5902 old_jvms->set_scloff(old_jvms->scloff() + adjustment);
5903 old_jvms->set_endoff(old_jvms->endoff() + adjustment);
5904 old_jvms->set_should_reexecute(true);
5905
5906 sfpt->set_i_o(map()->i_o());
5907 sfpt->set_memory(map()->memory());
5908 sfpt->set_control(map()->control());
5909 return sfpt;
5910 }
5911
5912 // In case of a deoptimization, we restart execution at the
5913 // allocation, allocating a new array. We would leave an uninitialized
5914 // array in the heap that GCs wouldn't expect. Move the allocation
5915 // after the traps so we don't allocate the array if we
5916 // deoptimize. This is possible because tightly_coupled_allocation()
5917 // guarantees there's no observer of the allocated array at this point
5918 // and the control flow is simple enough.
5919 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5920 int saved_reexecute_sp, uint new_idx) {
5921 if (saved_jvms_before_guards != nullptr && !stopped()) {
5922 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5923
5924 assert(alloc != nullptr, "only with a tightly coupled allocation");
5925 // restore JVM state to the state at the arraycopy
5926 saved_jvms_before_guards->map()->set_control(map()->control());
5927 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5928 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5929 // If we've improved the types of some nodes (null check) while
5930 // emitting the guards, propagate them to the current state
5931 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5932 set_jvms(saved_jvms_before_guards);
5933 _reexecute_sp = saved_reexecute_sp;
5934
5935 // Remove the allocation from above the guards
5936 CallProjections* callprojs = alloc->extract_projections(true);
5937 InitializeNode* init = alloc->initialization();
5938 Node* alloc_mem = alloc->in(TypeFunc::Memory);
5939 C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5940 C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
5941
5942 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5943 // the allocation (i.e. is only valid if the allocation succeeds):
5944 // 1) replace CastIINode with AllocateArrayNode's length here
5945 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5946 //
5947 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5948 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5949 Node* init_control = init->proj_out(TypeFunc::Control);
5950 Node* alloc_length = alloc->Ideal_length();
5951 #ifdef ASSERT
5952 Node* prev_cast = nullptr;
5953 #endif
5954 for (uint i = 0; i < init_control->outcnt(); i++) {
5955 Node* init_out = init_control->raw_out(i);
5956 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5957 #ifdef ASSERT
5958 if (prev_cast == nullptr) {
5959 prev_cast = init_out;
5961 if (prev_cast->cmp(*init_out) == false) {
5962 prev_cast->dump();
5963 init_out->dump();
5964 assert(false, "not equal CastIINode");
5965 }
5966 }
5967 #endif
5968 C->gvn_replace_by(init_out, alloc_length);
5969 }
5970 }
5971 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5972
5973 // move the allocation here (after the guards)
5974 _gvn.hash_delete(alloc);
5975 alloc->set_req(TypeFunc::Control, control());
5976 alloc->set_req(TypeFunc::I_O, i_o());
5977 Node *mem = reset_memory();
5978 set_all_memory(mem);
5979 alloc->set_req(TypeFunc::Memory, mem);
5980 set_control(init->proj_out_or_null(TypeFunc::Control));
5981 set_i_o(callprojs->fallthrough_ioproj);
5982
5983 // Update memory as done in GraphKit::set_output_for_allocation()
5984 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5985 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5986 if (ary_type->isa_aryptr() && length_type != nullptr) {
5987 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5988 }
5989 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5990 int elemidx = C->get_alias_index(telemref);
5991 set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
5992 set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
5993
5994 Node* allocx = _gvn.transform(alloc);
5995 assert(allocx == alloc, "where has the allocation gone?");
5996 assert(dest->is_CheckCastPP(), "not an allocation result?");
5997
5998 _gvn.hash_delete(dest);
5999 dest->set_req(0, control());
6000 Node* destx = _gvn.transform(dest);
6001 assert(destx == dest, "where has the allocation result gone?");
6299 top_src = src_type->isa_aryptr();
6300 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6301 src_spec = true;
6302 }
6303 if (!has_dest) {
6304 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6305 dest_type = _gvn.type(dest);
6306 top_dest = dest_type->isa_aryptr();
6307 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6308 dest_spec = true;
6309 }
6310 }
6311 }
6312
6313 if (has_src && has_dest && can_emit_guards) {
6314 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6315 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6316 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6317 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6318
6319 if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6320 // If both arrays are object arrays then having the exact types
6321 // for both will remove the need for a subtype check at runtime
6322 // before the call and may make it possible to pick a faster copy
6323 // routine (without a subtype check on every element)
6324 // Do we have the exact type of src?
6325 bool could_have_src = src_spec;
6326 // Do we have the exact type of dest?
6327 bool could_have_dest = dest_spec;
6328 ciKlass* src_k = nullptr;
6329 ciKlass* dest_k = nullptr;
6330 if (!src_spec) {
6331 src_k = src_type->speculative_type_not_null();
6332 if (src_k != nullptr && src_k->is_array_klass()) {
6333 could_have_src = true;
6334 }
6335 }
6336 if (!dest_spec) {
6337 dest_k = dest_type->speculative_type_not_null();
6338 if (dest_k != nullptr && dest_k->is_array_klass()) {
6339 could_have_dest = true;
6340 }
6341 }
6342 if (could_have_src && could_have_dest) {
6343 // If we can have both exact types, emit the missing guards
6344 if (could_have_src && !src_spec) {
6345 src = maybe_cast_profiled_obj(src, src_k, true);
6346 src_type = _gvn.type(src);
6347 top_src = src_type->isa_aryptr();
6348 }
6349 if (could_have_dest && !dest_spec) {
6350 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6351 dest_type = _gvn.type(dest);
6352 top_dest = dest_type->isa_aryptr();
6353 }
6354 }
6355 }
6356 }
6357
6358 ciMethod* trap_method = method();
6359 int trap_bci = bci();
6360 if (saved_jvms_before_guards != nullptr) {
6361 trap_method = alloc->jvms()->method();
6362 trap_bci = alloc->jvms()->bci();
6363 }
6364
6365 bool negative_length_guard_generated = false;
6366
6367 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6368 can_emit_guards && !src->is_top() && !dest->is_top()) {
6369 // validate arguments: enables transformation the ArrayCopyNode
6370 validated = true;
6371
6372 RegionNode* slow_region = new RegionNode(1);
6373 record_for_igvn(slow_region);
6374
6375 // (1) src and dest are arrays.
6376 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6377 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6378
6379 // (2) src and dest arrays must have elements of the same BasicType
6380 // done at macro expansion or at Ideal transformation time
6381
6382 // (4) src_offset must not be negative.
6383 generate_negative_guard(src_offset, slow_region);
6384
6385 // (5) dest_offset must not be negative.
6386 generate_negative_guard(dest_offset, slow_region);
6387
6388 // (7) src_offset + length must not exceed length of src.
6391 slow_region);
6392
6393 // (8) dest_offset + length must not exceed length of dest.
6394 generate_limit_guard(dest_offset, length,
6395 load_array_length(dest),
6396 slow_region);
6397
6398 // (6) length must not be negative.
6399 // This is also checked in generate_arraycopy() during macro expansion, but
6400 // we also have to check it here for the case where the ArrayCopyNode will
6401 // be eliminated by Escape Analysis.
6402 if (EliminateAllocations) {
6403 generate_negative_guard(length, slow_region);
6404 negative_length_guard_generated = true;
6405 }
6406
6407 // (9) each element of an oop array must be assignable
6408 Node* dest_klass = load_object_klass(dest);
6409 if (src != dest) {
6410 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6411 slow_region->add_req(not_subtype_ctrl);
6412 }
6413
6414 // TODO 8350865 Fix below logic. Also handle atomicity.
6415 generate_fair_guard(flat_array_test(src), slow_region);
6416 generate_fair_guard(flat_array_test(dest), slow_region);
6417
6418 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6419 const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6420 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6421 src_type = _gvn.type(src);
6422 top_src = src_type->isa_aryptr();
6423
6424 // Handle flat inline type arrays (null-free arrays are handled by the subtype check above)
6425 if (!stopped() && UseArrayFlattening) {
6426 // If dest is flat, src must be flat as well (guaranteed by src <: dest check). Handle flat src here.
6427 assert(top_dest == nullptr || !top_dest->is_flat() || top_src->is_flat(), "src array must be flat");
6428 if (top_src != nullptr && top_src->is_flat()) {
6429 // Src is flat, check that dest is flat as well
6430 if (top_dest != nullptr && !top_dest->is_flat()) {
6431 generate_fair_guard(flat_array_test(dest_klass, /* flat = */ false), slow_region);
6432 // Since dest is flat and src <: dest, dest must have the same type as src.
6433 top_dest = top_src->cast_to_exactness(false);
6434 assert(top_dest->is_flat(), "dest must be flat");
6435 dest = _gvn.transform(new CheckCastPPNode(control(), dest, top_dest));
6436 }
6437 } else if (top_src == nullptr || !top_src->is_not_flat()) {
6438 // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
6439 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
6440 assert(top_dest == nullptr || !top_dest->is_flat(), "dest array must not be flat");
6441 generate_fair_guard(flat_array_test(src), slow_region);
6442 if (top_src != nullptr) {
6443 top_src = top_src->cast_to_not_flat();
6444 src = _gvn.transform(new CheckCastPPNode(control(), src, top_src));
6445 }
6446 }
6447 }
6448
6449 {
6450 PreserveJVMState pjvms(this);
6451 set_control(_gvn.transform(slow_region));
6452 uncommon_trap(Deoptimization::Reason_intrinsic,
6453 Deoptimization::Action_make_not_entrant);
6454 assert(stopped(), "Should be stopped");
6455 }
6456 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6457 }
6458
6459 if (stopped()) {
6460 return true;
6461 }
6462
6463 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6464 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6465 // so the compiler has a chance to eliminate them: during macro expansion,
6466 // we have to set their control (CastPP nodes are eliminated).
6467 load_object_klass(src), load_object_klass(dest),
6468 load_array_length(src), load_array_length(dest));
6469
6470 ac->set_arraycopy(validated);
6471
6472 Node* n = _gvn.transform(ac);
6473 if (n == ac) {
6474 ac->connect_outputs(this);
6475 } else {
|