1 /*
2 * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "asm/macroAssembler.hpp"
26 #include "ci/ciSymbols.hpp"
27 #include "ci/ciUtilities.inline.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"
46 #include "opto/mulnode.hpp"
47 #include "opto/narrowptrnode.hpp"
48 #include "opto/opaquenode.hpp"
49 #include "opto/parse.hpp"
50 #include "opto/rootnode.hpp"
51 #include "opto/runtime.hpp"
52 #include "opto/subnode.hpp"
53 #include "opto/vectornode.hpp"
54 #include "prims/jvmtiExport.hpp"
55 #include "prims/jvmtiThreadState.hpp"
56 #include "prims/unsafe.hpp"
57 #include "runtime/jniHandles.inline.hpp"
58 #include "runtime/mountUnmountDisabler.hpp"
59 #include "runtime/objectMonitor.hpp"
60 #include "runtime/sharedRuntime.hpp"
61 #include "runtime/stubRoutines.hpp"
62 #include "utilities/macros.hpp"
63 #include "utilities/powerOfTwo.hpp"
64
65 //---------------------------make_vm_intrinsic----------------------------
66 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
67 vmIntrinsicID id = m->intrinsic_id();
68 assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
69
70 if (!m->is_loaded()) {
71 // Do not attempt to inline unloaded methods.
72 return nullptr;
73 }
74
75 C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
76 bool is_available = false;
77
78 {
79 // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
80 // the compiler must transition to '_thread_in_vm' state because both
81 // methods access VM-internal data.
392 case vmIntrinsics::_getReferenceOpaque: return inline_unsafe_access(!is_store, T_OBJECT, Opaque, false);
393 case vmIntrinsics::_getBooleanOpaque: return inline_unsafe_access(!is_store, T_BOOLEAN, Opaque, false);
394 case vmIntrinsics::_getByteOpaque: return inline_unsafe_access(!is_store, T_BYTE, Opaque, false);
395 case vmIntrinsics::_getShortOpaque: return inline_unsafe_access(!is_store, T_SHORT, Opaque, false);
396 case vmIntrinsics::_getCharOpaque: return inline_unsafe_access(!is_store, T_CHAR, Opaque, false);
397 case vmIntrinsics::_getIntOpaque: return inline_unsafe_access(!is_store, T_INT, Opaque, false);
398 case vmIntrinsics::_getLongOpaque: return inline_unsafe_access(!is_store, T_LONG, Opaque, false);
399 case vmIntrinsics::_getFloatOpaque: return inline_unsafe_access(!is_store, T_FLOAT, Opaque, false);
400 case vmIntrinsics::_getDoubleOpaque: return inline_unsafe_access(!is_store, T_DOUBLE, Opaque, false);
401
402 case vmIntrinsics::_putReferenceOpaque: return inline_unsafe_access( is_store, T_OBJECT, Opaque, false);
403 case vmIntrinsics::_putBooleanOpaque: return inline_unsafe_access( is_store, T_BOOLEAN, Opaque, false);
404 case vmIntrinsics::_putByteOpaque: return inline_unsafe_access( is_store, T_BYTE, Opaque, false);
405 case vmIntrinsics::_putShortOpaque: return inline_unsafe_access( is_store, T_SHORT, Opaque, false);
406 case vmIntrinsics::_putCharOpaque: return inline_unsafe_access( is_store, T_CHAR, Opaque, false);
407 case vmIntrinsics::_putIntOpaque: return inline_unsafe_access( is_store, T_INT, Opaque, false);
408 case vmIntrinsics::_putLongOpaque: return inline_unsafe_access( is_store, T_LONG, Opaque, false);
409 case vmIntrinsics::_putFloatOpaque: return inline_unsafe_access( is_store, T_FLOAT, Opaque, false);
410 case vmIntrinsics::_putDoubleOpaque: return inline_unsafe_access( is_store, T_DOUBLE, Opaque, false);
411
412 case vmIntrinsics::_compareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap, Volatile);
413 case vmIntrinsics::_compareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap, Volatile);
414 case vmIntrinsics::_compareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap, Volatile);
415 case vmIntrinsics::_compareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap, Volatile);
416 case vmIntrinsics::_compareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap, Volatile);
417
418 case vmIntrinsics::_weakCompareAndSetReferencePlain: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
419 case vmIntrinsics::_weakCompareAndSetReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
420 case vmIntrinsics::_weakCompareAndSetReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
421 case vmIntrinsics::_weakCompareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
422 case vmIntrinsics::_weakCompareAndSetBytePlain: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Relaxed);
423 case vmIntrinsics::_weakCompareAndSetByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Acquire);
424 case vmIntrinsics::_weakCompareAndSetByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Release);
425 case vmIntrinsics::_weakCompareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Volatile);
426 case vmIntrinsics::_weakCompareAndSetShortPlain: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Relaxed);
427 case vmIntrinsics::_weakCompareAndSetShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Acquire);
428 case vmIntrinsics::_weakCompareAndSetShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Release);
429 case vmIntrinsics::_weakCompareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Volatile);
430 case vmIntrinsics::_weakCompareAndSetIntPlain: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Relaxed);
431 case vmIntrinsics::_weakCompareAndSetIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Acquire);
451 case vmIntrinsics::_compareAndExchangeLong: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Volatile);
452 case vmIntrinsics::_compareAndExchangeLongAcquire: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Acquire);
453 case vmIntrinsics::_compareAndExchangeLongRelease: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Release);
454
455 case vmIntrinsics::_getAndAddByte: return inline_unsafe_load_store(T_BYTE, LS_get_add, Volatile);
456 case vmIntrinsics::_getAndAddShort: return inline_unsafe_load_store(T_SHORT, LS_get_add, Volatile);
457 case vmIntrinsics::_getAndAddInt: return inline_unsafe_load_store(T_INT, LS_get_add, Volatile);
458 case vmIntrinsics::_getAndAddLong: return inline_unsafe_load_store(T_LONG, LS_get_add, Volatile);
459
460 case vmIntrinsics::_getAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_get_set, Volatile);
461 case vmIntrinsics::_getAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_get_set, Volatile);
462 case vmIntrinsics::_getAndSetInt: return inline_unsafe_load_store(T_INT, LS_get_set, Volatile);
463 case vmIntrinsics::_getAndSetLong: return inline_unsafe_load_store(T_LONG, LS_get_set, Volatile);
464 case vmIntrinsics::_getAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_get_set, Volatile);
465
466 case vmIntrinsics::_loadFence:
467 case vmIntrinsics::_storeFence:
468 case vmIntrinsics::_storeStoreFence:
469 case vmIntrinsics::_fullFence: return inline_unsafe_fence(intrinsic_id());
470
471 case vmIntrinsics::_onSpinWait: return inline_onspinwait();
472
473 case vmIntrinsics::_currentCarrierThread: return inline_native_currentCarrierThread();
474 case vmIntrinsics::_currentThread: return inline_native_currentThread();
475 case vmIntrinsics::_setCurrentThread: return inline_native_setCurrentThread();
476
477 case vmIntrinsics::_scopedValueCache: return inline_native_scopedValueCache();
478 case vmIntrinsics::_setScopedValueCache: return inline_native_setScopedValueCache();
479
480 case vmIntrinsics::_Continuation_pin: return inline_native_Continuation_pinning(false);
481 case vmIntrinsics::_Continuation_unpin: return inline_native_Continuation_pinning(true);
482
483 case vmIntrinsics::_vthreadEndFirstTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
484 "endFirstTransition", true);
485 case vmIntrinsics::_vthreadStartFinalTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
486 "startFinalTransition", true);
487 case vmIntrinsics::_vthreadStartTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
488 "startTransition", false);
489 case vmIntrinsics::_vthreadEndTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
490 "endTransition", false);
499 #endif
500 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
501 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
502 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
503 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
504 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
505 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
506 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
507 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
508 case vmIntrinsics::_getLength: return inline_native_getLength();
509 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
510 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
511 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
512 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
513 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
514 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
515 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
516
517 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
518 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
519
520 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
521
522 case vmIntrinsics::_isInstance:
523 case vmIntrinsics::_isHidden:
524 case vmIntrinsics::_getSuperclass: return inline_native_Class_query(intrinsic_id());
525
526 case vmIntrinsics::_floatToRawIntBits:
527 case vmIntrinsics::_floatToIntBits:
528 case vmIntrinsics::_intBitsToFloat:
529 case vmIntrinsics::_doubleToRawLongBits:
530 case vmIntrinsics::_doubleToLongBits:
531 case vmIntrinsics::_longBitsToDouble:
532 case vmIntrinsics::_floatToFloat16:
533 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
534 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
535 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
536 case vmIntrinsics::_floatIsFinite:
537 case vmIntrinsics::_floatIsInfinite:
538 case vmIntrinsics::_doubleIsFinite:
2303 case vmIntrinsics::_remainderUnsigned_l: {
2304 zero_check_long(argument(2));
2305 // Compile-time detect of null-exception
2306 if (stopped()) {
2307 return true; // keep the graph constructed so far
2308 }
2309 n = new UModLNode(control(), argument(0), argument(2));
2310 break;
2311 }
2312 default: fatal_unexpected_iid(id); break;
2313 }
2314 set_result(_gvn.transform(n));
2315 return true;
2316 }
2317
2318 //----------------------------inline_unsafe_access----------------------------
2319
2320 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2321 // Attempt to infer a sharper value type from the offset and base type.
2322 ciKlass* sharpened_klass = nullptr;
2323
2324 // See if it is an instance field, with an object type.
2325 if (alias_type->field() != nullptr) {
2326 if (alias_type->field()->type()->is_klass()) {
2327 sharpened_klass = alias_type->field()->type()->as_klass();
2328 }
2329 }
2330
2331 const TypeOopPtr* result = nullptr;
2332 // See if it is a narrow oop array.
2333 if (adr_type->isa_aryptr()) {
2334 if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2335 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2336 if (elem_type != nullptr && elem_type->is_loaded()) {
2337 // Sharpen the value type.
2338 result = elem_type;
2339 }
2340 }
2341 }
2342
2343 // The sharpened class might be unloaded if there is no class loader
2344 // contraint in place.
2345 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2346 // Sharpen the value type.
2347 result = TypeOopPtr::make_from_klass(sharpened_klass);
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;
2456 #endif // ASSERT
2457 }
2458 #endif //PRODUCT
2459
2460 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2461
2462 Node* receiver = argument(0); // type: oop
2463
2464 // Build address expression.
2465 Node* heap_base_oop = top();
2466
2467 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2468 Node* base = argument(1); // type: oop
2469 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2470 Node* offset = argument(2); // type: long
2471 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2472 // to be plain byte offsets, which are also the same as those accepted
2473 // by oopDesc::field_addr.
2474 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2475 "fieldOffset must be byte-scaled");
2476 // 32-bit machines ignore the high half!
2477 offset = ConvL2X(offset);
2478
2479 // Save state and restore on bailout
2480 SavedState old_state(this);
2481
2482 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2483 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2484
2485 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2486 if (type != T_OBJECT) {
2487 decorators |= IN_NATIVE; // off-heap primitive access
2488 } else {
2489 return false; // off-heap oop accesses are not supported
2490 }
2491 } else {
2492 heap_base_oop = base; // on-heap or mixed access
2493 }
2494
2495 // Can base be null? Otherwise, always on-heap access.
2499 decorators |= IN_HEAP;
2500 }
2501
2502 Node* val = is_store ? argument(4) : nullptr;
2503
2504 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2505 if (adr_type == TypePtr::NULL_PTR) {
2506 return false; // off-heap access with zero address
2507 }
2508
2509 // Try to categorize the address.
2510 Compile::AliasType* alias_type = C->alias_type(adr_type);
2511 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2512
2513 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2514 alias_type->adr_type() == TypeAryPtr::RANGE) {
2515 return false; // not supported
2516 }
2517
2518 bool mismatched = false;
2519 BasicType bt = alias_type->basic_type();
2520 if (bt != T_ILLEGAL) {
2521 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2522 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2523 // Alias type doesn't differentiate between byte[] and boolean[]).
2524 // Use address type to get the element type.
2525 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2526 }
2527 if (is_reference_type(bt, true)) {
2528 // accessing an array field with getReference is not a mismatch
2529 bt = T_OBJECT;
2530 }
2531 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2532 // Don't intrinsify mismatched object accesses
2533 return false;
2534 }
2535 mismatched = (bt != type);
2536 } else if (alias_type->adr_type()->isa_oopptr()) {
2537 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2538 }
2539
2540 old_state.discard();
2541 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2542
2543 if (mismatched) {
2544 decorators |= C2_MISMATCHED;
2545 }
2546
2547 // First guess at the value type.
2548 const Type *value_type = Type::get_const_basic_type(type);
2549
2550 // Figure out the memory ordering.
2551 decorators |= mo_decorator_for_access_kind(kind);
2552
2553 if (!is_store && type == T_OBJECT) {
2554 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2555 if (tjp != nullptr) {
2556 value_type = tjp;
2557 }
2558 }
2559
2560 receiver = null_check(receiver);
2561 if (stopped()) {
2562 return true;
2563 }
2564 // Heap pointers get a null-check from the interpreter,
2565 // as a courtesy. However, this is not guaranteed by Unsafe,
2566 // and it is not possible to fully distinguish unintended nulls
2567 // from intended ones in this API.
2568
2569 if (!is_store) {
2570 Node* p = nullptr;
2571 // Try to constant fold a load from a constant field
2572 ciField* field = alias_type->field();
2573 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !mismatched) {
2574 // final or stable field
2575 p = make_constant_from_field(field, heap_base_oop);
2576 }
2577
2578 if (p == nullptr) { // Could not constant fold the load
2579 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2580 // Normalize the value returned by getBoolean in the following cases
2581 if (type == T_BOOLEAN &&
2582 (mismatched ||
2583 heap_base_oop == top() || // - heap_base_oop is null or
2584 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2585 // and the unsafe access is made to large offset
2586 // (i.e., larger than the maximum offset necessary for any
2587 // field access)
2588 ) {
2589 IdealKit ideal = IdealKit(this);
2590 #define __ ideal.
2591 IdealVariable normalized_result(ideal);
2592 __ declarations_done();
2593 __ set(normalized_result, p);
2594 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2595 __ set(normalized_result, ideal.ConI(1));
2596 ideal.end_if();
2597 final_sync(ideal);
2598 p = __ value(normalized_result);
2599 #undef __
2603 p = gvn().transform(new CastP2XNode(nullptr, p));
2604 p = ConvX2UL(p);
2605 }
2606 // The load node has the control of the preceding MemBarCPUOrder. All
2607 // following nodes will have the control of the MemBarCPUOrder inserted at
2608 // the end of this method. So, pushing the load onto the stack at a later
2609 // point is fine.
2610 set_result(p);
2611 } else {
2612 if (bt == T_ADDRESS) {
2613 // Repackage the long as a pointer.
2614 val = ConvL2X(val);
2615 val = gvn().transform(new CastX2PNode(val));
2616 }
2617 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2618 }
2619
2620 return true;
2621 }
2622
2623 //----------------------------inline_unsafe_load_store----------------------------
2624 // This method serves a couple of different customers (depending on LoadStoreKind):
2625 //
2626 // LS_cmp_swap:
2627 //
2628 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2629 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2630 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2631 //
2632 // LS_cmp_swap_weak:
2633 //
2634 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2635 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2636 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2637 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2638 //
2639 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2640 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2641 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2642 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
2805 }
2806 case LS_cmp_swap:
2807 case LS_cmp_swap_weak:
2808 case LS_get_add:
2809 break;
2810 default:
2811 ShouldNotReachHere();
2812 }
2813
2814 // Null check receiver.
2815 receiver = null_check(receiver);
2816 if (stopped()) {
2817 return true;
2818 }
2819
2820 int alias_idx = C->get_alias_index(adr_type);
2821
2822 if (is_reference_type(type)) {
2823 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2824
2825 // Transformation of a value which could be null pointer (CastPP #null)
2826 // could be delayed during Parse (for example, in adjust_map_after_if()).
2827 // Execute transformation here to avoid barrier generation in such case.
2828 if (_gvn.type(newval) == TypePtr::NULL_PTR)
2829 newval = _gvn.makecon(TypePtr::NULL_PTR);
2830
2831 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2832 // Refine the value to a null constant, when it is known to be null
2833 oldval = _gvn.makecon(TypePtr::NULL_PTR);
2834 }
2835 }
2836
2837 Node* result = nullptr;
2838 switch (kind) {
2839 case LS_cmp_exchange: {
2840 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2841 oldval, newval, value_type, type, decorators);
2842 break;
2843 }
2844 case LS_cmp_swap_weak:
2873 insert_mem_bar(Op_MemBarCPUOrder);
2874 switch(id) {
2875 case vmIntrinsics::_loadFence:
2876 insert_mem_bar(Op_LoadFence);
2877 return true;
2878 case vmIntrinsics::_storeFence:
2879 insert_mem_bar(Op_StoreFence);
2880 return true;
2881 case vmIntrinsics::_storeStoreFence:
2882 insert_mem_bar(Op_StoreStoreFence);
2883 return true;
2884 case vmIntrinsics::_fullFence:
2885 insert_mem_bar(Op_MemBarVolatile);
2886 return true;
2887 default:
2888 fatal_unexpected_iid(id);
2889 return false;
2890 }
2891 }
2892
2893 bool LibraryCallKit::inline_onspinwait() {
2894 insert_mem_bar(Op_OnSpinWait);
2895 return true;
2896 }
2897
2898 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
2899 if (!kls->is_Con()) {
2900 return true;
2901 }
2902 const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
2903 if (klsptr == nullptr) {
2904 return true;
2905 }
2906 ciInstanceKlass* ik = klsptr->instance_klass();
2907 // don't need a guard for a klass that is already initialized
2908 return !ik->is_initialized();
2909 }
2910
2911 //----------------------------inline_unsafe_writeback0-------------------------
2912 // public native void Unsafe.writeback0(long address)
2991 Deoptimization::Action_make_not_entrant);
2992 }
2993 if (stopped()) {
2994 return true;
2995 }
2996 #endif //INCLUDE_JVMTI
2997
2998 Node* test = nullptr;
2999 if (LibraryCallKit::klass_needs_init_guard(kls)) {
3000 // Note: The argument might still be an illegal value like
3001 // Serializable.class or Object[].class. The runtime will handle it.
3002 // But we must make an explicit check for initialization.
3003 Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3004 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3005 // can generate code to load it as unsigned byte.
3006 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3007 Node* bits = intcon(InstanceKlass::fully_initialized);
3008 test = _gvn.transform(new SubINode(inst, bits));
3009 // The 'test' is non-zero if we need to take a slow path.
3010 }
3011
3012 Node* obj = new_instance(kls, test);
3013 set_result(obj);
3014 return true;
3015 }
3016
3017 //------------------------inline_native_time_funcs--------------
3018 // inline code for System.currentTimeMillis() and System.nanoTime()
3019 // these have the same type and signature
3020 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3021 const TypeFunc* tf = OptoRuntime::void_long_Type();
3022 const TypePtr* no_memory_effects = nullptr;
3023 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3024 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3025 #ifdef ASSERT
3026 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3027 assert(value_top == top(), "second value must be top");
3028 #endif
3029 set_result(value);
3030 return true;
3031 }
3032
3807 Node* thread = _gvn.transform(new ThreadLocalNode());
3808 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
3809 Node* thread_obj_handle
3810 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3811 thread_obj_handle = _gvn.transform(thread_obj_handle);
3812 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3813 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3814
3815 // Change the _monitor_owner_id of the JavaThread
3816 Node* tid = load_field_from_object(arr, "tid", "J");
3817 Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3818 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3819
3820 JFR_ONLY(extend_setCurrentThread(thread, arr);)
3821 return true;
3822 }
3823
3824 const Type* LibraryCallKit::scopedValueCache_type() {
3825 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3826 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3827 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS);
3828
3829 // Because we create the scopedValue cache lazily we have to make the
3830 // type of the result BotPTR.
3831 bool xk = etype->klass_is_exact();
3832 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, 0);
3833 return objects_type;
3834 }
3835
3836 Node* LibraryCallKit::scopedValueCache_helper() {
3837 Node* thread = _gvn.transform(new ThreadLocalNode());
3838 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
3839 // We cannot use immutable_memory() because we might flip onto a
3840 // different carrier thread, at which point we'll need to use that
3841 // carrier thread's cache.
3842 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3843 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3844 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3845 }
3846
3847 //------------------------inline_native_scopedValueCache------------------
3848 bool LibraryCallKit::inline_native_scopedValueCache() {
3849 Node* cache_obj_handle = scopedValueCache_helper();
3850 const Type* objects_type = scopedValueCache_type();
3851 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3852
3988 }
3989 return kls;
3990 }
3991
3992 //--------------------(inline_native_Class_query helpers)---------------------
3993 // Use this for JVM_ACC_INTERFACE.
3994 // Fall through if (mods & mask) == bits, take the guard otherwise.
3995 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
3996 ByteSize offset, const Type* type, BasicType bt) {
3997 // Branch around if the given klass has the given modifier bit set.
3998 // Like generate_guard, adds a new path onto the region.
3999 Node* modp = basic_plus_adr(kls, in_bytes(offset));
4000 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4001 Node* mask = intcon(modifier_mask);
4002 Node* bits = intcon(modifier_bits);
4003 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4004 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4005 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4006 return generate_fair_guard(bol, region);
4007 }
4008 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4009 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4010 InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4011 }
4012
4013 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4014 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4015 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4016 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4017 }
4018
4019 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4020 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4021 }
4022
4023 //-------------------------inline_native_Class_query-------------------
4024 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4025 const Type* return_type = TypeInt::BOOL;
4026 Node* prim_return_value = top(); // what happens if it's a primitive class?
4027 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4113
4114
4115 case vmIntrinsics::_getSuperclass:
4116 // The rules here are somewhat unfortunate, but we can still do better
4117 // with random logic than with a JNI call.
4118 // Interfaces store null or Object as _super, but must report null.
4119 // Arrays store an intermediate super as _super, but must report Object.
4120 // Other types can report the actual _super.
4121 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4122 if (generate_array_guard(kls, region) != nullptr) {
4123 // A guard was added. If the guard is taken, it was an array.
4124 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4125 }
4126 // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4127 // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4128 if (generate_interface_guard(kls, region) != nullptr) {
4129 // A guard was added. If the guard is taken, it was an interface.
4130 phi->add_req(null());
4131 }
4132 // If we fall through, it's a plain class. Get its _super.
4133 p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4134 kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4135 null_ctl = top();
4136 kls = null_check_oop(kls, &null_ctl);
4137 if (null_ctl != top()) {
4138 // If the guard is taken, Object.superClass is null (both klass and mirror).
4139 region->add_req(null_ctl);
4140 phi ->add_req(null());
4141 }
4142 if (!stopped()) {
4143 query_value = load_mirror_from_klass(kls);
4144 }
4145 break;
4146
4147 default:
4148 fatal_unexpected_iid(id);
4149 break;
4150 }
4151
4152 // Fall-through is the normal case of a query to a real class.
4153 phi->init_req(1, query_value);
4154 region->init_req(1, control());
4155
4156 C->set_has_split_ifs(true); // Has chance for split-if optimization
4157 set_result(region, phi);
4158 return true;
4159 }
4160
4161 //-------------------------inline_Class_cast-------------------
4162 bool LibraryCallKit::inline_Class_cast() {
4163 Node* mirror = argument(0); // Class
4164 Node* obj = argument(1);
4165 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4166 if (mirror_con == nullptr) {
4167 return false; // dead path (mirror->is_top()).
4168 }
4169 if (obj == nullptr || obj->is_top()) {
4170 return false; // dead path
4171 }
4172 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4173
4174 // First, see if Class.cast() can be folded statically.
4175 // java_mirror_type() returns non-null for compile-time Class constants.
4176 ciType* tm = mirror_con->java_mirror_type();
4177 if (tm != nullptr && tm->is_klass() &&
4178 tp != nullptr) {
4179 if (!tp->is_loaded()) {
4180 // Don't use intrinsic when class is not loaded.
4181 return false;
4182 } else {
4183 int static_res = C->static_subtype_check(TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces), tp->as_klass_type());
4184 if (static_res == Compile::SSC_always_true) {
4185 // isInstance() is true - fold the code.
4186 set_result(obj);
4187 return true;
4188 } else if (static_res == Compile::SSC_always_false) {
4189 // Don't use intrinsic, have to throw ClassCastException.
4190 // If the reference is null, the non-intrinsic bytecode will
4191 // be optimized appropriately.
4192 return false;
4193 }
4194 }
4195 }
4196
4197 // Bailout intrinsic and do normal inlining if exception path is frequent.
4198 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4199 return false;
4200 }
4201
4202 // Generate dynamic checks.
4203 // Class.cast() is java implementation of _checkcast bytecode.
4204 // Do checkcast (Parse::do_checkcast()) optimizations here.
4205
4206 mirror = null_check(mirror);
4207 // If mirror is dead, only null-path is taken.
4208 if (stopped()) {
4209 return true;
4210 }
4211
4212 // Not-subtype or the mirror's klass ptr is null (in case it is a primitive).
4213 enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
4214 RegionNode* region = new RegionNode(PATH_LIMIT);
4215 record_for_igvn(region);
4216
4217 // Now load the mirror's klass metaobject, and null-check it.
4218 // If kls is null, we have a primitive mirror and
4219 // nothing is an instance of a primitive type.
4220 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4221
4222 Node* res = top();
4223 if (!stopped()) {
4224 Node* bad_type_ctrl = top();
4225 // Do checkcast optimizations.
4226 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4227 region->init_req(_bad_type_path, bad_type_ctrl);
4228 }
4229 if (region->in(_prim_path) != top() ||
4230 region->in(_bad_type_path) != top()) {
4231 // Let Interpreter throw ClassCastException.
4232 PreserveJVMState pjvms(this);
4233 set_control(_gvn.transform(region));
4234 uncommon_trap(Deoptimization::Reason_intrinsic,
4235 Deoptimization::Action_maybe_recompile);
4236 }
4237 if (!stopped()) {
4238 set_result(res);
4239 }
4240 return true;
4241 }
4242
4243
4244 //--------------------------inline_native_subtype_check------------------------
4245 // This intrinsic takes the JNI calls out of the heart of
4246 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4247 bool LibraryCallKit::inline_native_subtype_check() {
4248 // Pull both arguments off the stack.
4249 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4250 args[0] = argument(0);
4251 args[1] = argument(1);
4252 Node* klasses[2]; // corresponding Klasses: superk, subk
4253 klasses[0] = klasses[1] = top();
4254
4255 enum {
4256 // A full decision tree on {superc is prim, subc is prim}:
4257 _prim_0_path = 1, // {P,N} => false
4258 // {P,P} & superc!=subc => false
4259 _prim_same_path, // {P,P} & superc==subc => true
4260 _prim_1_path, // {N,P} => false
4261 _ref_subtype_path, // {N,N} & subtype check wins => true
4262 _both_ref_path, // {N,N} & subtype check loses => false
4263 PATH_LIMIT
4264 };
4265
4266 RegionNode* region = new RegionNode(PATH_LIMIT);
4267 Node* phi = new PhiNode(region, TypeInt::BOOL);
4268 record_for_igvn(region);
4269
4270 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4271 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4272 int class_klass_offset = java_lang_Class::klass_offset();
4273
4274 // First null-check both mirrors and load each mirror's klass metaobject.
4275 int which_arg;
4276 for (which_arg = 0; which_arg <= 1; which_arg++) {
4277 Node* arg = args[which_arg];
4278 arg = null_check(arg);
4279 if (stopped()) break;
4280 args[which_arg] = arg;
4281
4282 Node* p = basic_plus_adr(arg, class_klass_offset);
4283 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4284 klasses[which_arg] = _gvn.transform(kls);
4285 }
4286
4287 // Having loaded both klasses, test each for null.
4288 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4289 for (which_arg = 0; which_arg <= 1; which_arg++) {
4290 Node* kls = klasses[which_arg];
4291 Node* null_ctl = top();
4292 kls = null_check_oop(kls, &null_ctl, never_see_null);
4293 int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
4294 region->init_req(prim_path, null_ctl);
4295 if (stopped()) break;
4296 klasses[which_arg] = kls;
4297 }
4298
4299 if (!stopped()) {
4300 // now we have two reference types, in klasses[0..1]
4301 Node* subk = klasses[1]; // the argument to isAssignableFrom
4302 Node* superk = klasses[0]; // the receiver
4303 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4304 // now we have a successful reference subtype check
4305 region->set_req(_ref_subtype_path, control());
4306 }
4307
4308 // If both operands are primitive (both klasses null), then
4309 // we must return true when they are identical primitives.
4310 // It is convenient to test this after the first null klass check.
4311 set_control(region->in(_prim_0_path)); // go back to first null check
4312 if (!stopped()) {
4313 // Since superc is primitive, make a guard for the superc==subc case.
4314 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4315 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4316 generate_guard(bol_eq, region, PROB_FAIR);
4317 if (region->req() == PATH_LIMIT+1) {
4318 // A guard was added. If the added guard is taken, superc==subc.
4319 region->swap_edges(PATH_LIMIT, _prim_same_path);
4320 region->del_req(PATH_LIMIT);
4321 }
4322 region->set_req(_prim_0_path, control()); // Not equal after all.
4323 }
4324
4325 // these are the only paths that produce 'true':
4326 phi->set_req(_prim_same_path, intcon(1));
4327 phi->set_req(_ref_subtype_path, intcon(1));
4328
4329 // pull together the cases:
4330 assert(region->req() == PATH_LIMIT, "sane region");
4331 for (uint i = 1; i < region->req(); i++) {
4332 Node* ctl = region->in(i);
4333 if (ctl == nullptr || ctl == top()) {
4334 region->set_req(i, top());
4335 phi ->set_req(i, top());
4336 } else if (phi->in(i) == nullptr) {
4337 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4338 }
4339 }
4340
4341 set_control(_gvn.transform(region));
4342 set_result(_gvn.transform(phi));
4343 return true;
4344 }
4345
4346 //---------------------generate_array_guard_common------------------------
4347 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
4348 bool obj_array, bool not_array, Node** obj) {
4349
4350 if (stopped()) {
4351 return nullptr;
4352 }
4353
4354 // If obj_array/non_array==false/false:
4355 // Branch around if the given klass is in fact an array (either obj or prim).
4356 // If obj_array/non_array==false/true:
4357 // Branch around if the given klass is not an array klass of any kind.
4358 // If obj_array/non_array==true/true:
4359 // Branch around if the kls is not an oop array (kls is int[], String, etc.)
4360 // If obj_array/non_array==true/false:
4361 // Branch around if the kls is an oop array (Object[] or subtype)
4362 //
4363 // Like generate_guard, adds a new path onto the region.
4364 jint layout_con = 0;
4365 Node* layout_val = get_layout_helper(kls, layout_con);
4366 if (layout_val == nullptr) {
4367 bool query = (obj_array
4368 ? Klass::layout_helper_is_objArray(layout_con)
4369 : Klass::layout_helper_is_array(layout_con));
4370 if (query == not_array) {
4371 return nullptr; // never a branch
4372 } else { // always a branch
4373 Node* always_branch = control();
4374 if (region != nullptr)
4375 region->add_req(always_branch);
4376 set_control(top());
4377 return always_branch;
4378 }
4379 }
4380 // Now test the correct condition.
4381 jint nval = (obj_array
4382 ? (jint)(Klass::_lh_array_tag_type_value
4383 << Klass::_lh_array_tag_shift)
4384 : Klass::_lh_neutral_value);
4385 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4386 BoolTest::mask btest = BoolTest::lt; // correct for testing is_[obj]array
4387 // invert the test if we are looking for a non-array
4388 if (not_array) btest = BoolTest(btest).negate();
4389 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4390 Node* ctrl = generate_fair_guard(bol, region);
4391 Node* is_array_ctrl = not_array ? control() : ctrl;
4392 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4393 // Keep track of the fact that 'obj' is an array to prevent
4394 // array specific accesses from floating above the guard.
4395 *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4396 }
4397 return ctrl;
4398 }
4399
4400
4401 //-----------------------inline_native_newArray--------------------------
4402 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
4403 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4404 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4405 Node* mirror;
4406 Node* count_val;
4407 if (uninitialized) {
4408 null_check_receiver();
4409 mirror = argument(1);
4410 count_val = argument(2);
4411 } else {
4412 mirror = argument(0);
4413 count_val = argument(1);
4414 }
4415
4416 mirror = null_check(mirror);
4417 // If mirror or obj is dead, only null-path is taken.
4418 if (stopped()) return true;
4419
4420 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4421 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4422 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4440 CallJavaNode* slow_call = nullptr;
4441 if (uninitialized) {
4442 // Generate optimized virtual call (holder class 'Unsafe' is final)
4443 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4444 } else {
4445 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4446 }
4447 Node* slow_result = set_results_for_java_call(slow_call);
4448 // this->control() comes from set_results_for_java_call
4449 result_reg->set_req(_slow_path, control());
4450 result_val->set_req(_slow_path, slow_result);
4451 result_io ->set_req(_slow_path, i_o());
4452 result_mem->set_req(_slow_path, reset_memory());
4453 }
4454
4455 set_control(normal_ctl);
4456 if (!stopped()) {
4457 // Normal case: The array type has been cached in the java.lang.Class.
4458 // The following call works fine even if the array type is polymorphic.
4459 // It could be a dynamic mix of int[], boolean[], Object[], etc.
4460 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
4461 result_reg->init_req(_normal_path, control());
4462 result_val->init_req(_normal_path, obj);
4463 result_io ->init_req(_normal_path, i_o());
4464 result_mem->init_req(_normal_path, reset_memory());
4465
4466 if (uninitialized) {
4467 // Mark the allocation so that zeroing is skipped
4468 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4469 alloc->maybe_set_complete(&_gvn);
4470 }
4471 }
4472
4473 // Return the combined state.
4474 set_i_o( _gvn.transform(result_io) );
4475 set_all_memory( _gvn.transform(result_mem));
4476
4477 C->set_has_split_ifs(true); // Has chance for split-if optimization
4478 set_result(result_reg, result_val);
4479 return true;
4528 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4529 { PreserveReexecuteState preexecs(this);
4530 jvms()->set_should_reexecute(true);
4531
4532 array_type_mirror = null_check(array_type_mirror);
4533 original = null_check(original);
4534
4535 // Check if a null path was taken unconditionally.
4536 if (stopped()) return true;
4537
4538 Node* orig_length = load_array_length(original);
4539
4540 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4541 klass_node = null_check(klass_node);
4542
4543 RegionNode* bailout = new RegionNode(1);
4544 record_for_igvn(bailout);
4545
4546 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4547 // Bail out if that is so.
4548 Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
4549 if (not_objArray != nullptr) {
4550 // Improve the klass node's type from the new optimistic assumption:
4551 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4552 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
4553 Node* cast = new CastPPNode(control(), klass_node, akls);
4554 klass_node = _gvn.transform(cast);
4555 }
4556
4557 // Bail out if either start or end is negative.
4558 generate_negative_guard(start, bailout, &start);
4559 generate_negative_guard(end, bailout, &end);
4560
4561 Node* length = end;
4562 if (_gvn.type(start) != TypeInt::ZERO) {
4563 length = _gvn.transform(new SubINode(end, start));
4564 }
4565
4566 // Bail out if length is negative (i.e., if start > end).
4567 // Without this the new_array would throw
4568 // NegativeArraySizeException but IllegalArgumentException is what
4569 // should be thrown
4570 generate_negative_guard(length, bailout, &length);
4571
4572 // Bail out if start is larger than the original length
4573 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4574 generate_negative_guard(orig_tail, bailout, &orig_tail);
4575
4576 if (bailout->req() > 1) {
4577 PreserveJVMState pjvms(this);
4578 set_control(_gvn.transform(bailout));
4579 uncommon_trap(Deoptimization::Reason_intrinsic,
4580 Deoptimization::Action_maybe_recompile);
4581 }
4582
4583 if (!stopped()) {
4584 // How many elements will we copy from the original?
4585 // The answer is MinI(orig_tail, length).
4586 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4587
4588 // Generate a direct call to the right arraycopy function(s).
4589 // We know the copy is disjoint but we might not know if the
4590 // oop stores need checking.
4591 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
4597 // to the copyOf to be validated, including that the copy to the
4598 // new array won't trigger an ArrayStoreException. That subtype
4599 // check can be optimized if we know something on the type of
4600 // the input array from type speculation.
4601 if (_gvn.type(klass_node)->singleton()) {
4602 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
4603 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
4604
4605 int test = C->static_subtype_check(superk, subk);
4606 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4607 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4608 if (t_original->speculative_type() != nullptr) {
4609 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4610 }
4611 }
4612 }
4613
4614 bool validated = false;
4615 // Reason_class_check rather than Reason_intrinsic because we
4616 // want to intrinsify even if this traps.
4617 if (!too_many_traps(Deoptimization::Reason_class_check)) {
4618 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4619
4620 if (not_subtype_ctrl != top()) {
4621 PreserveJVMState pjvms(this);
4622 set_control(not_subtype_ctrl);
4623 uncommon_trap(Deoptimization::Reason_class_check,
4624 Deoptimization::Action_make_not_entrant);
4625 assert(stopped(), "Should be stopped");
4626 }
4627 validated = true;
4628 }
4629
4630 if (!stopped()) {
4631 newcopy = new_array(klass_node, length, 0); // no arguments to push
4632
4633 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4634 load_object_klass(original), klass_node);
4635 if (!is_copyOfRange) {
4636 ac->set_copyof(validated);
4637 } else {
4638 ac->set_copyofrange(validated);
4639 }
4640 Node* n = _gvn.transform(ac);
4641 if (n == ac) {
4642 ac->connect_outputs(this);
4643 } else {
4644 assert(validated, "shouldn't transform if all arguments not validated");
4645 set_all_memory(n);
4646 }
4647 }
4648 }
4649 } // original reexecute is set back here
4650
4651 C->set_has_split_ifs(true); // Has chance for split-if optimization
4683
4684 //-----------------------generate_method_call----------------------------
4685 // Use generate_method_call to make a slow-call to the real
4686 // method if the fast path fails. An alternative would be to
4687 // use a stub like OptoRuntime::slow_arraycopy_Java.
4688 // This only works for expanding the current library call,
4689 // not another intrinsic. (E.g., don't use this for making an
4690 // arraycopy call inside of the copyOf intrinsic.)
4691 CallJavaNode*
4692 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4693 // When compiling the intrinsic method itself, do not use this technique.
4694 guarantee(callee() != C->method(), "cannot make slow-call to self");
4695
4696 ciMethod* method = callee();
4697 // ensure the JVMS we have will be correct for this call
4698 guarantee(method_id == method->intrinsic_id(), "must match");
4699
4700 const TypeFunc* tf = TypeFunc::make(method);
4701 if (res_not_null) {
4702 assert(tf->return_type() == T_OBJECT, "");
4703 const TypeTuple* range = tf->range();
4704 const Type** fields = TypeTuple::fields(range->cnt());
4705 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4706 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4707 tf = TypeFunc::make(tf->domain(), new_range);
4708 }
4709 CallJavaNode* slow_call;
4710 if (is_static) {
4711 assert(!is_virtual, "");
4712 slow_call = new CallStaticJavaNode(C, tf,
4713 SharedRuntime::get_resolve_static_call_stub(), method);
4714 } else if (is_virtual) {
4715 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4716 int vtable_index = Method::invalid_vtable_index;
4717 if (UseInlineCaches) {
4718 // Suppress the vtable call
4719 } else {
4720 // hashCode and clone are not a miranda methods,
4721 // so the vtable index is fixed.
4722 // No need to use the linkResolver to get it.
4723 vtable_index = method->vtable_index();
4724 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4725 "bad index %d", vtable_index);
4726 }
4727 slow_call = new CallDynamicJavaNode(tf,
4744 set_edges_for_java_call(slow_call);
4745 return slow_call;
4746 }
4747
4748
4749 /**
4750 * Build special case code for calls to hashCode on an object. This call may
4751 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4752 * slightly different code.
4753 */
4754 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4755 assert(is_static == callee()->is_static(), "correct intrinsic selection");
4756 assert(!(is_virtual && is_static), "either virtual, special, or static");
4757
4758 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4759
4760 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4761 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
4762 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
4763 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4764 Node* obj = nullptr;
4765 if (!is_static) {
4766 // Check for hashing null object
4767 obj = null_check_receiver();
4768 if (stopped()) return true; // unconditionally null
4769 result_reg->init_req(_null_path, top());
4770 result_val->init_req(_null_path, top());
4771 } else {
4772 // Do a null check, and return zero if null.
4773 // System.identityHashCode(null) == 0
4774 obj = argument(0);
4775 Node* null_ctl = top();
4776 obj = null_check_oop(obj, &null_ctl);
4777 result_reg->init_req(_null_path, null_ctl);
4778 result_val->init_req(_null_path, _gvn.intcon(0));
4779 }
4780
4781 // Unconditionally null? Then return right away.
4782 if (stopped()) {
4783 set_control( result_reg->in(_null_path));
4784 if (!stopped())
4785 set_result(result_val->in(_null_path));
4786 return true;
4787 }
4788
4789 // We only go to the fast case code if we pass a number of guards. The
4790 // paths which do not pass are accumulated in the slow_region.
4791 RegionNode* slow_region = new RegionNode(1);
4792 record_for_igvn(slow_region);
4793
4794 // If this is a virtual call, we generate a funny guard. We pull out
4795 // the vtable entry corresponding to hashCode() from the target object.
4796 // If the target method which we are calling happens to be the native
4797 // Object hashCode() method, we pass the guard. We do not need this
4798 // guard for non-virtual calls -- the caller is known to be the native
4799 // Object hashCode().
4800 if (is_virtual) {
4801 // After null check, get the object's klass.
4802 Node* obj_klass = load_object_klass(obj);
4803 generate_virtual_guard(obj_klass, slow_region);
4804 }
4805
4806 // Get the header out of the object, use LoadMarkNode when available
4807 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4808 // The control of the load must be null. Otherwise, the load can move before
4809 // the null check after castPP removal.
4810 Node* no_ctrl = nullptr;
4811 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4812
4813 if (!UseObjectMonitorTable) {
4814 // Test the header to see if it is safe to read w.r.t. locking.
4815 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
4816 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4817 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
4818 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
4819 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
4820
4821 generate_slow_guard(test_monitor, slow_region);
4822 }
4823
4824 // Get the hash value and check to see that it has been properly assigned.
4825 // We depend on hash_mask being at most 32 bits and avoid the use of
4826 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4827 // vm: see markWord.hpp.
4828 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
4829 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
4830 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4831 // This hack lets the hash bits live anywhere in the mark object now, as long
4832 // as the shift drops the relevant bits into the low 32 bits. Note that
4833 // Java spec says that HashCode is an int so there's no point in capturing
4834 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4862 // this->control() comes from set_results_for_java_call
4863 result_reg->init_req(_slow_path, control());
4864 result_val->init_req(_slow_path, slow_result);
4865 result_io ->set_req(_slow_path, i_o());
4866 result_mem ->set_req(_slow_path, reset_memory());
4867 }
4868
4869 // Return the combined state.
4870 set_i_o( _gvn.transform(result_io) );
4871 set_all_memory( _gvn.transform(result_mem));
4872
4873 set_result(result_reg, result_val);
4874 return true;
4875 }
4876
4877 //---------------------------inline_native_getClass----------------------------
4878 // public final native Class<?> java.lang.Object.getClass();
4879 //
4880 // Build special case code for calls to getClass on an object.
4881 bool LibraryCallKit::inline_native_getClass() {
4882 Node* obj = null_check_receiver();
4883 if (stopped()) return true;
4884 set_result(load_mirror_from_klass(load_object_klass(obj)));
4885 return true;
4886 }
4887
4888 //-----------------inline_native_Reflection_getCallerClass---------------------
4889 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4890 //
4891 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4892 //
4893 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4894 // in that it must skip particular security frames and checks for
4895 // caller sensitive methods.
4896 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4897 #ifndef PRODUCT
4898 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4899 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4900 }
4901 #endif
4902
5284 // not cloneable or finalizer => slow path to out-of-line Object.clone
5285 //
5286 // The general case has two steps, allocation and copying.
5287 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5288 //
5289 // Copying also has two cases, oop arrays and everything else.
5290 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5291 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5292 //
5293 // These steps fold up nicely if and when the cloned object's klass
5294 // can be sharply typed as an object array, a type array, or an instance.
5295 //
5296 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5297 PhiNode* result_val;
5298
5299 // Set the reexecute bit for the interpreter to reexecute
5300 // the bytecode that invokes Object.clone if deoptimization happens.
5301 { PreserveReexecuteState preexecs(this);
5302 jvms()->set_should_reexecute(true);
5303
5304 Node* obj = null_check_receiver();
5305 if (stopped()) return true;
5306
5307 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5308
5309 // If we are going to clone an instance, we need its exact type to
5310 // know the number and types of fields to convert the clone to
5311 // loads/stores. Maybe a speculative type can help us.
5312 if (!obj_type->klass_is_exact() &&
5313 obj_type->speculative_type() != nullptr &&
5314 obj_type->speculative_type()->is_instance_klass()) {
5315 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5316 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5317 !spec_ik->has_injected_fields()) {
5318 if (!obj_type->isa_instptr() ||
5319 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5320 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5321 }
5322 }
5323 }
5324
5325 // Conservatively insert a memory barrier on all memory slices.
5326 // Do not let writes into the original float below the clone.
5327 insert_mem_bar(Op_MemBarCPUOrder);
5328
5329 // paths into result_reg:
5330 enum {
5331 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5332 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5333 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5334 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5335 PATH_LIMIT
5336 };
5337 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5338 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5339 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5340 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5341 record_for_igvn(result_reg);
5342
5343 Node* obj_klass = load_object_klass(obj);
5344 Node* array_obj = obj;
5345 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5346 if (array_ctl != nullptr) {
5347 // It's an array.
5348 PreserveJVMState pjvms(this);
5349 set_control(array_ctl);
5350 Node* obj_length = load_array_length(array_obj);
5351 Node* array_size = nullptr; // Size of the array without object alignment padding.
5352 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5353
5354 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5355 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5356 // If it is an oop array, it requires very special treatment,
5357 // because gc barriers are required when accessing the array.
5358 Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5359 if (is_obja != nullptr) {
5360 PreserveJVMState pjvms2(this);
5361 set_control(is_obja);
5362 // Generate a direct call to the right arraycopy function(s).
5363 // Clones are always tightly coupled.
5364 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5365 ac->set_clone_oop_array();
5366 Node* n = _gvn.transform(ac);
5367 assert(n == ac, "cannot disappear");
5368 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5369
5370 result_reg->init_req(_objArray_path, control());
5371 result_val->init_req(_objArray_path, alloc_obj);
5372 result_i_o ->set_req(_objArray_path, i_o());
5373 result_mem ->set_req(_objArray_path, reset_memory());
5374 }
5375 }
5376 // Otherwise, there are no barriers to worry about.
5377 // (We can dispense with card marks if we know the allocation
5378 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5379 // causes the non-eden paths to take compensating steps to
5380 // simulate a fresh allocation, so that no further
5381 // card marks are required in compiled code to initialize
5382 // the object.)
5383
5384 if (!stopped()) {
5385 copy_to_clone(array_obj, alloc_obj, array_size, true);
5386
5387 // Present the results of the copy.
5388 result_reg->init_req(_array_path, control());
5389 result_val->init_req(_array_path, alloc_obj);
5390 result_i_o ->set_req(_array_path, i_o());
5391 result_mem ->set_req(_array_path, reset_memory());
5392 }
5393 }
5394
5395 // We only go to the instance fast case code if we pass a number of guards.
5396 // The paths which do not pass are accumulated in the slow_region.
5397 RegionNode* slow_region = new RegionNode(1);
5398 record_for_igvn(slow_region);
5399 if (!stopped()) {
5400 // It's an instance (we did array above). Make the slow-path tests.
5401 // If this is a virtual call, we generate a funny guard. We grab
5402 // the vtable entry corresponding to clone() from the target object.
5403 // If the target method which we are calling happens to be the
5404 // Object clone() method, we pass the guard. We do not need this
5405 // guard for non-virtual calls; the caller is known to be the native
5406 // Object clone().
5407 if (is_virtual) {
5408 generate_virtual_guard(obj_klass, slow_region);
5409 }
5410
5411 // The object must be easily cloneable and must not have a finalizer.
5412 // Both of these conditions may be checked in a single test.
5413 // We could optimize the test further, but we don't care.
5414 generate_misc_flags_guard(obj_klass,
5415 // Test both conditions:
5416 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5417 // Must be cloneable but not finalizer:
5418 KlassFlags::_misc_is_cloneable_fast,
5510 set_jvms(sfpt->jvms());
5511 _reexecute_sp = jvms()->sp();
5512
5513 return saved_jvms;
5514 }
5515 }
5516 }
5517 return nullptr;
5518 }
5519
5520 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5521 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5522 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5523 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5524 uint size = alloc->req();
5525 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5526 old_jvms->set_map(sfpt);
5527 for (uint i = 0; i < size; i++) {
5528 sfpt->init_req(i, alloc->in(i));
5529 }
5530 // re-push array length for deoptimization
5531 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
5532 old_jvms->set_sp(old_jvms->sp()+1);
5533 old_jvms->set_monoff(old_jvms->monoff()+1);
5534 old_jvms->set_scloff(old_jvms->scloff()+1);
5535 old_jvms->set_endoff(old_jvms->endoff()+1);
5536 old_jvms->set_should_reexecute(true);
5537
5538 sfpt->set_i_o(map()->i_o());
5539 sfpt->set_memory(map()->memory());
5540 sfpt->set_control(map()->control());
5541 return sfpt;
5542 }
5543
5544 // In case of a deoptimization, we restart execution at the
5545 // allocation, allocating a new array. We would leave an uninitialized
5546 // array in the heap that GCs wouldn't expect. Move the allocation
5547 // after the traps so we don't allocate the array if we
5548 // deoptimize. This is possible because tightly_coupled_allocation()
5549 // guarantees there's no observer of the allocated array at this point
5550 // and the control flow is simple enough.
5551 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5552 int saved_reexecute_sp, uint new_idx) {
5553 if (saved_jvms_before_guards != nullptr && !stopped()) {
5554 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5555
5556 assert(alloc != nullptr, "only with a tightly coupled allocation");
5557 // restore JVM state to the state at the arraycopy
5558 saved_jvms_before_guards->map()->set_control(map()->control());
5559 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5560 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5561 // If we've improved the types of some nodes (null check) while
5562 // emitting the guards, propagate them to the current state
5563 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5564 set_jvms(saved_jvms_before_guards);
5565 _reexecute_sp = saved_reexecute_sp;
5566
5567 // Remove the allocation from above the guards
5568 CallProjections callprojs;
5569 alloc->extract_projections(&callprojs, true);
5570 InitializeNode* init = alloc->initialization();
5571 Node* alloc_mem = alloc->in(TypeFunc::Memory);
5572 C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5573 init->replace_mem_projs_by(alloc_mem, C);
5574
5575 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5576 // the allocation (i.e. is only valid if the allocation succeeds):
5577 // 1) replace CastIINode with AllocateArrayNode's length here
5578 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5579 //
5580 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5581 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5582 Node* init_control = init->proj_out(TypeFunc::Control);
5583 Node* alloc_length = alloc->Ideal_length();
5584 #ifdef ASSERT
5585 Node* prev_cast = nullptr;
5586 #endif
5587 for (uint i = 0; i < init_control->outcnt(); i++) {
5588 Node* init_out = init_control->raw_out(i);
5589 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5590 #ifdef ASSERT
5591 if (prev_cast == nullptr) {
5592 prev_cast = init_out;
5594 if (prev_cast->cmp(*init_out) == false) {
5595 prev_cast->dump();
5596 init_out->dump();
5597 assert(false, "not equal CastIINode");
5598 }
5599 }
5600 #endif
5601 C->gvn_replace_by(init_out, alloc_length);
5602 }
5603 }
5604 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5605
5606 // move the allocation here (after the guards)
5607 _gvn.hash_delete(alloc);
5608 alloc->set_req(TypeFunc::Control, control());
5609 alloc->set_req(TypeFunc::I_O, i_o());
5610 Node *mem = reset_memory();
5611 set_all_memory(mem);
5612 alloc->set_req(TypeFunc::Memory, mem);
5613 set_control(init->proj_out_or_null(TypeFunc::Control));
5614 set_i_o(callprojs.fallthrough_ioproj);
5615
5616 // Update memory as done in GraphKit::set_output_for_allocation()
5617 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5618 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5619 if (ary_type->isa_aryptr() && length_type != nullptr) {
5620 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5621 }
5622 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5623 int elemidx = C->get_alias_index(telemref);
5624 // Need to properly move every memory projection for the Initialize
5625 #ifdef ASSERT
5626 int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
5627 int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
5628 #endif
5629 auto move_proj = [&](ProjNode* proj) {
5630 int alias_idx = C->get_alias_index(proj->adr_type());
5631 assert(alias_idx == Compile::AliasIdxRaw ||
5632 alias_idx == elemidx ||
5633 alias_idx == mark_idx ||
5634 alias_idx == klass_idx, "should be raw memory or array element type");
5944 top_src = src_type->isa_aryptr();
5945 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5946 src_spec = true;
5947 }
5948 if (!has_dest) {
5949 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5950 dest_type = _gvn.type(dest);
5951 top_dest = dest_type->isa_aryptr();
5952 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5953 dest_spec = true;
5954 }
5955 }
5956 }
5957
5958 if (has_src && has_dest && can_emit_guards) {
5959 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
5960 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
5961 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
5962 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
5963
5964 if (src_elem == dest_elem && src_elem == T_OBJECT) {
5965 // If both arrays are object arrays then having the exact types
5966 // for both will remove the need for a subtype check at runtime
5967 // before the call and may make it possible to pick a faster copy
5968 // routine (without a subtype check on every element)
5969 // Do we have the exact type of src?
5970 bool could_have_src = src_spec;
5971 // Do we have the exact type of dest?
5972 bool could_have_dest = dest_spec;
5973 ciKlass* src_k = nullptr;
5974 ciKlass* dest_k = nullptr;
5975 if (!src_spec) {
5976 src_k = src_type->speculative_type_not_null();
5977 if (src_k != nullptr && src_k->is_array_klass()) {
5978 could_have_src = true;
5979 }
5980 }
5981 if (!dest_spec) {
5982 dest_k = dest_type->speculative_type_not_null();
5983 if (dest_k != nullptr && dest_k->is_array_klass()) {
5984 could_have_dest = true;
5985 }
5986 }
5987 if (could_have_src && could_have_dest) {
5988 // If we can have both exact types, emit the missing guards
5989 if (could_have_src && !src_spec) {
5990 src = maybe_cast_profiled_obj(src, src_k, true);
5991 }
5992 if (could_have_dest && !dest_spec) {
5993 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5994 }
5995 }
5996 }
5997 }
5998
5999 ciMethod* trap_method = method();
6000 int trap_bci = bci();
6001 if (saved_jvms_before_guards != nullptr) {
6002 trap_method = alloc->jvms()->method();
6003 trap_bci = alloc->jvms()->bci();
6004 }
6005
6006 bool negative_length_guard_generated = false;
6007
6008 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6009 can_emit_guards &&
6010 !src->is_top() && !dest->is_top()) {
6011 // validate arguments: enables transformation the ArrayCopyNode
6012 validated = true;
6013
6014 RegionNode* slow_region = new RegionNode(1);
6015 record_for_igvn(slow_region);
6016
6017 // (1) src and dest are arrays.
6018 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6019 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6020
6021 // (2) src and dest arrays must have elements of the same BasicType
6022 // done at macro expansion or at Ideal transformation time
6023
6024 // (4) src_offset must not be negative.
6025 generate_negative_guard(src_offset, slow_region);
6026
6027 // (5) dest_offset must not be negative.
6028 generate_negative_guard(dest_offset, slow_region);
6029
6030 // (7) src_offset + length must not exceed length of src.
6031 generate_limit_guard(src_offset, length,
6032 load_array_length(src),
6033 slow_region);
6034
6035 // (8) dest_offset + length must not exceed length of dest.
6036 generate_limit_guard(dest_offset, length,
6037 load_array_length(dest),
6038 slow_region);
6039
6040 // (6) length must not be negative.
6041 // This is also checked in generate_arraycopy() during macro expansion, but
6042 // we also have to check it here for the case where the ArrayCopyNode will
6043 // be eliminated by Escape Analysis.
6044 if (EliminateAllocations) {
6045 generate_negative_guard(length, slow_region);
6046 negative_length_guard_generated = true;
6047 }
6048
6049 // (9) each element of an oop array must be assignable
6050 Node* dest_klass = load_object_klass(dest);
6051 if (src != dest) {
6052 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6053
6054 if (not_subtype_ctrl != top()) {
6055 PreserveJVMState pjvms(this);
6056 set_control(not_subtype_ctrl);
6057 uncommon_trap(Deoptimization::Reason_intrinsic,
6058 Deoptimization::Action_make_not_entrant);
6059 assert(stopped(), "Should be stopped");
6060 }
6061 }
6062 {
6063 PreserveJVMState pjvms(this);
6064 set_control(_gvn.transform(slow_region));
6065 uncommon_trap(Deoptimization::Reason_intrinsic,
6066 Deoptimization::Action_make_not_entrant);
6067 assert(stopped(), "Should be stopped");
6068 }
6069
6070 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6071 const Type *toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6072 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6073 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6074 }
6075
6076 if (stopped()) {
6077 return true;
6078 }
6079
6080 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6081 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6082 // so the compiler has a chance to eliminate them: during macro expansion,
6083 // we have to set their control (CastPP nodes are eliminated).
6084 load_object_klass(src), load_object_klass(dest),
6085 load_array_length(src), load_array_length(dest));
6086
6087 ac->set_arraycopy(validated);
6088
6089 Node* n = _gvn.transform(ac);
6090 if (n == ac) {
6091 ac->connect_outputs(this);
6092 } else {
6093 assert(validated, "shouldn't transform if all arguments not validated");
6094 set_all_memory(n);
6095 }
6096 clear_upper_avx();
6097
6098
6099 return true;
6100 }
6101
6102
6103 // Helper function which determines if an arraycopy immediately follows
6104 // an allocation, with no intervening tests or other escapes for the object.
|
1 /*
2 * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "asm/macroAssembler.hpp"
26 #include "ci/ciArrayKlass.hpp"
27 #include "ci/ciFlatArrayKlass.hpp"
28 #include "ci/ciInstanceKlass.hpp"
29 #include "ci/ciSymbols.hpp"
30 #include "ci/ciUtilities.inline.hpp"
31 #include "classfile/vmIntrinsics.hpp"
32 #include "compiler/compileBroker.hpp"
33 #include "compiler/compileLog.hpp"
34 #include "gc/shared/barrierSet.hpp"
35 #include "gc/shared/c2/barrierSetC2.hpp"
36 #include "jfr/support/jfrIntrinsics.hpp"
37 #include "memory/resourceArea.hpp"
38 #include "oops/accessDecorators.hpp"
39 #include "oops/klass.inline.hpp"
40 #include "oops/layoutKind.hpp"
41 #include "oops/objArrayKlass.hpp"
42 #include "opto/addnode.hpp"
43 #include "opto/arraycopynode.hpp"
44 #include "opto/c2compiler.hpp"
45 #include "opto/castnode.hpp"
46 #include "opto/cfgnode.hpp"
47 #include "opto/convertnode.hpp"
48 #include "opto/countbitsnode.hpp"
49 #include "opto/graphKit.hpp"
50 #include "opto/idealKit.hpp"
51 #include "opto/inlinetypenode.hpp"
52 #include "opto/library_call.hpp"
53 #include "opto/mathexactnode.hpp"
54 #include "opto/mulnode.hpp"
55 #include "opto/narrowptrnode.hpp"
56 #include "opto/opaquenode.hpp"
57 #include "opto/opcodes.hpp"
58 #include "opto/parse.hpp"
59 #include "opto/rootnode.hpp"
60 #include "opto/runtime.hpp"
61 #include "opto/subnode.hpp"
62 #include "opto/type.hpp"
63 #include "opto/vectornode.hpp"
64 #include "prims/jvmtiExport.hpp"
65 #include "prims/jvmtiThreadState.hpp"
66 #include "prims/unsafe.hpp"
67 #include "runtime/globals.hpp"
68 #include "runtime/jniHandles.inline.hpp"
69 #include "runtime/mountUnmountDisabler.hpp"
70 #include "runtime/objectMonitor.hpp"
71 #include "runtime/sharedRuntime.hpp"
72 #include "runtime/stubRoutines.hpp"
73 #include "utilities/globalDefinitions.hpp"
74 #include "utilities/macros.hpp"
75 #include "utilities/powerOfTwo.hpp"
76
77 //---------------------------make_vm_intrinsic----------------------------
78 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
79 vmIntrinsicID id = m->intrinsic_id();
80 assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
81
82 if (!m->is_loaded()) {
83 // Do not attempt to inline unloaded methods.
84 return nullptr;
85 }
86
87 C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
88 bool is_available = false;
89
90 {
91 // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
92 // the compiler must transition to '_thread_in_vm' state because both
93 // methods access VM-internal data.
404 case vmIntrinsics::_getReferenceOpaque: return inline_unsafe_access(!is_store, T_OBJECT, Opaque, false);
405 case vmIntrinsics::_getBooleanOpaque: return inline_unsafe_access(!is_store, T_BOOLEAN, Opaque, false);
406 case vmIntrinsics::_getByteOpaque: return inline_unsafe_access(!is_store, T_BYTE, Opaque, false);
407 case vmIntrinsics::_getShortOpaque: return inline_unsafe_access(!is_store, T_SHORT, Opaque, false);
408 case vmIntrinsics::_getCharOpaque: return inline_unsafe_access(!is_store, T_CHAR, Opaque, false);
409 case vmIntrinsics::_getIntOpaque: return inline_unsafe_access(!is_store, T_INT, Opaque, false);
410 case vmIntrinsics::_getLongOpaque: return inline_unsafe_access(!is_store, T_LONG, Opaque, false);
411 case vmIntrinsics::_getFloatOpaque: return inline_unsafe_access(!is_store, T_FLOAT, Opaque, false);
412 case vmIntrinsics::_getDoubleOpaque: return inline_unsafe_access(!is_store, T_DOUBLE, Opaque, false);
413
414 case vmIntrinsics::_putReferenceOpaque: return inline_unsafe_access( is_store, T_OBJECT, Opaque, false);
415 case vmIntrinsics::_putBooleanOpaque: return inline_unsafe_access( is_store, T_BOOLEAN, Opaque, false);
416 case vmIntrinsics::_putByteOpaque: return inline_unsafe_access( is_store, T_BYTE, Opaque, false);
417 case vmIntrinsics::_putShortOpaque: return inline_unsafe_access( is_store, T_SHORT, Opaque, false);
418 case vmIntrinsics::_putCharOpaque: return inline_unsafe_access( is_store, T_CHAR, Opaque, false);
419 case vmIntrinsics::_putIntOpaque: return inline_unsafe_access( is_store, T_INT, Opaque, false);
420 case vmIntrinsics::_putLongOpaque: return inline_unsafe_access( is_store, T_LONG, Opaque, false);
421 case vmIntrinsics::_putFloatOpaque: return inline_unsafe_access( is_store, T_FLOAT, Opaque, false);
422 case vmIntrinsics::_putDoubleOpaque: return inline_unsafe_access( is_store, T_DOUBLE, Opaque, false);
423
424 case vmIntrinsics::_getFlatValue: return inline_unsafe_flat_access(!is_store, Relaxed);
425 case vmIntrinsics::_putFlatValue: return inline_unsafe_flat_access( is_store, Relaxed);
426
427 case vmIntrinsics::_compareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap, Volatile);
428 case vmIntrinsics::_compareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap, Volatile);
429 case vmIntrinsics::_compareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap, Volatile);
430 case vmIntrinsics::_compareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap, Volatile);
431 case vmIntrinsics::_compareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap, Volatile);
432
433 case vmIntrinsics::_weakCompareAndSetReferencePlain: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
434 case vmIntrinsics::_weakCompareAndSetReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
435 case vmIntrinsics::_weakCompareAndSetReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
436 case vmIntrinsics::_weakCompareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
437 case vmIntrinsics::_weakCompareAndSetBytePlain: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Relaxed);
438 case vmIntrinsics::_weakCompareAndSetByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Acquire);
439 case vmIntrinsics::_weakCompareAndSetByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Release);
440 case vmIntrinsics::_weakCompareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Volatile);
441 case vmIntrinsics::_weakCompareAndSetShortPlain: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Relaxed);
442 case vmIntrinsics::_weakCompareAndSetShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Acquire);
443 case vmIntrinsics::_weakCompareAndSetShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Release);
444 case vmIntrinsics::_weakCompareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Volatile);
445 case vmIntrinsics::_weakCompareAndSetIntPlain: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Relaxed);
446 case vmIntrinsics::_weakCompareAndSetIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Acquire);
466 case vmIntrinsics::_compareAndExchangeLong: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Volatile);
467 case vmIntrinsics::_compareAndExchangeLongAcquire: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Acquire);
468 case vmIntrinsics::_compareAndExchangeLongRelease: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Release);
469
470 case vmIntrinsics::_getAndAddByte: return inline_unsafe_load_store(T_BYTE, LS_get_add, Volatile);
471 case vmIntrinsics::_getAndAddShort: return inline_unsafe_load_store(T_SHORT, LS_get_add, Volatile);
472 case vmIntrinsics::_getAndAddInt: return inline_unsafe_load_store(T_INT, LS_get_add, Volatile);
473 case vmIntrinsics::_getAndAddLong: return inline_unsafe_load_store(T_LONG, LS_get_add, Volatile);
474
475 case vmIntrinsics::_getAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_get_set, Volatile);
476 case vmIntrinsics::_getAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_get_set, Volatile);
477 case vmIntrinsics::_getAndSetInt: return inline_unsafe_load_store(T_INT, LS_get_set, Volatile);
478 case vmIntrinsics::_getAndSetLong: return inline_unsafe_load_store(T_LONG, LS_get_set, Volatile);
479 case vmIntrinsics::_getAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_get_set, Volatile);
480
481 case vmIntrinsics::_loadFence:
482 case vmIntrinsics::_storeFence:
483 case vmIntrinsics::_storeStoreFence:
484 case vmIntrinsics::_fullFence: return inline_unsafe_fence(intrinsic_id());
485
486 case vmIntrinsics::_arrayInstanceBaseOffset: return inline_arrayInstanceBaseOffset();
487 case vmIntrinsics::_arrayInstanceIndexScale: return inline_arrayInstanceIndexScale();
488 case vmIntrinsics::_arrayLayout: return inline_arrayLayout();
489 case vmIntrinsics::_getFieldMap: return inline_getFieldMap();
490
491 case vmIntrinsics::_onSpinWait: return inline_onspinwait();
492
493 case vmIntrinsics::_currentCarrierThread: return inline_native_currentCarrierThread();
494 case vmIntrinsics::_currentThread: return inline_native_currentThread();
495 case vmIntrinsics::_setCurrentThread: return inline_native_setCurrentThread();
496
497 case vmIntrinsics::_scopedValueCache: return inline_native_scopedValueCache();
498 case vmIntrinsics::_setScopedValueCache: return inline_native_setScopedValueCache();
499
500 case vmIntrinsics::_Continuation_pin: return inline_native_Continuation_pinning(false);
501 case vmIntrinsics::_Continuation_unpin: return inline_native_Continuation_pinning(true);
502
503 case vmIntrinsics::_vthreadEndFirstTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
504 "endFirstTransition", true);
505 case vmIntrinsics::_vthreadStartFinalTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
506 "startFinalTransition", true);
507 case vmIntrinsics::_vthreadStartTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
508 "startTransition", false);
509 case vmIntrinsics::_vthreadEndTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
510 "endTransition", false);
519 #endif
520 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
521 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
522 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
523 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
524 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
525 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
526 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
527 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
528 case vmIntrinsics::_getLength: return inline_native_getLength();
529 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
530 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
531 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
532 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
533 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
534 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
535 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
536
537 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
538 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
539 case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
540 case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
541 case vmIntrinsics::_newNullableAtomicArray: return inline_newArray(/* null_free */ false, /* atomic */ true);
542 case vmIntrinsics::_isFlatArray: return inline_getArrayProperties(IsFlat);
543 case vmIntrinsics::_isNullRestrictedArray: return inline_getArrayProperties(IsNullRestricted);
544 case vmIntrinsics::_isAtomicArray: return inline_getArrayProperties(IsAtomic);
545
546 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
547
548 case vmIntrinsics::_isInstance:
549 case vmIntrinsics::_isHidden:
550 case vmIntrinsics::_getSuperclass: return inline_native_Class_query(intrinsic_id());
551
552 case vmIntrinsics::_floatToRawIntBits:
553 case vmIntrinsics::_floatToIntBits:
554 case vmIntrinsics::_intBitsToFloat:
555 case vmIntrinsics::_doubleToRawLongBits:
556 case vmIntrinsics::_doubleToLongBits:
557 case vmIntrinsics::_longBitsToDouble:
558 case vmIntrinsics::_floatToFloat16:
559 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
560 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
561 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
562 case vmIntrinsics::_floatIsFinite:
563 case vmIntrinsics::_floatIsInfinite:
564 case vmIntrinsics::_doubleIsFinite:
2329 case vmIntrinsics::_remainderUnsigned_l: {
2330 zero_check_long(argument(2));
2331 // Compile-time detect of null-exception
2332 if (stopped()) {
2333 return true; // keep the graph constructed so far
2334 }
2335 n = new UModLNode(control(), argument(0), argument(2));
2336 break;
2337 }
2338 default: fatal_unexpected_iid(id); break;
2339 }
2340 set_result(_gvn.transform(n));
2341 return true;
2342 }
2343
2344 //----------------------------inline_unsafe_access----------------------------
2345
2346 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2347 // Attempt to infer a sharper value type from the offset and base type.
2348 ciKlass* sharpened_klass = nullptr;
2349 bool null_free = false;
2350
2351 // See if it is an instance field, with an object type.
2352 if (alias_type->field() != nullptr) {
2353 if (alias_type->field()->type()->is_klass()) {
2354 sharpened_klass = alias_type->field()->type()->as_klass();
2355 null_free = alias_type->field()->is_null_free();
2356 }
2357 }
2358
2359 const TypeOopPtr* result = nullptr;
2360 // See if it is a narrow oop array.
2361 if (adr_type->isa_aryptr()) {
2362 if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2363 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2364 null_free = adr_type->is_aryptr()->is_null_free();
2365 if (elem_type != nullptr && elem_type->is_loaded()) {
2366 // Sharpen the value type.
2367 result = elem_type;
2368 }
2369 }
2370 }
2371
2372 // The sharpened class might be unloaded if there is no class loader
2373 // contraint in place.
2374 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2375 // Sharpen the value type.
2376 result = TypeOopPtr::make_from_klass(sharpened_klass);
2377 if (null_free) {
2378 result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2379 }
2380 }
2381 if (result != nullptr) {
2382 #ifndef PRODUCT
2383 if (C->print_intrinsics() || C->print_inlining()) {
2384 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2385 tty->print(" sharpened value: "); result->dump(); tty->cr();
2386 }
2387 #endif
2388 }
2389 return result;
2390 }
2391
2392 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2393 switch (kind) {
2394 case Relaxed:
2395 return MO_UNORDERED;
2396 case Opaque:
2397 return MO_RELAXED;
2398 case Acquire:
2399 return MO_ACQUIRE;
2488 #endif // ASSERT
2489 }
2490 #endif //PRODUCT
2491
2492 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2493
2494 Node* receiver = argument(0); // type: oop
2495
2496 // Build address expression.
2497 Node* heap_base_oop = top();
2498
2499 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2500 Node* base = argument(1); // type: oop
2501 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2502 Node* offset = argument(2); // type: long
2503 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2504 // to be plain byte offsets, which are also the same as those accepted
2505 // by oopDesc::field_addr.
2506 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2507 "fieldOffset must be byte-scaled");
2508
2509 if (base->is_InlineType()) {
2510 assert(!is_store, "InlineTypeNodes are non-larval value objects");
2511 InlineTypeNode* vt = base->as_InlineType();
2512 if (offset->is_Con()) {
2513 long off = find_long_con(offset, 0);
2514 ciInlineKlass* vk = vt->type()->inline_klass();
2515 if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2516 return false;
2517 }
2518
2519 ciField* field = vk->get_non_flat_field_by_offset(off);
2520 if (field != nullptr) {
2521 BasicType bt = type2field[field->type()->basic_type()];
2522 if (bt == T_ARRAY || bt == T_NARROWOOP) {
2523 bt = T_OBJECT;
2524 }
2525 if (bt == type && !field->is_flat()) {
2526 Node* value = vt->field_value_by_offset(off, false);
2527 if (value->is_InlineType()) {
2528 value = value->as_InlineType()->adjust_scalarization_depth(this);
2529 }
2530 set_result(value);
2531 return true;
2532 }
2533 }
2534 }
2535 {
2536 // Re-execute the unsafe access if allocation triggers deoptimization.
2537 PreserveReexecuteState preexecs(this);
2538 jvms()->set_should_reexecute(true);
2539 vt = vt->buffer(this);
2540 }
2541 base = vt->get_oop();
2542 }
2543
2544 // 32-bit machines ignore the high half!
2545 offset = ConvL2X(offset);
2546
2547 // Save state and restore on bailout
2548 SavedState old_state(this);
2549
2550 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2551 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2552
2553 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2554 if (type != T_OBJECT) {
2555 decorators |= IN_NATIVE; // off-heap primitive access
2556 } else {
2557 return false; // off-heap oop accesses are not supported
2558 }
2559 } else {
2560 heap_base_oop = base; // on-heap or mixed access
2561 }
2562
2563 // Can base be null? Otherwise, always on-heap access.
2567 decorators |= IN_HEAP;
2568 }
2569
2570 Node* val = is_store ? argument(4) : nullptr;
2571
2572 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2573 if (adr_type == TypePtr::NULL_PTR) {
2574 return false; // off-heap access with zero address
2575 }
2576
2577 // Try to categorize the address.
2578 Compile::AliasType* alias_type = C->alias_type(adr_type);
2579 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2580
2581 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2582 alias_type->adr_type() == TypeAryPtr::RANGE) {
2583 return false; // not supported
2584 }
2585
2586 bool mismatched = false;
2587 BasicType bt = T_ILLEGAL;
2588 ciField* field = nullptr;
2589 if (adr_type->isa_instptr()) {
2590 const TypeInstPtr* instptr = adr_type->is_instptr();
2591 ciInstanceKlass* k = instptr->instance_klass();
2592 int off = instptr->offset();
2593 if (instptr->const_oop() != nullptr &&
2594 k == ciEnv::current()->Class_klass() &&
2595 instptr->offset() >= (k->size_helper() * wordSize)) {
2596 k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2597 field = k->get_field_by_offset(off, true);
2598 } else {
2599 field = k->get_non_flat_field_by_offset(off);
2600 }
2601 if (field != nullptr) {
2602 bt = type2field[field->type()->basic_type()];
2603 }
2604 if (bt != alias_type->basic_type()) {
2605 // Type mismatch. Is it an access to a nested flat field?
2606 field = k->get_field_by_offset(off, false);
2607 if (field != nullptr) {
2608 bt = type2field[field->type()->basic_type()];
2609 }
2610 }
2611 assert(bt == alias_type->basic_type(), "should match");
2612 } else {
2613 bt = alias_type->basic_type();
2614 }
2615
2616 if (bt != T_ILLEGAL) {
2617 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2618 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2619 // Alias type doesn't differentiate between byte[] and boolean[]).
2620 // Use address type to get the element type.
2621 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2622 }
2623 if (is_reference_type(bt, true)) {
2624 // accessing an array field with getReference is not a mismatch
2625 bt = T_OBJECT;
2626 }
2627 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2628 // Don't intrinsify mismatched object accesses
2629 return false;
2630 }
2631 mismatched = (bt != type);
2632 } else if (alias_type->adr_type()->isa_oopptr()) {
2633 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2634 }
2635
2636 old_state.discard();
2637 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2638
2639 if (mismatched) {
2640 decorators |= C2_MISMATCHED;
2641 }
2642
2643 // First guess at the value type.
2644 const Type *value_type = Type::get_const_basic_type(type);
2645
2646 // Figure out the memory ordering.
2647 decorators |= mo_decorator_for_access_kind(kind);
2648
2649 if (!is_store) {
2650 if (type == T_OBJECT) {
2651 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2652 if (tjp != nullptr) {
2653 value_type = tjp;
2654 }
2655 }
2656 }
2657
2658 receiver = null_check(receiver);
2659 if (stopped()) {
2660 return true;
2661 }
2662 // Heap pointers get a null-check from the interpreter,
2663 // as a courtesy. However, this is not guaranteed by Unsafe,
2664 // and it is not possible to fully distinguish unintended nulls
2665 // from intended ones in this API.
2666
2667 if (!is_store) {
2668 Node* p = nullptr;
2669 // Try to constant fold a load from a constant field
2670
2671 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2672 // final or stable field
2673 p = make_constant_from_field(field, heap_base_oop);
2674 }
2675
2676 if (p == nullptr) { // Could not constant fold the load
2677 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2678 const TypeOopPtr* ptr = value_type->make_oopptr();
2679 if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2680 // Load a non-flattened inline type from memory
2681 p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2682 }
2683 // Normalize the value returned by getBoolean in the following cases
2684 if (type == T_BOOLEAN &&
2685 (mismatched ||
2686 heap_base_oop == top() || // - heap_base_oop is null or
2687 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2688 // and the unsafe access is made to large offset
2689 // (i.e., larger than the maximum offset necessary for any
2690 // field access)
2691 ) {
2692 IdealKit ideal = IdealKit(this);
2693 #define __ ideal.
2694 IdealVariable normalized_result(ideal);
2695 __ declarations_done();
2696 __ set(normalized_result, p);
2697 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2698 __ set(normalized_result, ideal.ConI(1));
2699 ideal.end_if();
2700 final_sync(ideal);
2701 p = __ value(normalized_result);
2702 #undef __
2706 p = gvn().transform(new CastP2XNode(nullptr, p));
2707 p = ConvX2UL(p);
2708 }
2709 // The load node has the control of the preceding MemBarCPUOrder. All
2710 // following nodes will have the control of the MemBarCPUOrder inserted at
2711 // the end of this method. So, pushing the load onto the stack at a later
2712 // point is fine.
2713 set_result(p);
2714 } else {
2715 if (bt == T_ADDRESS) {
2716 // Repackage the long as a pointer.
2717 val = ConvL2X(val);
2718 val = gvn().transform(new CastX2PNode(val));
2719 }
2720 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2721 }
2722
2723 return true;
2724 }
2725
2726 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2727 #ifdef ASSERT
2728 {
2729 ResourceMark rm;
2730 // Check the signatures.
2731 ciSignature* sig = callee()->signature();
2732 assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2733 assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2734 assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2735 assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2736 if (is_store) {
2737 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2738 assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2739 assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2740 } else {
2741 assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2742 assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2743 }
2744 }
2745 #endif // ASSERT
2746
2747 assert(kind == Relaxed, "Only plain accesses for now");
2748 if (callee()->is_static()) {
2749 // caller must have the capability!
2750 return false;
2751 }
2752 C->set_has_unsafe_access(true);
2753
2754 const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2755 if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2756 // parameter valueType is not a constant
2757 return false;
2758 }
2759 ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2760 if (!mirror_type->is_inlinetype()) {
2761 // Dead code
2762 return false;
2763 }
2764 ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2765
2766 const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2767 if (layout_type == nullptr || !layout_type->is_con()) {
2768 // parameter layoutKind is not a constant
2769 return false;
2770 }
2771 assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2772 layout_type->get_con() <= static_cast<int>(LayoutKind::UNKNOWN),
2773 "invalid layoutKind %d", layout_type->get_con());
2774 LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2775 assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2776 layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2777 "unexpected layoutKind %d", layout_type->get_con());
2778
2779 null_check(argument(0));
2780 if (stopped()) {
2781 return true;
2782 }
2783
2784 Node* base = must_be_not_null(argument(1), true);
2785 Node* offset = argument(2);
2786 const Type* base_type = _gvn.type(base);
2787
2788 Node* ptr;
2789 bool immutable_memory = false;
2790 DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2791 if (base_type->isa_instptr()) {
2792 const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2793 if (offset_type == nullptr || !offset_type->is_con()) {
2794 // Offset into a non-array should be a constant
2795 decorators |= C2_MISMATCHED;
2796 } else {
2797 int offset_con = checked_cast<int>(offset_type->get_con());
2798 ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2799 ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2800 if (field == nullptr) {
2801 assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2802 decorators |= C2_MISMATCHED;
2803 } else {
2804 assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2805 offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2806 immutable_memory = field->is_strict() && field->is_final();
2807
2808 if (base->is_InlineType()) {
2809 assert(!is_store, "Cannot store into a non-larval value object");
2810 set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2811 return true;
2812 }
2813 }
2814 }
2815
2816 if (base->is_InlineType()) {
2817 assert(!is_store, "Cannot store into a non-larval value object");
2818 base = base->as_InlineType()->buffer(this, true);
2819 }
2820 ptr = basic_plus_adr(base, ConvL2X(offset));
2821 } else if (base_type->isa_aryptr()) {
2822 decorators |= IS_ARRAY;
2823 if (layout == LayoutKind::REFERENCE) {
2824 if (!base_type->is_aryptr()->is_not_flat()) {
2825 const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2826 Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2827 replace_in_map(base, new_base);
2828 base = new_base;
2829 }
2830 ptr = basic_plus_adr(base, ConvL2X(offset));
2831 } else {
2832 if (UseArrayFlattening) {
2833 // Flat array must have an exact type
2834 bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2835 bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2836 Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2837 replace_in_map(base, new_base);
2838 base = new_base;
2839 ptr = basic_plus_adr(base, ConvL2X(offset));
2840 const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2841 if (ptr_type->field_offset().get() != 0) {
2842 ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2843 }
2844 } else {
2845 uncommon_trap(Deoptimization::Reason_intrinsic,
2846 Deoptimization::Action_none);
2847 return true;
2848 }
2849 }
2850 } else {
2851 decorators |= C2_MISMATCHED;
2852 ptr = basic_plus_adr(base, ConvL2X(offset));
2853 }
2854
2855 if (is_store) {
2856 Node* value = argument(6);
2857 const Type* value_type = _gvn.type(value);
2858 if (!value_type->is_inlinetypeptr()) {
2859 value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2860 Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2861 new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2862 replace_in_map(value, new_value);
2863 value = new_value;
2864 }
2865
2866 assert(value_type->inline_klass() == value_klass, "value is of type %s while valueType is %s", value_type->inline_klass()->name()->as_utf8(), value_klass->name()->as_utf8());
2867 if (layout == LayoutKind::REFERENCE) {
2868 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2869 access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2870 } else {
2871 bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2872 bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2873 value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2874 }
2875
2876 return true;
2877 } else {
2878 decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2879 InlineTypeNode* result;
2880 if (layout == LayoutKind::REFERENCE) {
2881 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2882 Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2883 result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2884 } else {
2885 bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2886 bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2887 result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2888 }
2889
2890 set_result(result);
2891 return true;
2892 }
2893 }
2894
2895 //----------------------------inline_unsafe_load_store----------------------------
2896 // This method serves a couple of different customers (depending on LoadStoreKind):
2897 //
2898 // LS_cmp_swap:
2899 //
2900 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2901 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2902 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2903 //
2904 // LS_cmp_swap_weak:
2905 //
2906 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2907 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2908 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2909 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2910 //
2911 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2912 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2913 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2914 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
3077 }
3078 case LS_cmp_swap:
3079 case LS_cmp_swap_weak:
3080 case LS_get_add:
3081 break;
3082 default:
3083 ShouldNotReachHere();
3084 }
3085
3086 // Null check receiver.
3087 receiver = null_check(receiver);
3088 if (stopped()) {
3089 return true;
3090 }
3091
3092 int alias_idx = C->get_alias_index(adr_type);
3093
3094 if (is_reference_type(type)) {
3095 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3096
3097 if (oldval != nullptr && oldval->is_InlineType()) {
3098 // Re-execute the unsafe access if allocation triggers deoptimization.
3099 PreserveReexecuteState preexecs(this);
3100 jvms()->set_should_reexecute(true);
3101 oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3102 }
3103 if (newval != nullptr && newval->is_InlineType()) {
3104 // Re-execute the unsafe access if allocation triggers deoptimization.
3105 PreserveReexecuteState preexecs(this);
3106 jvms()->set_should_reexecute(true);
3107 newval = newval->as_InlineType()->buffer(this)->get_oop();
3108 }
3109
3110 // Transformation of a value which could be null pointer (CastPP #null)
3111 // could be delayed during Parse (for example, in adjust_map_after_if()).
3112 // Execute transformation here to avoid barrier generation in such case.
3113 if (_gvn.type(newval) == TypePtr::NULL_PTR)
3114 newval = _gvn.makecon(TypePtr::NULL_PTR);
3115
3116 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3117 // Refine the value to a null constant, when it is known to be null
3118 oldval = _gvn.makecon(TypePtr::NULL_PTR);
3119 }
3120 }
3121
3122 Node* result = nullptr;
3123 switch (kind) {
3124 case LS_cmp_exchange: {
3125 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3126 oldval, newval, value_type, type, decorators);
3127 break;
3128 }
3129 case LS_cmp_swap_weak:
3158 insert_mem_bar(Op_MemBarCPUOrder);
3159 switch(id) {
3160 case vmIntrinsics::_loadFence:
3161 insert_mem_bar(Op_LoadFence);
3162 return true;
3163 case vmIntrinsics::_storeFence:
3164 insert_mem_bar(Op_StoreFence);
3165 return true;
3166 case vmIntrinsics::_storeStoreFence:
3167 insert_mem_bar(Op_StoreStoreFence);
3168 return true;
3169 case vmIntrinsics::_fullFence:
3170 insert_mem_bar(Op_MemBarVolatile);
3171 return true;
3172 default:
3173 fatal_unexpected_iid(id);
3174 return false;
3175 }
3176 }
3177
3178 // private native int arrayInstanceBaseOffset0(Object[] array);
3179 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3180 Node* array = argument(1);
3181 Node* klass_node = load_object_klass(array);
3182
3183 jint layout_con = Klass::_lh_neutral_value;
3184 Node* layout_val = get_layout_helper(klass_node, layout_con);
3185 int layout_is_con = (layout_val == nullptr);
3186
3187 Node* header_size = nullptr;
3188 if (layout_is_con) {
3189 int hsize = Klass::layout_helper_header_size(layout_con);
3190 header_size = intcon(hsize);
3191 } else {
3192 Node* hss = intcon(Klass::_lh_header_size_shift);
3193 Node* hsm = intcon(Klass::_lh_header_size_mask);
3194 header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3195 header_size = _gvn.transform(new AndINode(header_size, hsm));
3196 }
3197 set_result(header_size);
3198 return true;
3199 }
3200
3201 // private native int arrayInstanceIndexScale0(Object[] array);
3202 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3203 Node* array = argument(1);
3204 Node* klass_node = load_object_klass(array);
3205
3206 jint layout_con = Klass::_lh_neutral_value;
3207 Node* layout_val = get_layout_helper(klass_node, layout_con);
3208 int layout_is_con = (layout_val == nullptr);
3209
3210 Node* element_size = nullptr;
3211 if (layout_is_con) {
3212 int log_element_size = Klass::layout_helper_log2_element_size(layout_con);
3213 int elem_size = 1 << log_element_size;
3214 element_size = intcon(elem_size);
3215 } else {
3216 Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3217 Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3218 Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3219 log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3220 element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3221 }
3222 set_result(element_size);
3223 return true;
3224 }
3225
3226 // private native int arrayLayout0(Object[] array);
3227 bool LibraryCallKit::inline_arrayLayout() {
3228 RegionNode* region = new RegionNode(2);
3229 Node* phi = new PhiNode(region, TypeInt::POS);
3230
3231 Node* array = argument(1);
3232 Node* klass_node = load_object_klass(array);
3233 generate_refArray_guard(klass_node, region);
3234 if (region->req() == 3) {
3235 phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3236 }
3237
3238 int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3239 Node* layout_kind_addr = basic_plus_adr(klass_node, layout_kind_offset);
3240 Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3241
3242 region->init_req(1, control());
3243 phi->init_req(1, layout_kind);
3244
3245 set_control(_gvn.transform(region));
3246 set_result(_gvn.transform(phi));
3247 return true;
3248 }
3249
3250 // private native int[] getFieldMap0(Class <?> c);
3251 // int offset = c._klass._acmp_maps_offset;
3252 // return (int[])c.obj_field(offset);
3253 bool LibraryCallKit::inline_getFieldMap() {
3254 Node* mirror = argument(1);
3255 Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3256
3257 int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3258 Node* field_map_offset_addr = basic_plus_adr(klass, field_map_offset_offset);
3259 Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3260 field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3261
3262 Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3263 const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3264 // TODO 8350865 Remove this
3265 val_type = val_type->cast_to_not_flat(true)->cast_to_not_null_free(true);
3266 Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3267
3268 set_result(map);
3269 return true;
3270 }
3271
3272 bool LibraryCallKit::inline_onspinwait() {
3273 insert_mem_bar(Op_OnSpinWait);
3274 return true;
3275 }
3276
3277 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3278 if (!kls->is_Con()) {
3279 return true;
3280 }
3281 const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3282 if (klsptr == nullptr) {
3283 return true;
3284 }
3285 ciInstanceKlass* ik = klsptr->instance_klass();
3286 // don't need a guard for a klass that is already initialized
3287 return !ik->is_initialized();
3288 }
3289
3290 //----------------------------inline_unsafe_writeback0-------------------------
3291 // public native void Unsafe.writeback0(long address)
3370 Deoptimization::Action_make_not_entrant);
3371 }
3372 if (stopped()) {
3373 return true;
3374 }
3375 #endif //INCLUDE_JVMTI
3376
3377 Node* test = nullptr;
3378 if (LibraryCallKit::klass_needs_init_guard(kls)) {
3379 // Note: The argument might still be an illegal value like
3380 // Serializable.class or Object[].class. The runtime will handle it.
3381 // But we must make an explicit check for initialization.
3382 Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3383 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3384 // can generate code to load it as unsigned byte.
3385 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3386 Node* bits = intcon(InstanceKlass::fully_initialized);
3387 test = _gvn.transform(new SubINode(inst, bits));
3388 // The 'test' is non-zero if we need to take a slow path.
3389 }
3390 Node* obj = nullptr;
3391 const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3392 if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3393 obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3394 } else {
3395 obj = new_instance(kls, test);
3396 }
3397 set_result(obj);
3398 return true;
3399 }
3400
3401 //------------------------inline_native_time_funcs--------------
3402 // inline code for System.currentTimeMillis() and System.nanoTime()
3403 // these have the same type and signature
3404 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3405 const TypeFunc* tf = OptoRuntime::void_long_Type();
3406 const TypePtr* no_memory_effects = nullptr;
3407 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3408 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3409 #ifdef ASSERT
3410 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3411 assert(value_top == top(), "second value must be top");
3412 #endif
3413 set_result(value);
3414 return true;
3415 }
3416
4191 Node* thread = _gvn.transform(new ThreadLocalNode());
4192 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4193 Node* thread_obj_handle
4194 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4195 thread_obj_handle = _gvn.transform(thread_obj_handle);
4196 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4197 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4198
4199 // Change the _monitor_owner_id of the JavaThread
4200 Node* tid = load_field_from_object(arr, "tid", "J");
4201 Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4202 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4203
4204 JFR_ONLY(extend_setCurrentThread(thread, arr);)
4205 return true;
4206 }
4207
4208 const Type* LibraryCallKit::scopedValueCache_type() {
4209 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4210 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4211 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4212
4213 // Because we create the scopedValue cache lazily we have to make the
4214 // type of the result BotPTR.
4215 bool xk = etype->klass_is_exact();
4216 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4217 return objects_type;
4218 }
4219
4220 Node* LibraryCallKit::scopedValueCache_helper() {
4221 Node* thread = _gvn.transform(new ThreadLocalNode());
4222 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4223 // We cannot use immutable_memory() because we might flip onto a
4224 // different carrier thread, at which point we'll need to use that
4225 // carrier thread's cache.
4226 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4227 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4228 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4229 }
4230
4231 //------------------------inline_native_scopedValueCache------------------
4232 bool LibraryCallKit::inline_native_scopedValueCache() {
4233 Node* cache_obj_handle = scopedValueCache_helper();
4234 const Type* objects_type = scopedValueCache_type();
4235 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4236
4372 }
4373 return kls;
4374 }
4375
4376 //--------------------(inline_native_Class_query helpers)---------------------
4377 // Use this for JVM_ACC_INTERFACE.
4378 // Fall through if (mods & mask) == bits, take the guard otherwise.
4379 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4380 ByteSize offset, const Type* type, BasicType bt) {
4381 // Branch around if the given klass has the given modifier bit set.
4382 // Like generate_guard, adds a new path onto the region.
4383 Node* modp = basic_plus_adr(kls, in_bytes(offset));
4384 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4385 Node* mask = intcon(modifier_mask);
4386 Node* bits = intcon(modifier_bits);
4387 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4388 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4389 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4390 return generate_fair_guard(bol, region);
4391 }
4392
4393 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4394 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4395 InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4396 }
4397
4398 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4399 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4400 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4401 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4402 }
4403
4404 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4405 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4406 }
4407
4408 //-------------------------inline_native_Class_query-------------------
4409 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4410 const Type* return_type = TypeInt::BOOL;
4411 Node* prim_return_value = top(); // what happens if it's a primitive class?
4412 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4498
4499
4500 case vmIntrinsics::_getSuperclass:
4501 // The rules here are somewhat unfortunate, but we can still do better
4502 // with random logic than with a JNI call.
4503 // Interfaces store null or Object as _super, but must report null.
4504 // Arrays store an intermediate super as _super, but must report Object.
4505 // Other types can report the actual _super.
4506 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4507 if (generate_array_guard(kls, region) != nullptr) {
4508 // A guard was added. If the guard is taken, it was an array.
4509 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4510 }
4511 // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4512 // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4513 if (generate_interface_guard(kls, region) != nullptr) {
4514 // A guard was added. If the guard is taken, it was an interface.
4515 phi->add_req(null());
4516 }
4517 // If we fall through, it's a plain class. Get its _super.
4518 if (!stopped()) {
4519 p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4520 kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4521 null_ctl = top();
4522 kls = null_check_oop(kls, &null_ctl);
4523 if (null_ctl != top()) {
4524 // If the guard is taken, Object.superClass is null (both klass and mirror).
4525 region->add_req(null_ctl);
4526 phi ->add_req(null());
4527 }
4528 if (!stopped()) {
4529 query_value = load_mirror_from_klass(kls);
4530 }
4531 }
4532 break;
4533
4534 default:
4535 fatal_unexpected_iid(id);
4536 break;
4537 }
4538
4539 // Fall-through is the normal case of a query to a real class.
4540 phi->init_req(1, query_value);
4541 region->init_req(1, control());
4542
4543 C->set_has_split_ifs(true); // Has chance for split-if optimization
4544 set_result(region, phi);
4545 return true;
4546 }
4547
4548
4549 //-------------------------inline_Class_cast-------------------
4550 bool LibraryCallKit::inline_Class_cast() {
4551 Node* mirror = argument(0); // Class
4552 Node* obj = argument(1);
4553 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4554 if (mirror_con == nullptr) {
4555 return false; // dead path (mirror->is_top()).
4556 }
4557 if (obj == nullptr || obj->is_top()) {
4558 return false; // dead path
4559 }
4560 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4561
4562 // First, see if Class.cast() can be folded statically.
4563 // java_mirror_type() returns non-null for compile-time Class constants.
4564 ciType* tm = mirror_con->java_mirror_type();
4565 if (tm != nullptr && tm->is_klass() &&
4566 tp != nullptr) {
4567 if (!tp->is_loaded()) {
4568 // Don't use intrinsic when class is not loaded.
4569 return false;
4570 } else {
4571 const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4572 int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4573 if (static_res == Compile::SSC_always_true) {
4574 // isInstance() is true - fold the code.
4575 set_result(obj);
4576 return true;
4577 } else if (static_res == Compile::SSC_always_false) {
4578 // Don't use intrinsic, have to throw ClassCastException.
4579 // If the reference is null, the non-intrinsic bytecode will
4580 // be optimized appropriately.
4581 return false;
4582 }
4583 }
4584 }
4585
4586 // Bailout intrinsic and do normal inlining if exception path is frequent.
4587 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4588 return false;
4589 }
4590
4591 // Generate dynamic checks.
4592 // Class.cast() is java implementation of _checkcast bytecode.
4593 // Do checkcast (Parse::do_checkcast()) optimizations here.
4594
4595 mirror = null_check(mirror);
4596 // If mirror is dead, only null-path is taken.
4597 if (stopped()) {
4598 return true;
4599 }
4600
4601 // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4602 enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4603 RegionNode* region = new RegionNode(PATH_LIMIT);
4604 record_for_igvn(region);
4605
4606 // Now load the mirror's klass metaobject, and null-check it.
4607 // If kls is null, we have a primitive mirror and
4608 // nothing is an instance of a primitive type.
4609 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4610
4611 Node* res = top();
4612 Node* io = i_o();
4613 Node* mem = merged_memory();
4614 if (!stopped()) {
4615
4616 Node* bad_type_ctrl = top();
4617 // Do checkcast optimizations.
4618 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4619 region->init_req(_bad_type_path, bad_type_ctrl);
4620 }
4621 if (region->in(_prim_path) != top() ||
4622 region->in(_bad_type_path) != top() ||
4623 region->in(_npe_path) != top()) {
4624 // Let Interpreter throw ClassCastException.
4625 PreserveJVMState pjvms(this);
4626 set_control(_gvn.transform(region));
4627 // Set IO and memory because gen_checkcast may override them when buffering inline types
4628 set_i_o(io);
4629 set_all_memory(mem);
4630 uncommon_trap(Deoptimization::Reason_intrinsic,
4631 Deoptimization::Action_maybe_recompile);
4632 }
4633 if (!stopped()) {
4634 set_result(res);
4635 }
4636 return true;
4637 }
4638
4639
4640 //--------------------------inline_native_subtype_check------------------------
4641 // This intrinsic takes the JNI calls out of the heart of
4642 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4643 bool LibraryCallKit::inline_native_subtype_check() {
4644 // Pull both arguments off the stack.
4645 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4646 args[0] = argument(0);
4647 args[1] = argument(1);
4648 Node* klasses[2]; // corresponding Klasses: superk, subk
4649 klasses[0] = klasses[1] = top();
4650
4651 enum {
4652 // A full decision tree on {superc is prim, subc is prim}:
4653 _prim_0_path = 1, // {P,N} => false
4654 // {P,P} & superc!=subc => false
4655 _prim_same_path, // {P,P} & superc==subc => true
4656 _prim_1_path, // {N,P} => false
4657 _ref_subtype_path, // {N,N} & subtype check wins => true
4658 _both_ref_path, // {N,N} & subtype check loses => false
4659 PATH_LIMIT
4660 };
4661
4662 RegionNode* region = new RegionNode(PATH_LIMIT);
4663 RegionNode* prim_region = new RegionNode(2);
4664 Node* phi = new PhiNode(region, TypeInt::BOOL);
4665 record_for_igvn(region);
4666 record_for_igvn(prim_region);
4667
4668 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4669 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4670 int class_klass_offset = java_lang_Class::klass_offset();
4671
4672 // First null-check both mirrors and load each mirror's klass metaobject.
4673 int which_arg;
4674 for (which_arg = 0; which_arg <= 1; which_arg++) {
4675 Node* arg = args[which_arg];
4676 arg = null_check(arg);
4677 if (stopped()) break;
4678 args[which_arg] = arg;
4679
4680 Node* p = basic_plus_adr(arg, class_klass_offset);
4681 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4682 klasses[which_arg] = _gvn.transform(kls);
4683 }
4684
4685 // Having loaded both klasses, test each for null.
4686 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4687 for (which_arg = 0; which_arg <= 1; which_arg++) {
4688 Node* kls = klasses[which_arg];
4689 Node* null_ctl = top();
4690 kls = null_check_oop(kls, &null_ctl, never_see_null);
4691 if (which_arg == 0) {
4692 prim_region->init_req(1, null_ctl);
4693 } else {
4694 region->init_req(_prim_1_path, null_ctl);
4695 }
4696 if (stopped()) break;
4697 klasses[which_arg] = kls;
4698 }
4699
4700 if (!stopped()) {
4701 // now we have two reference types, in klasses[0..1]
4702 Node* subk = klasses[1]; // the argument to isAssignableFrom
4703 Node* superk = klasses[0]; // the receiver
4704 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4705 region->set_req(_ref_subtype_path, control());
4706 }
4707
4708 // If both operands are primitive (both klasses null), then
4709 // we must return true when they are identical primitives.
4710 // It is convenient to test this after the first null klass check.
4711 // This path is also used if superc is a value mirror.
4712 set_control(_gvn.transform(prim_region));
4713 if (!stopped()) {
4714 // Since superc is primitive, make a guard for the superc==subc case.
4715 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4716 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4717 generate_fair_guard(bol_eq, region);
4718 if (region->req() == PATH_LIMIT+1) {
4719 // A guard was added. If the added guard is taken, superc==subc.
4720 region->swap_edges(PATH_LIMIT, _prim_same_path);
4721 region->del_req(PATH_LIMIT);
4722 }
4723 region->set_req(_prim_0_path, control()); // Not equal after all.
4724 }
4725
4726 // these are the only paths that produce 'true':
4727 phi->set_req(_prim_same_path, intcon(1));
4728 phi->set_req(_ref_subtype_path, intcon(1));
4729
4730 // pull together the cases:
4731 assert(region->req() == PATH_LIMIT, "sane region");
4732 for (uint i = 1; i < region->req(); i++) {
4733 Node* ctl = region->in(i);
4734 if (ctl == nullptr || ctl == top()) {
4735 region->set_req(i, top());
4736 phi ->set_req(i, top());
4737 } else if (phi->in(i) == nullptr) {
4738 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4739 }
4740 }
4741
4742 set_control(_gvn.transform(region));
4743 set_result(_gvn.transform(phi));
4744 return true;
4745 }
4746
4747 //---------------------generate_array_guard_common------------------------
4748 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4749
4750 if (stopped()) {
4751 return nullptr;
4752 }
4753
4754 // Like generate_guard, adds a new path onto the region.
4755 jint layout_con = 0;
4756 Node* layout_val = get_layout_helper(kls, layout_con);
4757 if (layout_val == nullptr) {
4758 bool query = 0;
4759 switch(kind) {
4760 case RefArray: query = Klass::layout_helper_is_refArray(layout_con); break;
4761 case NonRefArray: query = !Klass::layout_helper_is_refArray(layout_con); break;
4762 case TypeArray: query = Klass::layout_helper_is_typeArray(layout_con); break;
4763 case AnyArray: query = Klass::layout_helper_is_array(layout_con); break;
4764 case NonArray: query = !Klass::layout_helper_is_array(layout_con); break;
4765 default:
4766 ShouldNotReachHere();
4767 }
4768 if (!query) {
4769 return nullptr; // never a branch
4770 } else { // always a branch
4771 Node* always_branch = control();
4772 if (region != nullptr)
4773 region->add_req(always_branch);
4774 set_control(top());
4775 return always_branch;
4776 }
4777 }
4778 unsigned int value = 0;
4779 BoolTest::mask btest = BoolTest::illegal;
4780 switch(kind) {
4781 case RefArray:
4782 case NonRefArray: {
4783 value = Klass::_lh_array_tag_ref_value;
4784 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4785 btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4786 break;
4787 }
4788 case TypeArray: {
4789 value = Klass::_lh_array_tag_type_value;
4790 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4791 btest = BoolTest::eq;
4792 break;
4793 }
4794 case AnyArray: value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4795 case NonArray: value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4796 default:
4797 ShouldNotReachHere();
4798 }
4799 // Now test the correct condition.
4800 jint nval = (jint)value;
4801 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4802 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4803 Node* ctrl = generate_fair_guard(bol, region);
4804 Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4805 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4806 // Keep track of the fact that 'obj' is an array to prevent
4807 // array specific accesses from floating above the guard.
4808 *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4809 }
4810 return ctrl;
4811 }
4812
4813 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4814 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4815 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4816 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4817 assert(null_free || atomic, "nullable implies atomic");
4818 Node* componentType = argument(0);
4819 Node* length = argument(1);
4820 Node* init_val = null_free ? argument(2) : nullptr;
4821
4822 const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4823 if (tp != nullptr) {
4824 ciInstanceKlass* ik = tp->instance_klass();
4825 if (ik == C->env()->Class_klass()) {
4826 ciType* t = tp->java_mirror_type();
4827 if (t != nullptr && t->is_inlinetype()) {
4828
4829 ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4830 assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4831
4832 // TOOD 8350865 ZGC needs card marks on initializing oop stores
4833 if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4834 return false;
4835 }
4836
4837 if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4838 const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4839 if (null_free) {
4840 if (init_val->is_InlineType()) {
4841 if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4842 // Zeroing is enough because the init value is the all-zero value
4843 init_val = nullptr;
4844 } else {
4845 init_val = init_val->as_InlineType()->buffer(this);
4846 }
4847 }
4848 // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4849 // If we insert a checkcast here, we can be sure that init_val is an InlineTypeNode, so
4850 // when we folded a field load from an allocation (e.g. during escape analysis), we can
4851 // remove the check init_val->is_InlineType().
4852 }
4853 Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4854 const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4855 assert(arytype->is_null_free() == null_free, "inconsistency");
4856 assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4857 set_result(obj);
4858 return true;
4859 }
4860 }
4861 }
4862 }
4863 return false;
4864 }
4865
4866 // public static native boolean ValueClass::isFlatArray(Object array);
4867 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4868 // public static native boolean ValueClass::isAtomicArray(Object array);
4869 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4870 Node* array = argument(0);
4871
4872 Node* bol;
4873 switch(check) {
4874 case IsFlat:
4875 // TODO 8350865 Use the object version here instead of loading the klass
4876 // The problem is that PhaseMacroExpand::expand_flatarraycheck_node can only handle some IR shapes and will fail, for example, if the bol is directly wired to a ReturnNode
4877 bol = flat_array_test(load_object_klass(array));
4878 break;
4879 case IsNullRestricted:
4880 bol = null_free_array_test(array);
4881 break;
4882 case IsAtomic:
4883 // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4884 // Enable TestIntrinsics::test87/88 once this is implemented
4885 // bol = null_free_atomic_array_test
4886 return false;
4887 default:
4888 ShouldNotReachHere();
4889 }
4890
4891 Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4892 set_result(res);
4893 return true;
4894 }
4895
4896 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4897 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4898 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4899 RegionNode* region = new RegionNode(2);
4900 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4901
4902 if (type_array_guard) {
4903 generate_typeArray_guard(klass_node, region);
4904 if (region->req() == 3) {
4905 phi->add_req(klass_node);
4906 }
4907 }
4908 Node* adr_refined_klass = basic_plus_adr(klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4909 Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4910
4911 // Can be null if not initialized yet, just deopt
4912 Node* null_ctl = top();
4913 refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4914
4915 region->init_req(1, control());
4916 phi->init_req(1, refined_klass);
4917
4918 set_control(_gvn.transform(region));
4919 return _gvn.transform(phi);
4920 }
4921
4922 // Load the non-refined array klass from an ObjArrayKlass.
4923 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4924 const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4925 if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4926 return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4927 }
4928
4929 RegionNode* region = new RegionNode(2);
4930 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4931
4932 generate_typeArray_guard(klass_node, region);
4933 if (region->req() == 3) {
4934 phi->add_req(klass_node);
4935 }
4936 Node* super_adr = basic_plus_adr(klass_node, in_bytes(Klass::super_offset()));
4937 Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4938
4939 region->init_req(1, control());
4940 phi->init_req(1, super_klass);
4941
4942 set_control(_gvn.transform(region));
4943 return _gvn.transform(phi);
4944 }
4945
4946 //-----------------------inline_native_newArray--------------------------
4947 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4948 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4949 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4950 Node* mirror;
4951 Node* count_val;
4952 if (uninitialized) {
4953 null_check_receiver();
4954 mirror = argument(1);
4955 count_val = argument(2);
4956 } else {
4957 mirror = argument(0);
4958 count_val = argument(1);
4959 }
4960
4961 mirror = null_check(mirror);
4962 // If mirror or obj is dead, only null-path is taken.
4963 if (stopped()) return true;
4964
4965 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4966 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4967 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4985 CallJavaNode* slow_call = nullptr;
4986 if (uninitialized) {
4987 // Generate optimized virtual call (holder class 'Unsafe' is final)
4988 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4989 } else {
4990 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4991 }
4992 Node* slow_result = set_results_for_java_call(slow_call);
4993 // this->control() comes from set_results_for_java_call
4994 result_reg->set_req(_slow_path, control());
4995 result_val->set_req(_slow_path, slow_result);
4996 result_io ->set_req(_slow_path, i_o());
4997 result_mem->set_req(_slow_path, reset_memory());
4998 }
4999
5000 set_control(normal_ctl);
5001 if (!stopped()) {
5002 // Normal case: The array type has been cached in the java.lang.Class.
5003 // The following call works fine even if the array type is polymorphic.
5004 // It could be a dynamic mix of int[], boolean[], Object[], etc.
5005
5006 klass_node = load_default_refined_array_klass(klass_node);
5007
5008 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
5009 result_reg->init_req(_normal_path, control());
5010 result_val->init_req(_normal_path, obj);
5011 result_io ->init_req(_normal_path, i_o());
5012 result_mem->init_req(_normal_path, reset_memory());
5013
5014 if (uninitialized) {
5015 // Mark the allocation so that zeroing is skipped
5016 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5017 alloc->maybe_set_complete(&_gvn);
5018 }
5019 }
5020
5021 // Return the combined state.
5022 set_i_o( _gvn.transform(result_io) );
5023 set_all_memory( _gvn.transform(result_mem));
5024
5025 C->set_has_split_ifs(true); // Has chance for split-if optimization
5026 set_result(result_reg, result_val);
5027 return true;
5076 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5077 { PreserveReexecuteState preexecs(this);
5078 jvms()->set_should_reexecute(true);
5079
5080 array_type_mirror = null_check(array_type_mirror);
5081 original = null_check(original);
5082
5083 // Check if a null path was taken unconditionally.
5084 if (stopped()) return true;
5085
5086 Node* orig_length = load_array_length(original);
5087
5088 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5089 klass_node = null_check(klass_node);
5090
5091 RegionNode* bailout = new RegionNode(1);
5092 record_for_igvn(bailout);
5093
5094 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5095 // Bail out if that is so.
5096 // Inline type array may have object field that would require a
5097 // write barrier. Conservatively, go to slow path.
5098 // TODO 8251971: Optimize for the case when flat src/dst are later found
5099 // to not contain oops (i.e., move this check to the macro expansion phase).
5100 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5101 const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5102 const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5103 bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5104 // Can src array be flat and contain oops?
5105 (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5106 // Can dest array be flat and contain oops?
5107 tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5108 Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5109
5110 Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5111
5112 if (not_objArray != nullptr) {
5113 // Improve the klass node's type from the new optimistic assumption:
5114 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5115 bool not_flat = !UseArrayFlattening;
5116 bool not_null_free = !Arguments::is_valhalla_enabled();
5117 const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5118 Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5119 refined_klass_node = _gvn.transform(cast);
5120 }
5121
5122 // Bail out if either start or end is negative.
5123 generate_negative_guard(start, bailout, &start);
5124 generate_negative_guard(end, bailout, &end);
5125
5126 Node* length = end;
5127 if (_gvn.type(start) != TypeInt::ZERO) {
5128 length = _gvn.transform(new SubINode(end, start));
5129 }
5130
5131 // Bail out if length is negative (i.e., if start > end).
5132 // Without this the new_array would throw
5133 // NegativeArraySizeException but IllegalArgumentException is what
5134 // should be thrown
5135 generate_negative_guard(length, bailout, &length);
5136
5137 // Handle inline type arrays
5138 bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5139 if (!stopped()) {
5140 // TODO 8251971
5141 if (!orig_t->is_null_free()) {
5142 // Not statically known to be null free, add a check
5143 generate_fair_guard(null_free_array_test(original), bailout);
5144 }
5145 orig_t = _gvn.type(original)->isa_aryptr();
5146 if (orig_t != nullptr && orig_t->is_flat()) {
5147 // Src is flat, check that dest is flat as well
5148 if (exclude_flat) {
5149 // Dest can't be flat, bail out
5150 bailout->add_req(control());
5151 set_control(top());
5152 } else {
5153 generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5154 }
5155 // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5156 } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5157 // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5158 ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5159 // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5160 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5161 generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5162 if (orig_t != nullptr) {
5163 orig_t = orig_t->cast_to_not_flat();
5164 original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5165 }
5166 }
5167 if (!can_validate) {
5168 // No validation. The subtype check emitted at macro expansion time will not go to the slow
5169 // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5170 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5171 generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5172 generate_fair_guard(null_free_array_test(original), bailout);
5173 }
5174 }
5175
5176 // Bail out if start is larger than the original length
5177 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5178 generate_negative_guard(orig_tail, bailout, &orig_tail);
5179
5180 if (bailout->req() > 1) {
5181 PreserveJVMState pjvms(this);
5182 set_control(_gvn.transform(bailout));
5183 uncommon_trap(Deoptimization::Reason_intrinsic,
5184 Deoptimization::Action_maybe_recompile);
5185 }
5186
5187 if (!stopped()) {
5188 // How many elements will we copy from the original?
5189 // The answer is MinI(orig_tail, length).
5190 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5191
5192 // Generate a direct call to the right arraycopy function(s).
5193 // We know the copy is disjoint but we might not know if the
5194 // oop stores need checking.
5195 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
5201 // to the copyOf to be validated, including that the copy to the
5202 // new array won't trigger an ArrayStoreException. That subtype
5203 // check can be optimized if we know something on the type of
5204 // the input array from type speculation.
5205 if (_gvn.type(klass_node)->singleton()) {
5206 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5207 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5208
5209 int test = C->static_subtype_check(superk, subk);
5210 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5211 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5212 if (t_original->speculative_type() != nullptr) {
5213 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5214 }
5215 }
5216 }
5217
5218 bool validated = false;
5219 // Reason_class_check rather than Reason_intrinsic because we
5220 // want to intrinsify even if this traps.
5221 if (can_validate) {
5222 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5223
5224 if (not_subtype_ctrl != top()) {
5225 PreserveJVMState pjvms(this);
5226 set_control(not_subtype_ctrl);
5227 uncommon_trap(Deoptimization::Reason_class_check,
5228 Deoptimization::Action_make_not_entrant);
5229 assert(stopped(), "Should be stopped");
5230 }
5231 validated = true;
5232 }
5233
5234 if (!stopped()) {
5235 newcopy = new_array(refined_klass_node, length, 0); // no arguments to push
5236
5237 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5238 load_object_klass(original), klass_node);
5239 if (!is_copyOfRange) {
5240 ac->set_copyof(validated);
5241 } else {
5242 ac->set_copyofrange(validated);
5243 }
5244 Node* n = _gvn.transform(ac);
5245 if (n == ac) {
5246 ac->connect_outputs(this);
5247 } else {
5248 assert(validated, "shouldn't transform if all arguments not validated");
5249 set_all_memory(n);
5250 }
5251 }
5252 }
5253 } // original reexecute is set back here
5254
5255 C->set_has_split_ifs(true); // Has chance for split-if optimization
5287
5288 //-----------------------generate_method_call----------------------------
5289 // Use generate_method_call to make a slow-call to the real
5290 // method if the fast path fails. An alternative would be to
5291 // use a stub like OptoRuntime::slow_arraycopy_Java.
5292 // This only works for expanding the current library call,
5293 // not another intrinsic. (E.g., don't use this for making an
5294 // arraycopy call inside of the copyOf intrinsic.)
5295 CallJavaNode*
5296 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5297 // When compiling the intrinsic method itself, do not use this technique.
5298 guarantee(callee() != C->method(), "cannot make slow-call to self");
5299
5300 ciMethod* method = callee();
5301 // ensure the JVMS we have will be correct for this call
5302 guarantee(method_id == method->intrinsic_id(), "must match");
5303
5304 const TypeFunc* tf = TypeFunc::make(method);
5305 if (res_not_null) {
5306 assert(tf->return_type() == T_OBJECT, "");
5307 const TypeTuple* range = tf->range_cc();
5308 const Type** fields = TypeTuple::fields(range->cnt());
5309 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5310 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5311 tf = TypeFunc::make(tf->domain_cc(), new_range);
5312 }
5313 CallJavaNode* slow_call;
5314 if (is_static) {
5315 assert(!is_virtual, "");
5316 slow_call = new CallStaticJavaNode(C, tf,
5317 SharedRuntime::get_resolve_static_call_stub(), method);
5318 } else if (is_virtual) {
5319 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5320 int vtable_index = Method::invalid_vtable_index;
5321 if (UseInlineCaches) {
5322 // Suppress the vtable call
5323 } else {
5324 // hashCode and clone are not a miranda methods,
5325 // so the vtable index is fixed.
5326 // No need to use the linkResolver to get it.
5327 vtable_index = method->vtable_index();
5328 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5329 "bad index %d", vtable_index);
5330 }
5331 slow_call = new CallDynamicJavaNode(tf,
5348 set_edges_for_java_call(slow_call);
5349 return slow_call;
5350 }
5351
5352
5353 /**
5354 * Build special case code for calls to hashCode on an object. This call may
5355 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5356 * slightly different code.
5357 */
5358 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5359 assert(is_static == callee()->is_static(), "correct intrinsic selection");
5360 assert(!(is_virtual && is_static), "either virtual, special, or static");
5361
5362 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5363
5364 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5365 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
5366 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
5367 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5368 Node* obj = argument(0);
5369
5370 // Don't intrinsify hashcode on inline types for now.
5371 // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5372 if (gvn().type(obj)->is_inlinetypeptr()) {
5373 return false;
5374 }
5375
5376 if (!is_static) {
5377 // Check for hashing null object
5378 obj = null_check_receiver();
5379 if (stopped()) return true; // unconditionally null
5380 result_reg->init_req(_null_path, top());
5381 result_val->init_req(_null_path, top());
5382 } else {
5383 // Do a null check, and return zero if null.
5384 // System.identityHashCode(null) == 0
5385 Node* null_ctl = top();
5386 obj = null_check_oop(obj, &null_ctl);
5387 result_reg->init_req(_null_path, null_ctl);
5388 result_val->init_req(_null_path, _gvn.intcon(0));
5389 }
5390
5391 // Unconditionally null? Then return right away.
5392 if (stopped()) {
5393 set_control( result_reg->in(_null_path));
5394 if (!stopped())
5395 set_result(result_val->in(_null_path));
5396 return true;
5397 }
5398
5399 // We only go to the fast case code if we pass a number of guards. The
5400 // paths which do not pass are accumulated in the slow_region.
5401 RegionNode* slow_region = new RegionNode(1);
5402 record_for_igvn(slow_region);
5403
5404 // If this is a virtual call, we generate a funny guard. We pull out
5405 // the vtable entry corresponding to hashCode() from the target object.
5406 // If the target method which we are calling happens to be the native
5407 // Object hashCode() method, we pass the guard. We do not need this
5408 // guard for non-virtual calls -- the caller is known to be the native
5409 // Object hashCode().
5410 if (is_virtual) {
5411 // After null check, get the object's klass.
5412 Node* obj_klass = load_object_klass(obj);
5413 generate_virtual_guard(obj_klass, slow_region);
5414 }
5415
5416 // Get the header out of the object, use LoadMarkNode when available
5417 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5418 // The control of the load must be null. Otherwise, the load can move before
5419 // the null check after castPP removal.
5420 Node* no_ctrl = nullptr;
5421 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5422
5423 if (!UseObjectMonitorTable) {
5424 // Test the header to see if it is safe to read w.r.t. locking.
5425 // We cannot use the inline type mask as this may check bits that are overriden
5426 // by an object monitor's pointer when inflating locking.
5427 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
5428 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5429 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
5430 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5431 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5432
5433 generate_slow_guard(test_monitor, slow_region);
5434 }
5435
5436 // Get the hash value and check to see that it has been properly assigned.
5437 // We depend on hash_mask being at most 32 bits and avoid the use of
5438 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5439 // vm: see markWord.hpp.
5440 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
5441 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
5442 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5443 // This hack lets the hash bits live anywhere in the mark object now, as long
5444 // as the shift drops the relevant bits into the low 32 bits. Note that
5445 // Java spec says that HashCode is an int so there's no point in capturing
5446 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5474 // this->control() comes from set_results_for_java_call
5475 result_reg->init_req(_slow_path, control());
5476 result_val->init_req(_slow_path, slow_result);
5477 result_io ->set_req(_slow_path, i_o());
5478 result_mem ->set_req(_slow_path, reset_memory());
5479 }
5480
5481 // Return the combined state.
5482 set_i_o( _gvn.transform(result_io) );
5483 set_all_memory( _gvn.transform(result_mem));
5484
5485 set_result(result_reg, result_val);
5486 return true;
5487 }
5488
5489 //---------------------------inline_native_getClass----------------------------
5490 // public final native Class<?> java.lang.Object.getClass();
5491 //
5492 // Build special case code for calls to getClass on an object.
5493 bool LibraryCallKit::inline_native_getClass() {
5494 Node* obj = argument(0);
5495 if (obj->is_InlineType()) {
5496 const Type* t = _gvn.type(obj);
5497 if (t->maybe_null()) {
5498 null_check(obj);
5499 }
5500 set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5501 return true;
5502 }
5503 obj = null_check_receiver();
5504 if (stopped()) return true;
5505 set_result(load_mirror_from_klass(load_object_klass(obj)));
5506 return true;
5507 }
5508
5509 //-----------------inline_native_Reflection_getCallerClass---------------------
5510 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5511 //
5512 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5513 //
5514 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5515 // in that it must skip particular security frames and checks for
5516 // caller sensitive methods.
5517 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5518 #ifndef PRODUCT
5519 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5520 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5521 }
5522 #endif
5523
5905 // not cloneable or finalizer => slow path to out-of-line Object.clone
5906 //
5907 // The general case has two steps, allocation and copying.
5908 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5909 //
5910 // Copying also has two cases, oop arrays and everything else.
5911 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5912 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5913 //
5914 // These steps fold up nicely if and when the cloned object's klass
5915 // can be sharply typed as an object array, a type array, or an instance.
5916 //
5917 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5918 PhiNode* result_val;
5919
5920 // Set the reexecute bit for the interpreter to reexecute
5921 // the bytecode that invokes Object.clone if deoptimization happens.
5922 { PreserveReexecuteState preexecs(this);
5923 jvms()->set_should_reexecute(true);
5924
5925 Node* obj = argument(0);
5926 obj = null_check_receiver();
5927 if (stopped()) return true;
5928
5929 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5930 if (obj_type->is_inlinetypeptr()) {
5931 // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5932 // no identity.
5933 set_result(obj);
5934 return true;
5935 }
5936
5937 // If we are going to clone an instance, we need its exact type to
5938 // know the number and types of fields to convert the clone to
5939 // loads/stores. Maybe a speculative type can help us.
5940 if (!obj_type->klass_is_exact() &&
5941 obj_type->speculative_type() != nullptr &&
5942 obj_type->speculative_type()->is_instance_klass() &&
5943 !obj_type->speculative_type()->is_inlinetype()) {
5944 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5945 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5946 !spec_ik->has_injected_fields()) {
5947 if (!obj_type->isa_instptr() ||
5948 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5949 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5950 }
5951 }
5952 }
5953
5954 // Conservatively insert a memory barrier on all memory slices.
5955 // Do not let writes into the original float below the clone.
5956 insert_mem_bar(Op_MemBarCPUOrder);
5957
5958 // paths into result_reg:
5959 enum {
5960 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5961 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5962 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5963 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5964 PATH_LIMIT
5965 };
5966 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5967 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5968 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5969 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5970 record_for_igvn(result_reg);
5971
5972 Node* obj_klass = load_object_klass(obj);
5973 // We only go to the fast case code if we pass a number of guards.
5974 // The paths which do not pass are accumulated in the slow_region.
5975 RegionNode* slow_region = new RegionNode(1);
5976 record_for_igvn(slow_region);
5977
5978 Node* array_obj = obj;
5979 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5980 if (array_ctl != nullptr) {
5981 // It's an array.
5982 PreserveJVMState pjvms(this);
5983 set_control(array_ctl);
5984
5985 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5986 const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5987 if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5988 obj_type->can_be_inline_array() &&
5989 (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5990 // Flat inline type array may have object field that would require a
5991 // write barrier. Conservatively, go to slow path.
5992 generate_fair_guard(flat_array_test(obj_klass), slow_region);
5993 }
5994
5995 if (!stopped()) {
5996 Node* obj_length = load_array_length(array_obj);
5997 Node* array_size = nullptr; // Size of the array without object alignment padding.
5998 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5999
6000 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6001 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6002 // If it is an oop array, it requires very special treatment,
6003 // because gc barriers are required when accessing the array.
6004 Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6005 if (is_obja != nullptr) {
6006 PreserveJVMState pjvms2(this);
6007 set_control(is_obja);
6008 // Generate a direct call to the right arraycopy function(s).
6009 // Clones are always tightly coupled.
6010 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6011 ac->set_clone_oop_array();
6012 Node* n = _gvn.transform(ac);
6013 assert(n == ac, "cannot disappear");
6014 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6015
6016 result_reg->init_req(_objArray_path, control());
6017 result_val->init_req(_objArray_path, alloc_obj);
6018 result_i_o ->set_req(_objArray_path, i_o());
6019 result_mem ->set_req(_objArray_path, reset_memory());
6020 }
6021 }
6022 // Otherwise, there are no barriers to worry about.
6023 // (We can dispense with card marks if we know the allocation
6024 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
6025 // causes the non-eden paths to take compensating steps to
6026 // simulate a fresh allocation, so that no further
6027 // card marks are required in compiled code to initialize
6028 // the object.)
6029
6030 if (!stopped()) {
6031 copy_to_clone(obj, alloc_obj, array_size, true);
6032
6033 // Present the results of the copy.
6034 result_reg->init_req(_array_path, control());
6035 result_val->init_req(_array_path, alloc_obj);
6036 result_i_o ->set_req(_array_path, i_o());
6037 result_mem ->set_req(_array_path, reset_memory());
6038 }
6039 }
6040 }
6041
6042 if (!stopped()) {
6043 // It's an instance (we did array above). Make the slow-path tests.
6044 // If this is a virtual call, we generate a funny guard. We grab
6045 // the vtable entry corresponding to clone() from the target object.
6046 // If the target method which we are calling happens to be the
6047 // Object clone() method, we pass the guard. We do not need this
6048 // guard for non-virtual calls; the caller is known to be the native
6049 // Object clone().
6050 if (is_virtual) {
6051 generate_virtual_guard(obj_klass, slow_region);
6052 }
6053
6054 // The object must be easily cloneable and must not have a finalizer.
6055 // Both of these conditions may be checked in a single test.
6056 // We could optimize the test further, but we don't care.
6057 generate_misc_flags_guard(obj_klass,
6058 // Test both conditions:
6059 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6060 // Must be cloneable but not finalizer:
6061 KlassFlags::_misc_is_cloneable_fast,
6153 set_jvms(sfpt->jvms());
6154 _reexecute_sp = jvms()->sp();
6155
6156 return saved_jvms;
6157 }
6158 }
6159 }
6160 return nullptr;
6161 }
6162
6163 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6164 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6165 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6166 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6167 uint size = alloc->req();
6168 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6169 old_jvms->set_map(sfpt);
6170 for (uint i = 0; i < size; i++) {
6171 sfpt->init_req(i, alloc->in(i));
6172 }
6173 int adjustment = 1;
6174 const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6175 if (ary_klass_ptr->is_null_free()) {
6176 // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6177 // also requires the componentType and initVal on stack for re-execution.
6178 // Re-create and push the componentType.
6179 ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6180 ciInstance* instance = klass->component_mirror_instance();
6181 const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6182 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6183 adjustment++;
6184 }
6185 // re-push array length for deoptimization
6186 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6187 if (ary_klass_ptr->is_null_free()) {
6188 // Re-create and push the initVal.
6189 Node* init_val = alloc->in(AllocateNode::InitValue);
6190 if (init_val == nullptr) {
6191 init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6192 } else if (UseCompressedOops) {
6193 init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6194 }
6195 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6196 adjustment++;
6197 }
6198 old_jvms->set_sp(old_jvms->sp() + adjustment);
6199 old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6200 old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6201 old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6202 old_jvms->set_should_reexecute(true);
6203
6204 sfpt->set_i_o(map()->i_o());
6205 sfpt->set_memory(map()->memory());
6206 sfpt->set_control(map()->control());
6207 return sfpt;
6208 }
6209
6210 // In case of a deoptimization, we restart execution at the
6211 // allocation, allocating a new array. We would leave an uninitialized
6212 // array in the heap that GCs wouldn't expect. Move the allocation
6213 // after the traps so we don't allocate the array if we
6214 // deoptimize. This is possible because tightly_coupled_allocation()
6215 // guarantees there's no observer of the allocated array at this point
6216 // and the control flow is simple enough.
6217 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6218 int saved_reexecute_sp, uint new_idx) {
6219 if (saved_jvms_before_guards != nullptr && !stopped()) {
6220 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6221
6222 assert(alloc != nullptr, "only with a tightly coupled allocation");
6223 // restore JVM state to the state at the arraycopy
6224 saved_jvms_before_guards->map()->set_control(map()->control());
6225 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6226 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6227 // If we've improved the types of some nodes (null check) while
6228 // emitting the guards, propagate them to the current state
6229 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6230 set_jvms(saved_jvms_before_guards);
6231 _reexecute_sp = saved_reexecute_sp;
6232
6233 // Remove the allocation from above the guards
6234 CallProjections* callprojs = alloc->extract_projections(true);
6235 InitializeNode* init = alloc->initialization();
6236 Node* alloc_mem = alloc->in(TypeFunc::Memory);
6237 C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6238 init->replace_mem_projs_by(alloc_mem, C);
6239
6240 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6241 // the allocation (i.e. is only valid if the allocation succeeds):
6242 // 1) replace CastIINode with AllocateArrayNode's length here
6243 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6244 //
6245 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6246 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6247 Node* init_control = init->proj_out(TypeFunc::Control);
6248 Node* alloc_length = alloc->Ideal_length();
6249 #ifdef ASSERT
6250 Node* prev_cast = nullptr;
6251 #endif
6252 for (uint i = 0; i < init_control->outcnt(); i++) {
6253 Node* init_out = init_control->raw_out(i);
6254 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6255 #ifdef ASSERT
6256 if (prev_cast == nullptr) {
6257 prev_cast = init_out;
6259 if (prev_cast->cmp(*init_out) == false) {
6260 prev_cast->dump();
6261 init_out->dump();
6262 assert(false, "not equal CastIINode");
6263 }
6264 }
6265 #endif
6266 C->gvn_replace_by(init_out, alloc_length);
6267 }
6268 }
6269 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6270
6271 // move the allocation here (after the guards)
6272 _gvn.hash_delete(alloc);
6273 alloc->set_req(TypeFunc::Control, control());
6274 alloc->set_req(TypeFunc::I_O, i_o());
6275 Node *mem = reset_memory();
6276 set_all_memory(mem);
6277 alloc->set_req(TypeFunc::Memory, mem);
6278 set_control(init->proj_out_or_null(TypeFunc::Control));
6279 set_i_o(callprojs->fallthrough_ioproj);
6280
6281 // Update memory as done in GraphKit::set_output_for_allocation()
6282 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6283 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6284 if (ary_type->isa_aryptr() && length_type != nullptr) {
6285 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6286 }
6287 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6288 int elemidx = C->get_alias_index(telemref);
6289 // Need to properly move every memory projection for the Initialize
6290 #ifdef ASSERT
6291 int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6292 int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6293 #endif
6294 auto move_proj = [&](ProjNode* proj) {
6295 int alias_idx = C->get_alias_index(proj->adr_type());
6296 assert(alias_idx == Compile::AliasIdxRaw ||
6297 alias_idx == elemidx ||
6298 alias_idx == mark_idx ||
6299 alias_idx == klass_idx, "should be raw memory or array element type");
6609 top_src = src_type->isa_aryptr();
6610 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6611 src_spec = true;
6612 }
6613 if (!has_dest) {
6614 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6615 dest_type = _gvn.type(dest);
6616 top_dest = dest_type->isa_aryptr();
6617 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6618 dest_spec = true;
6619 }
6620 }
6621 }
6622
6623 if (has_src && has_dest && can_emit_guards) {
6624 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6625 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6626 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6627 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6628
6629 if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6630 // If both arrays are object arrays then having the exact types
6631 // for both will remove the need for a subtype check at runtime
6632 // before the call and may make it possible to pick a faster copy
6633 // routine (without a subtype check on every element)
6634 // Do we have the exact type of src?
6635 bool could_have_src = src_spec;
6636 // Do we have the exact type of dest?
6637 bool could_have_dest = dest_spec;
6638 ciKlass* src_k = nullptr;
6639 ciKlass* dest_k = nullptr;
6640 if (!src_spec) {
6641 src_k = src_type->speculative_type_not_null();
6642 if (src_k != nullptr && src_k->is_array_klass()) {
6643 could_have_src = true;
6644 }
6645 }
6646 if (!dest_spec) {
6647 dest_k = dest_type->speculative_type_not_null();
6648 if (dest_k != nullptr && dest_k->is_array_klass()) {
6649 could_have_dest = true;
6650 }
6651 }
6652 if (could_have_src && could_have_dest) {
6653 // If we can have both exact types, emit the missing guards
6654 if (could_have_src && !src_spec) {
6655 src = maybe_cast_profiled_obj(src, src_k, true);
6656 src_type = _gvn.type(src);
6657 top_src = src_type->isa_aryptr();
6658 }
6659 if (could_have_dest && !dest_spec) {
6660 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6661 dest_type = _gvn.type(dest);
6662 top_dest = dest_type->isa_aryptr();
6663 }
6664 }
6665 }
6666 }
6667
6668 ciMethod* trap_method = method();
6669 int trap_bci = bci();
6670 if (saved_jvms_before_guards != nullptr) {
6671 trap_method = alloc->jvms()->method();
6672 trap_bci = alloc->jvms()->bci();
6673 }
6674
6675 bool negative_length_guard_generated = false;
6676
6677 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6678 can_emit_guards && !src->is_top() && !dest->is_top()) {
6679 // validate arguments: enables transformation the ArrayCopyNode
6680 validated = true;
6681
6682 RegionNode* slow_region = new RegionNode(1);
6683 record_for_igvn(slow_region);
6684
6685 // (1) src and dest are arrays.
6686 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6687 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6688
6689 // (2) src and dest arrays must have elements of the same BasicType
6690 // done at macro expansion or at Ideal transformation time
6691
6692 // (4) src_offset must not be negative.
6693 generate_negative_guard(src_offset, slow_region);
6694
6695 // (5) dest_offset must not be negative.
6696 generate_negative_guard(dest_offset, slow_region);
6697
6698 // (7) src_offset + length must not exceed length of src.
6699 generate_limit_guard(src_offset, length,
6700 load_array_length(src),
6701 slow_region);
6702
6703 // (8) dest_offset + length must not exceed length of dest.
6704 generate_limit_guard(dest_offset, length,
6705 load_array_length(dest),
6706 slow_region);
6707
6708 // (6) length must not be negative.
6709 // This is also checked in generate_arraycopy() during macro expansion, but
6710 // we also have to check it here for the case where the ArrayCopyNode will
6711 // be eliminated by Escape Analysis.
6712 if (EliminateAllocations) {
6713 generate_negative_guard(length, slow_region);
6714 negative_length_guard_generated = true;
6715 }
6716
6717 // (9) each element of an oop array must be assignable
6718 Node* dest_klass = load_object_klass(dest);
6719 Node* refined_dest_klass = dest_klass;
6720 if (src != dest) {
6721 dest_klass = load_non_refined_array_klass(refined_dest_klass);
6722 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6723 slow_region->add_req(not_subtype_ctrl);
6724 }
6725
6726 // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6727 // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6728 Node* src_klass = load_object_klass(src);
6729 Node* adr_prop_src = basic_plus_adr(src_klass, in_bytes(ArrayKlass::properties_offset()));
6730 Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6731 Node* adr_prop_dest = basic_plus_adr(refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6732 Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6733
6734 prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6735 prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6736 prop_src = _gvn.transform(new AndINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6737
6738 Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6739 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6740 generate_fair_guard(tst, slow_region);
6741
6742 // TODO 8350865 This is too strong
6743 generate_fair_guard(flat_array_test(src), slow_region);
6744 generate_fair_guard(flat_array_test(dest), slow_region);
6745
6746 {
6747 PreserveJVMState pjvms(this);
6748 set_control(_gvn.transform(slow_region));
6749 uncommon_trap(Deoptimization::Reason_intrinsic,
6750 Deoptimization::Action_make_not_entrant);
6751 assert(stopped(), "Should be stopped");
6752 }
6753
6754 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6755 if (dest_klass_t == nullptr) {
6756 // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6757 // are in a dead path.
6758 uncommon_trap(Deoptimization::Reason_intrinsic,
6759 Deoptimization::Action_make_not_entrant);
6760 return true;
6761 }
6762
6763 const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6764 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6765 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6766 }
6767
6768 if (stopped()) {
6769 return true;
6770 }
6771
6772 Node* dest_klass = load_object_klass(dest);
6773 dest_klass = load_non_refined_array_klass(dest_klass);
6774
6775 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6776 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6777 // so the compiler has a chance to eliminate them: during macro expansion,
6778 // we have to set their control (CastPP nodes are eliminated).
6779 load_object_klass(src), dest_klass,
6780 load_array_length(src), load_array_length(dest));
6781
6782 ac->set_arraycopy(validated);
6783
6784 Node* n = _gvn.transform(ac);
6785 if (n == ac) {
6786 ac->connect_outputs(this);
6787 } else {
6788 assert(validated, "shouldn't transform if all arguments not validated");
6789 set_all_memory(n);
6790 }
6791 clear_upper_avx();
6792
6793
6794 return true;
6795 }
6796
6797
6798 // Helper function which determines if an arraycopy immediately follows
6799 // an allocation, with no intervening tests or other escapes for the object.
|