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:
2263 case vmIntrinsics::_remainderUnsigned_l: {
2264 zero_check_long(argument(2));
2265 // Compile-time detect of null-exception
2266 if (stopped()) {
2267 return true; // keep the graph constructed so far
2268 }
2269 n = new UModLNode(control(), argument(0), argument(2));
2270 break;
2271 }
2272 default: fatal_unexpected_iid(id); break;
2273 }
2274 set_result(_gvn.transform(n));
2275 return true;
2276 }
2277
2278 //----------------------------inline_unsafe_access----------------------------
2279
2280 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2281 // Attempt to infer a sharper value type from the offset and base type.
2282 ciKlass* sharpened_klass = nullptr;
2283
2284 // See if it is an instance field, with an object type.
2285 if (alias_type->field() != nullptr) {
2286 if (alias_type->field()->type()->is_klass()) {
2287 sharpened_klass = alias_type->field()->type()->as_klass();
2288 }
2289 }
2290
2291 const TypeOopPtr* result = nullptr;
2292 // See if it is a narrow oop array.
2293 if (adr_type->isa_aryptr()) {
2294 if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2295 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2296 if (elem_type != nullptr && elem_type->is_loaded()) {
2297 // Sharpen the value type.
2298 result = elem_type;
2299 }
2300 }
2301 }
2302
2303 // The sharpened class might be unloaded if there is no class loader
2304 // contraint in place.
2305 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2306 // Sharpen the value type.
2307 result = TypeOopPtr::make_from_klass(sharpened_klass);
2308 }
2309 if (result != nullptr) {
2310 #ifndef PRODUCT
2311 if (C->print_intrinsics() || C->print_inlining()) {
2312 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2313 tty->print(" sharpened value: "); result->dump(); tty->cr();
2314 }
2315 #endif
2316 }
2317 return result;
2318 }
2319
2320 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2321 switch (kind) {
2322 case Relaxed:
2323 return MO_UNORDERED;
2324 case Opaque:
2325 return MO_RELAXED;
2326 case Acquire:
2327 return MO_ACQUIRE;
2375 #endif // ASSERT
2376 }
2377 #endif //PRODUCT
2378
2379 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2380
2381 Node* receiver = argument(0); // type: oop
2382
2383 // Build address expression.
2384 Node* heap_base_oop = top();
2385
2386 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2387 Node* base = argument(1); // type: oop
2388 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2389 Node* offset = argument(2); // type: long
2390 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2391 // to be plain byte offsets, which are also the same as those accepted
2392 // by oopDesc::field_addr.
2393 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2394 "fieldOffset must be byte-scaled");
2395 // 32-bit machines ignore the high half!
2396 offset = ConvL2X(offset);
2397
2398 // Save state and restore on bailout
2399 SavedState old_state(this);
2400
2401 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2402 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2403
2404 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2405 if (type != T_OBJECT) {
2406 decorators |= IN_NATIVE; // off-heap primitive access
2407 } else {
2408 return false; // off-heap oop accesses are not supported
2409 }
2410 } else {
2411 heap_base_oop = base; // on-heap or mixed access
2412 }
2413
2414 // Can base be null? Otherwise, always on-heap access.
2418 decorators |= IN_HEAP;
2419 }
2420
2421 Node* val = is_store ? argument(4) : nullptr;
2422
2423 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2424 if (adr_type == TypePtr::NULL_PTR) {
2425 return false; // off-heap access with zero address
2426 }
2427
2428 // Try to categorize the address.
2429 Compile::AliasType* alias_type = C->alias_type(adr_type);
2430 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2431
2432 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2433 alias_type->adr_type() == TypeAryPtr::RANGE) {
2434 return false; // not supported
2435 }
2436
2437 bool mismatched = false;
2438 BasicType bt = alias_type->basic_type();
2439 if (bt != T_ILLEGAL) {
2440 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2441 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2442 // Alias type doesn't differentiate between byte[] and boolean[]).
2443 // Use address type to get the element type.
2444 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2445 }
2446 if (is_reference_type(bt, true)) {
2447 // accessing an array field with getReference is not a mismatch
2448 bt = T_OBJECT;
2449 }
2450 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2451 // Don't intrinsify mismatched object accesses
2452 return false;
2453 }
2454 mismatched = (bt != type);
2455 } else if (alias_type->adr_type()->isa_oopptr()) {
2456 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2457 }
2458
2459 old_state.discard();
2460 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2461
2462 if (mismatched) {
2463 decorators |= C2_MISMATCHED;
2464 }
2465
2466 // First guess at the value type.
2467 const Type *value_type = Type::get_const_basic_type(type);
2468
2469 // Figure out the memory ordering.
2470 decorators |= mo_decorator_for_access_kind(kind);
2471
2472 if (!is_store && type == T_OBJECT) {
2473 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2474 if (tjp != nullptr) {
2475 value_type = tjp;
2476 }
2477 }
2478
2479 receiver = null_check(receiver);
2480 if (stopped()) {
2481 return true;
2482 }
2483 // Heap pointers get a null-check from the interpreter,
2484 // as a courtesy. However, this is not guaranteed by Unsafe,
2485 // and it is not possible to fully distinguish unintended nulls
2486 // from intended ones in this API.
2487
2488 if (!is_store) {
2489 Node* p = nullptr;
2490 // Try to constant fold a load from a constant field
2491 ciField* field = alias_type->field();
2492 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !mismatched) {
2493 // final or stable field
2494 p = make_constant_from_field(field, heap_base_oop);
2495 }
2496
2497 if (p == nullptr) { // Could not constant fold the load
2498 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2499 // Normalize the value returned by getBoolean in the following cases
2500 if (type == T_BOOLEAN &&
2501 (mismatched ||
2502 heap_base_oop == top() || // - heap_base_oop is null or
2503 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2504 // and the unsafe access is made to large offset
2505 // (i.e., larger than the maximum offset necessary for any
2506 // field access)
2507 ) {
2508 IdealKit ideal = IdealKit(this);
2509 #define __ ideal.
2510 IdealVariable normalized_result(ideal);
2511 __ declarations_done();
2512 __ set(normalized_result, p);
2513 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2514 __ set(normalized_result, ideal.ConI(1));
2515 ideal.end_if();
2516 final_sync(ideal);
2517 p = __ value(normalized_result);
2518 #undef __
2522 p = gvn().transform(new CastP2XNode(nullptr, p));
2523 p = ConvX2UL(p);
2524 }
2525 // The load node has the control of the preceding MemBarCPUOrder. All
2526 // following nodes will have the control of the MemBarCPUOrder inserted at
2527 // the end of this method. So, pushing the load onto the stack at a later
2528 // point is fine.
2529 set_result(p);
2530 } else {
2531 if (bt == T_ADDRESS) {
2532 // Repackage the long as a pointer.
2533 val = ConvL2X(val);
2534 val = gvn().transform(new CastX2PNode(val));
2535 }
2536 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2537 }
2538
2539 return true;
2540 }
2541
2542 //----------------------------inline_unsafe_load_store----------------------------
2543 // This method serves a couple of different customers (depending on LoadStoreKind):
2544 //
2545 // LS_cmp_swap:
2546 //
2547 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2548 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2549 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2550 //
2551 // LS_cmp_swap_weak:
2552 //
2553 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2554 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2555 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2556 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2557 //
2558 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2559 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2560 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2561 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
2724 }
2725 case LS_cmp_swap:
2726 case LS_cmp_swap_weak:
2727 case LS_get_add:
2728 break;
2729 default:
2730 ShouldNotReachHere();
2731 }
2732
2733 // Null check receiver.
2734 receiver = null_check(receiver);
2735 if (stopped()) {
2736 return true;
2737 }
2738
2739 int alias_idx = C->get_alias_index(adr_type);
2740
2741 if (is_reference_type(type)) {
2742 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2743
2744 // Transformation of a value which could be null pointer (CastPP #null)
2745 // could be delayed during Parse (for example, in adjust_map_after_if()).
2746 // Execute transformation here to avoid barrier generation in such case.
2747 if (_gvn.type(newval) == TypePtr::NULL_PTR)
2748 newval = _gvn.makecon(TypePtr::NULL_PTR);
2749
2750 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2751 // Refine the value to a null constant, when it is known to be null
2752 oldval = _gvn.makecon(TypePtr::NULL_PTR);
2753 }
2754 }
2755
2756 Node* result = nullptr;
2757 switch (kind) {
2758 case LS_cmp_exchange: {
2759 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2760 oldval, newval, value_type, type, decorators);
2761 break;
2762 }
2763 case LS_cmp_swap_weak:
2792 insert_mem_bar(Op_MemBarCPUOrder);
2793 switch(id) {
2794 case vmIntrinsics::_loadFence:
2795 insert_mem_bar(Op_LoadFence);
2796 return true;
2797 case vmIntrinsics::_storeFence:
2798 insert_mem_bar(Op_StoreFence);
2799 return true;
2800 case vmIntrinsics::_storeStoreFence:
2801 insert_mem_bar(Op_StoreStoreFence);
2802 return true;
2803 case vmIntrinsics::_fullFence:
2804 insert_mem_bar(Op_MemBarFull);
2805 return true;
2806 default:
2807 fatal_unexpected_iid(id);
2808 return false;
2809 }
2810 }
2811
2812 bool LibraryCallKit::inline_onspinwait() {
2813 insert_mem_bar(Op_OnSpinWait);
2814 return true;
2815 }
2816
2817 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
2818 if (!kls->is_Con()) {
2819 return true;
2820 }
2821 const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
2822 if (klsptr == nullptr) {
2823 return true;
2824 }
2825 ciInstanceKlass* ik = klsptr->instance_klass();
2826 // don't need a guard for a klass that is already initialized
2827 return !ik->is_initialized();
2828 }
2829
2830 //----------------------------inline_unsafe_writeback0-------------------------
2831 // public native void Unsafe.writeback0(long address)
2910 Deoptimization::Action_make_not_entrant);
2911 }
2912 if (stopped()) {
2913 return true;
2914 }
2915 #endif //INCLUDE_JVMTI
2916
2917 Node* test = nullptr;
2918 if (LibraryCallKit::klass_needs_init_guard(kls)) {
2919 // Note: The argument might still be an illegal value like
2920 // Serializable.class or Object[].class. The runtime will handle it.
2921 // But we must make an explicit check for initialization.
2922 Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
2923 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
2924 // can generate code to load it as unsigned byte.
2925 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
2926 Node* bits = intcon(InstanceKlass::fully_initialized);
2927 test = _gvn.transform(new SubINode(inst, bits));
2928 // The 'test' is non-zero if we need to take a slow path.
2929 }
2930
2931 Node* obj = new_instance(kls, test);
2932 set_result(obj);
2933 return true;
2934 }
2935
2936 //------------------------inline_native_time_funcs--------------
2937 // inline code for System.currentTimeMillis() and System.nanoTime()
2938 // these have the same type and signature
2939 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
2940 const TypeFunc* tf = OptoRuntime::void_long_Type();
2941 const TypePtr* no_memory_effects = nullptr;
2942 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
2943 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
2944 #ifdef ASSERT
2945 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
2946 assert(value_top == top(), "second value must be top");
2947 #endif
2948 set_result(value);
2949 return true;
2950 }
3726 Node* arr = argument(1);
3727 Node* thread = _gvn.transform(new ThreadLocalNode());
3728 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
3729 Node* thread_obj_handle
3730 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3731 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3732 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3733
3734 // Change the _monitor_owner_id of the JavaThread
3735 Node* tid = load_field_from_object(arr, "tid", "J");
3736 Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3737 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3738
3739 JFR_ONLY(extend_setCurrentThread(thread, arr);)
3740 return true;
3741 }
3742
3743 const Type* LibraryCallKit::scopedValueCache_type() {
3744 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3745 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3746 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS);
3747
3748 // Because we create the scopedValue cache lazily we have to make the
3749 // type of the result BotPTR.
3750 bool xk = etype->klass_is_exact();
3751 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, 0);
3752 return objects_type;
3753 }
3754
3755 Node* LibraryCallKit::scopedValueCache_helper() {
3756 Node* thread = _gvn.transform(new ThreadLocalNode());
3757 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
3758 // We cannot use immutable_memory() because we might flip onto a
3759 // different carrier thread, at which point we'll need to use that
3760 // carrier thread's cache.
3761 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3762 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3763 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3764 }
3765
3766 //------------------------inline_native_scopedValueCache------------------
3767 bool LibraryCallKit::inline_native_scopedValueCache() {
3768 Node* cache_obj_handle = scopedValueCache_helper();
3769 const Type* objects_type = scopedValueCache_type();
3770 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3771
3907 }
3908 return kls;
3909 }
3910
3911 //--------------------(inline_native_Class_query helpers)---------------------
3912 // Use this for JVM_ACC_INTERFACE.
3913 // Fall through if (mods & mask) == bits, take the guard otherwise.
3914 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
3915 ByteSize offset, const Type* type, BasicType bt) {
3916 // Branch around if the given klass has the given modifier bit set.
3917 // Like generate_guard, adds a new path onto the region.
3918 Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
3919 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
3920 Node* mask = intcon(modifier_mask);
3921 Node* bits = intcon(modifier_bits);
3922 Node* mbit = _gvn.transform(new AndINode(mods, mask));
3923 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
3924 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3925 return generate_fair_guard(bol, region);
3926 }
3927 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3928 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
3929 InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
3930 }
3931
3932 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
3933 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3934 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
3935 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
3936 }
3937
3938 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
3939 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
3940 }
3941
3942 //-------------------------inline_native_Class_query-------------------
3943 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
3944 const Type* return_type = TypeInt::BOOL;
3945 Node* prim_return_value = top(); // what happens if it's a primitive class?
3946 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4032
4033
4034 case vmIntrinsics::_getSuperclass:
4035 // The rules here are somewhat unfortunate, but we can still do better
4036 // with random logic than with a JNI call.
4037 // Interfaces store null or Object as _super, but must report null.
4038 // Arrays store an intermediate super as _super, but must report Object.
4039 // Other types can report the actual _super.
4040 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4041 if (generate_array_guard(kls, region) != nullptr) {
4042 // A guard was added. If the guard is taken, it was an array.
4043 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4044 }
4045 // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4046 // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4047 if (generate_interface_guard(kls, region) != nullptr) {
4048 // A guard was added. If the guard is taken, it was an interface.
4049 phi->add_req(null());
4050 }
4051 // If we fall through, it's a plain class. Get its _super.
4052 p = off_heap_plus_addr(kls, in_bytes(Klass::super_offset()));
4053 kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4054 null_ctl = top();
4055 kls = null_check_oop(kls, &null_ctl);
4056 if (null_ctl != top()) {
4057 // If the guard is taken, Object.superClass is null (both klass and mirror).
4058 region->add_req(null_ctl);
4059 phi ->add_req(null());
4060 }
4061 if (!stopped()) {
4062 query_value = load_mirror_from_klass(kls);
4063 }
4064 break;
4065
4066 default:
4067 fatal_unexpected_iid(id);
4068 break;
4069 }
4070
4071 // Fall-through is the normal case of a query to a real class.
4072 phi->init_req(1, query_value);
4073 region->init_req(1, control());
4074
4075 C->set_has_split_ifs(true); // Has chance for split-if optimization
4076 set_result(region, phi);
4077 return true;
4078 }
4079
4080 //-------------------------inline_Class_cast-------------------
4081 bool LibraryCallKit::inline_Class_cast() {
4082 Node* mirror = argument(0); // Class
4083 Node* obj = argument(1);
4084 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4085 if (mirror_con == nullptr) {
4086 return false; // dead path (mirror->is_top()).
4087 }
4088 if (obj == nullptr || obj->is_top()) {
4089 return false; // dead path
4090 }
4091 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4092
4093 // First, see if Class.cast() can be folded statically.
4094 // java_mirror_type() returns non-null for compile-time Class constants.
4095 ciType* tm = mirror_con->java_mirror_type();
4096 if (tm != nullptr && tm->is_klass() &&
4097 tp != nullptr) {
4098 if (!tp->is_loaded()) {
4099 // Don't use intrinsic when class is not loaded.
4100 return false;
4101 } else {
4102 int static_res = C->static_subtype_check(TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces), tp->as_klass_type());
4103 if (static_res == Compile::SSC_always_true) {
4104 // isInstance() is true - fold the code.
4105 set_result(obj);
4106 return true;
4107 } else if (static_res == Compile::SSC_always_false) {
4108 // Don't use intrinsic, have to throw ClassCastException.
4109 // If the reference is null, the non-intrinsic bytecode will
4110 // be optimized appropriately.
4111 return false;
4112 }
4113 }
4114 }
4115
4116 // Bailout intrinsic and do normal inlining if exception path is frequent.
4117 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4118 return false;
4119 }
4120
4121 // Generate dynamic checks.
4122 // Class.cast() is java implementation of _checkcast bytecode.
4123 // Do checkcast (Parse::do_checkcast()) optimizations here.
4124
4125 mirror = null_check(mirror);
4126 // If mirror is dead, only null-path is taken.
4127 if (stopped()) {
4128 return true;
4129 }
4130
4131 // Not-subtype or the mirror's klass ptr is null (in case it is a primitive).
4132 enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
4133 RegionNode* region = new RegionNode(PATH_LIMIT);
4134 record_for_igvn(region);
4135
4136 // Now load the mirror's klass metaobject, and null-check it.
4137 // If kls is null, we have a primitive mirror and
4138 // nothing is an instance of a primitive type.
4139 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4140
4141 Node* res = top();
4142 if (!stopped()) {
4143 Node* bad_type_ctrl = top();
4144 // Do checkcast optimizations.
4145 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4146 region->init_req(_bad_type_path, bad_type_ctrl);
4147 }
4148 if (region->in(_prim_path) != top() ||
4149 region->in(_bad_type_path) != top()) {
4150 // Let Interpreter throw ClassCastException.
4151 PreserveJVMState pjvms(this);
4152 set_control(_gvn.transform(region));
4153 uncommon_trap(Deoptimization::Reason_intrinsic,
4154 Deoptimization::Action_maybe_recompile);
4155 }
4156 if (!stopped()) {
4157 set_result(res);
4158 }
4159 return true;
4160 }
4161
4162
4163 //--------------------------inline_native_subtype_check------------------------
4164 // This intrinsic takes the JNI calls out of the heart of
4165 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4166 bool LibraryCallKit::inline_native_subtype_check() {
4167 // Pull both arguments off the stack.
4168 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4169 args[0] = argument(0);
4170 args[1] = argument(1);
4171 Node* klasses[2]; // corresponding Klasses: superk, subk
4172 klasses[0] = klasses[1] = top();
4173
4174 enum {
4175 // A full decision tree on {superc is prim, subc is prim}:
4176 _prim_0_path = 1, // {P,N} => false
4177 // {P,P} & superc!=subc => false
4178 _prim_same_path, // {P,P} & superc==subc => true
4179 _prim_1_path, // {N,P} => false
4180 _ref_subtype_path, // {N,N} & subtype check wins => true
4181 _both_ref_path, // {N,N} & subtype check loses => false
4182 PATH_LIMIT
4183 };
4184
4185 RegionNode* region = new RegionNode(PATH_LIMIT);
4186 Node* phi = new PhiNode(region, TypeInt::BOOL);
4187 record_for_igvn(region);
4188
4189 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4190 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4191 int class_klass_offset = java_lang_Class::klass_offset();
4192
4193 // First null-check both mirrors and load each mirror's klass metaobject.
4194 int which_arg;
4195 for (which_arg = 0; which_arg <= 1; which_arg++) {
4196 Node* arg = args[which_arg];
4197 arg = null_check(arg);
4198 if (stopped()) break;
4199 args[which_arg] = arg;
4200
4201 Node* p = basic_plus_adr(arg, class_klass_offset);
4202 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4203 klasses[which_arg] = _gvn.transform(kls);
4204 }
4205
4206 // Having loaded both klasses, test each for null.
4207 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4208 for (which_arg = 0; which_arg <= 1; which_arg++) {
4209 Node* kls = klasses[which_arg];
4210 Node* null_ctl = top();
4211 kls = null_check_oop(kls, &null_ctl, never_see_null);
4212 int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
4213 region->init_req(prim_path, null_ctl);
4214 if (stopped()) break;
4215 klasses[which_arg] = kls;
4216 }
4217
4218 if (!stopped()) {
4219 // now we have two reference types, in klasses[0..1]
4220 Node* subk = klasses[1]; // the argument to isAssignableFrom
4221 Node* superk = klasses[0]; // the receiver
4222 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4223 // now we have a successful reference subtype check
4224 region->set_req(_ref_subtype_path, control());
4225 }
4226
4227 // If both operands are primitive (both klasses null), then
4228 // we must return true when they are identical primitives.
4229 // It is convenient to test this after the first null klass check.
4230 set_control(region->in(_prim_0_path)); // go back to first null check
4231 if (!stopped()) {
4232 // Since superc is primitive, make a guard for the superc==subc case.
4233 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4234 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4235 generate_guard(bol_eq, region, PROB_FAIR);
4236 if (region->req() == PATH_LIMIT+1) {
4237 // A guard was added. If the added guard is taken, superc==subc.
4238 region->swap_edges(PATH_LIMIT, _prim_same_path);
4239 region->del_req(PATH_LIMIT);
4240 }
4241 region->set_req(_prim_0_path, control()); // Not equal after all.
4242 }
4243
4244 // these are the only paths that produce 'true':
4245 phi->set_req(_prim_same_path, intcon(1));
4246 phi->set_req(_ref_subtype_path, intcon(1));
4247
4248 // pull together the cases:
4249 assert(region->req() == PATH_LIMIT, "sane region");
4250 for (uint i = 1; i < region->req(); i++) {
4251 Node* ctl = region->in(i);
4252 if (ctl == nullptr || ctl == top()) {
4253 region->set_req(i, top());
4254 phi ->set_req(i, top());
4255 } else if (phi->in(i) == nullptr) {
4256 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4257 }
4258 }
4259
4260 set_control(_gvn.transform(region));
4261 set_result(_gvn.transform(phi));
4262 return true;
4263 }
4264
4265 //---------------------generate_array_guard_common------------------------
4266 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
4267 bool obj_array, bool not_array, Node** obj) {
4268
4269 if (stopped()) {
4270 return nullptr;
4271 }
4272
4273 // If obj_array/non_array==false/false:
4274 // Branch around if the given klass is in fact an array (either obj or prim).
4275 // If obj_array/non_array==false/true:
4276 // Branch around if the given klass is not an array klass of any kind.
4277 // If obj_array/non_array==true/true:
4278 // Branch around if the kls is not an oop array (kls is int[], String, etc.)
4279 // If obj_array/non_array==true/false:
4280 // Branch around if the kls is an oop array (Object[] or subtype)
4281 //
4282 // Like generate_guard, adds a new path onto the region.
4283 jint layout_con = 0;
4284 Node* layout_val = get_layout_helper(kls, layout_con);
4285 if (layout_val == nullptr) {
4286 bool query = (obj_array
4287 ? Klass::layout_helper_is_objArray(layout_con)
4288 : Klass::layout_helper_is_array(layout_con));
4289 if (query == not_array) {
4290 return nullptr; // never a branch
4291 } else { // always a branch
4292 Node* always_branch = control();
4293 if (region != nullptr)
4294 region->add_req(always_branch);
4295 set_control(top());
4296 return always_branch;
4297 }
4298 }
4299 // Now test the correct condition.
4300 jint nval = (obj_array
4301 ? (jint)(Klass::_lh_array_tag_type_value
4302 << Klass::_lh_array_tag_shift)
4303 : Klass::_lh_neutral_value);
4304 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4305 BoolTest::mask btest = BoolTest::lt; // correct for testing is_[obj]array
4306 // invert the test if we are looking for a non-array
4307 if (not_array) btest = BoolTest(btest).negate();
4308 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4309 Node* ctrl = generate_fair_guard(bol, region);
4310 Node* is_array_ctrl = not_array ? control() : ctrl;
4311 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4312 // Keep track of the fact that 'obj' is an array to prevent
4313 // array specific accesses from floating above the guard.
4314 *obj = _gvn.transform(new CheckCastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4315 }
4316 return ctrl;
4317 }
4318
4319
4320 //-----------------------inline_native_newArray--------------------------
4321 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
4322 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4323 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4324 Node* mirror;
4325 Node* count_val;
4326 if (uninitialized) {
4327 null_check_receiver();
4328 mirror = argument(1);
4329 count_val = argument(2);
4330 } else {
4331 mirror = argument(0);
4332 count_val = argument(1);
4333 }
4334
4335 mirror = null_check(mirror);
4336 // If mirror or obj is dead, only null-path is taken.
4337 if (stopped()) return true;
4338
4339 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4340 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4341 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4359 CallJavaNode* slow_call = nullptr;
4360 if (uninitialized) {
4361 // Generate optimized virtual call (holder class 'Unsafe' is final)
4362 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4363 } else {
4364 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4365 }
4366 Node* slow_result = set_results_for_java_call(slow_call);
4367 // this->control() comes from set_results_for_java_call
4368 result_reg->set_req(_slow_path, control());
4369 result_val->set_req(_slow_path, slow_result);
4370 result_io ->set_req(_slow_path, i_o());
4371 result_mem->set_req(_slow_path, reset_memory());
4372 }
4373
4374 set_control(normal_ctl);
4375 if (!stopped()) {
4376 // Normal case: The array type has been cached in the java.lang.Class.
4377 // The following call works fine even if the array type is polymorphic.
4378 // It could be a dynamic mix of int[], boolean[], Object[], etc.
4379 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
4380 result_reg->init_req(_normal_path, control());
4381 result_val->init_req(_normal_path, obj);
4382 result_io ->init_req(_normal_path, i_o());
4383 result_mem->init_req(_normal_path, reset_memory());
4384
4385 if (uninitialized) {
4386 // Mark the allocation so that zeroing is skipped
4387 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4388 alloc->maybe_set_complete(&_gvn);
4389 }
4390 }
4391
4392 // Return the combined state.
4393 set_i_o( _gvn.transform(result_io) );
4394 set_all_memory( _gvn.transform(result_mem));
4395
4396 C->set_has_split_ifs(true); // Has chance for split-if optimization
4397 set_result(result_reg, result_val);
4398 return true;
4447 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4448 { PreserveReexecuteState preexecs(this);
4449 jvms()->set_should_reexecute(true);
4450
4451 array_type_mirror = null_check(array_type_mirror);
4452 original = null_check(original);
4453
4454 // Check if a null path was taken unconditionally.
4455 if (stopped()) return true;
4456
4457 Node* orig_length = load_array_length(original);
4458
4459 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4460 klass_node = null_check(klass_node);
4461
4462 RegionNode* bailout = new RegionNode(1);
4463 record_for_igvn(bailout);
4464
4465 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4466 // Bail out if that is so.
4467 Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
4468 if (not_objArray != nullptr) {
4469 // Improve the klass node's type from the new optimistic assumption:
4470 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4471 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
4472 Node* cast = new CastPPNode(control(), klass_node, akls);
4473 klass_node = _gvn.transform(cast);
4474 }
4475
4476 // Bail out if either start or end is negative.
4477 generate_negative_guard(start, bailout, &start);
4478 generate_negative_guard(end, bailout, &end);
4479
4480 Node* length = end;
4481 if (_gvn.type(start) != TypeInt::ZERO) {
4482 length = _gvn.transform(new SubINode(end, start));
4483 }
4484
4485 // Bail out if length is negative (i.e., if start > end).
4486 // Without this the new_array would throw
4487 // NegativeArraySizeException but IllegalArgumentException is what
4488 // should be thrown
4489 generate_negative_guard(length, bailout, &length);
4490
4491 // Bail out if start is larger than the original length
4492 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4493 generate_negative_guard(orig_tail, bailout, &orig_tail);
4494
4495 if (bailout->req() > 1) {
4496 PreserveJVMState pjvms(this);
4497 set_control(_gvn.transform(bailout));
4498 uncommon_trap(Deoptimization::Reason_intrinsic,
4499 Deoptimization::Action_maybe_recompile);
4500 }
4501
4502 if (!stopped()) {
4503 // How many elements will we copy from the original?
4504 // The answer is MinI(orig_tail, length).
4505 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4506
4507 // Generate a direct call to the right arraycopy function(s).
4508 // We know the copy is disjoint but we might not know if the
4509 // oop stores need checking.
4510 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
4530 }
4531 }
4532
4533 bool validated = false;
4534 // Reason_class_check rather than Reason_intrinsic because we
4535 // want to intrinsify even if this traps.
4536 if (!too_many_traps(Deoptimization::Reason_class_check)) {
4537 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4538
4539 if (not_subtype_ctrl != top()) {
4540 PreserveJVMState pjvms(this);
4541 set_control(not_subtype_ctrl);
4542 uncommon_trap(Deoptimization::Reason_class_check,
4543 Deoptimization::Action_make_not_entrant);
4544 assert(stopped(), "Should be stopped");
4545 }
4546 validated = true;
4547 }
4548
4549 if (!stopped()) {
4550 newcopy = new_array(klass_node, length, 0); // no arguments to push
4551
4552 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4553 load_object_klass(original), klass_node);
4554 if (!is_copyOfRange) {
4555 ac->set_copyof(validated);
4556 } else {
4557 ac->set_copyofrange(validated);
4558 }
4559 Node* n = _gvn.transform(ac);
4560 if (n == ac) {
4561 ac->connect_outputs(this);
4562 } else {
4563 assert(validated, "shouldn't transform if all arguments not validated");
4564 set_all_memory(n);
4565 }
4566 }
4567 }
4568 } // original reexecute is set back here
4569
4570 C->set_has_split_ifs(true); // Has chance for split-if optimization
4602
4603 //-----------------------generate_method_call----------------------------
4604 // Use generate_method_call to make a slow-call to the real
4605 // method if the fast path fails. An alternative would be to
4606 // use a stub like OptoRuntime::slow_arraycopy_Java.
4607 // This only works for expanding the current library call,
4608 // not another intrinsic. (E.g., don't use this for making an
4609 // arraycopy call inside of the copyOf intrinsic.)
4610 CallJavaNode*
4611 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4612 // When compiling the intrinsic method itself, do not use this technique.
4613 guarantee(callee() != C->method(), "cannot make slow-call to self");
4614
4615 ciMethod* method = callee();
4616 // ensure the JVMS we have will be correct for this call
4617 guarantee(method_id == method->intrinsic_id(), "must match");
4618
4619 const TypeFunc* tf = TypeFunc::make(method);
4620 if (res_not_null) {
4621 assert(tf->return_type() == T_OBJECT, "");
4622 const TypeTuple* range = tf->range();
4623 const Type** fields = TypeTuple::fields(range->cnt());
4624 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4625 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4626 tf = TypeFunc::make(tf->domain(), new_range);
4627 }
4628 CallJavaNode* slow_call;
4629 if (is_static) {
4630 assert(!is_virtual, "");
4631 slow_call = new CallStaticJavaNode(C, tf,
4632 SharedRuntime::get_resolve_static_call_stub(), method);
4633 } else if (is_virtual) {
4634 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4635 int vtable_index = Method::invalid_vtable_index;
4636 if (UseInlineCaches) {
4637 // Suppress the vtable call
4638 } else {
4639 // hashCode and clone are not a miranda methods,
4640 // so the vtable index is fixed.
4641 // No need to use the linkResolver to get it.
4642 vtable_index = method->vtable_index();
4643 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4644 "bad index %d", vtable_index);
4645 }
4646 slow_call = new CallDynamicJavaNode(tf,
4663 set_edges_for_java_call(slow_call);
4664 return slow_call;
4665 }
4666
4667
4668 /**
4669 * Build special case code for calls to hashCode on an object. This call may
4670 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4671 * slightly different code.
4672 */
4673 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4674 assert(is_static == callee()->is_static(), "correct intrinsic selection");
4675 assert(!(is_virtual && is_static), "either virtual, special, or static");
4676
4677 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4678
4679 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4680 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
4681 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
4682 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4683 Node* obj = nullptr;
4684 if (!is_static) {
4685 // Check for hashing null object
4686 obj = null_check_receiver();
4687 if (stopped()) return true; // unconditionally null
4688 result_reg->init_req(_null_path, top());
4689 result_val->init_req(_null_path, top());
4690 } else {
4691 // Do a null check, and return zero if null.
4692 // System.identityHashCode(null) == 0
4693 obj = argument(0);
4694 Node* null_ctl = top();
4695 obj = null_check_oop(obj, &null_ctl);
4696 result_reg->init_req(_null_path, null_ctl);
4697 result_val->init_req(_null_path, _gvn.intcon(0));
4698 }
4699
4700 // Unconditionally null? Then return right away.
4701 if (stopped()) {
4702 set_control( result_reg->in(_null_path));
4703 if (!stopped())
4704 set_result(result_val->in(_null_path));
4705 return true;
4706 }
4707
4708 // We only go to the fast case code if we pass a number of guards. The
4709 // paths which do not pass are accumulated in the slow_region.
4710 RegionNode* slow_region = new RegionNode(1);
4711 record_for_igvn(slow_region);
4712
4713 // If this is a virtual call, we generate a funny guard. We pull out
4714 // the vtable entry corresponding to hashCode() from the target object.
4715 // If the target method which we are calling happens to be the native
4716 // Object hashCode() method, we pass the guard. We do not need this
4717 // guard for non-virtual calls -- the caller is known to be the native
4718 // Object hashCode().
4719 if (is_virtual) {
4720 // After null check, get the object's klass.
4721 Node* obj_klass = load_object_klass(obj);
4722 generate_virtual_guard(obj_klass, slow_region);
4723 }
4724
4725 // Get the header out of the object, use LoadMarkNode when available
4726 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4727 // The control of the load must be null. Otherwise, the load can move before
4728 // the null check after castPP removal.
4729 Node* no_ctrl = nullptr;
4730 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4731
4732 if (!UseObjectMonitorTable) {
4733 // Test the header to see if it is safe to read w.r.t. locking.
4734 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
4735 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4736 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
4737 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
4738 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
4739
4740 generate_slow_guard(test_monitor, slow_region);
4741 }
4742
4743 // Get the hash value and check to see that it has been properly assigned.
4744 // We depend on hash_mask being at most 32 bits and avoid the use of
4745 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4746 // vm: see markWord.hpp.
4747 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
4748 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
4749 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4750 // This hack lets the hash bits live anywhere in the mark object now, as long
4751 // as the shift drops the relevant bits into the low 32 bits. Note that
4752 // Java spec says that HashCode is an int so there's no point in capturing
4753 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4781 // this->control() comes from set_results_for_java_call
4782 result_reg->init_req(_slow_path, control());
4783 result_val->init_req(_slow_path, slow_result);
4784 result_io ->set_req(_slow_path, i_o());
4785 result_mem ->set_req(_slow_path, reset_memory());
4786 }
4787
4788 // Return the combined state.
4789 set_i_o( _gvn.transform(result_io) );
4790 set_all_memory( _gvn.transform(result_mem));
4791
4792 set_result(result_reg, result_val);
4793 return true;
4794 }
4795
4796 //---------------------------inline_native_getClass----------------------------
4797 // public final native Class<?> java.lang.Object.getClass();
4798 //
4799 // Build special case code for calls to getClass on an object.
4800 bool LibraryCallKit::inline_native_getClass() {
4801 Node* obj = null_check_receiver();
4802 if (stopped()) return true;
4803 set_result(load_mirror_from_klass(load_object_klass(obj)));
4804 return true;
4805 }
4806
4807 //-----------------inline_native_Reflection_getCallerClass---------------------
4808 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4809 //
4810 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4811 //
4812 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4813 // in that it must skip particular security frames and checks for
4814 // caller sensitive methods.
4815 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4816 #ifndef PRODUCT
4817 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4818 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4819 }
4820 #endif
4821
5203 // not cloneable or finalizer => slow path to out-of-line Object.clone
5204 //
5205 // The general case has two steps, allocation and copying.
5206 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5207 //
5208 // Copying also has two cases, oop arrays and everything else.
5209 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5210 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5211 //
5212 // These steps fold up nicely if and when the cloned object's klass
5213 // can be sharply typed as an object array, a type array, or an instance.
5214 //
5215 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5216 PhiNode* result_val;
5217
5218 // Set the reexecute bit for the interpreter to reexecute
5219 // the bytecode that invokes Object.clone if deoptimization happens.
5220 { PreserveReexecuteState preexecs(this);
5221 jvms()->set_should_reexecute(true);
5222
5223 Node* obj = null_check_receiver();
5224 if (stopped()) return true;
5225
5226 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5227
5228 // If we are going to clone an instance, we need its exact type to
5229 // know the number and types of fields to convert the clone to
5230 // loads/stores. Maybe a speculative type can help us.
5231 if (!obj_type->klass_is_exact() &&
5232 obj_type->speculative_type() != nullptr &&
5233 obj_type->speculative_type()->is_instance_klass()) {
5234 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5235 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5236 !spec_ik->has_injected_fields()) {
5237 if (!obj_type->isa_instptr() ||
5238 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5239 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5240 }
5241 }
5242 }
5243
5244 // Conservatively insert a memory barrier on all memory slices.
5245 // Do not let writes into the original float below the clone.
5246 insert_mem_bar(Op_MemBarCPUOrder);
5247
5248 // paths into result_reg:
5249 enum {
5250 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5251 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5252 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5253 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5254 PATH_LIMIT
5255 };
5256 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5257 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5258 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5259 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5260 record_for_igvn(result_reg);
5261
5262 Node* obj_klass = load_object_klass(obj);
5263 Node* array_obj = obj;
5264 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5265 if (array_ctl != nullptr) {
5266 // It's an array.
5267 PreserveJVMState pjvms(this);
5268 set_control(array_ctl);
5269 Node* obj_length = load_array_length(array_obj);
5270 Node* array_size = nullptr; // Size of the array without object alignment padding.
5271 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5272
5273 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5274 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5275 // If it is an oop array, it requires very special treatment,
5276 // because gc barriers are required when accessing the array.
5277 Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5278 if (is_obja != nullptr) {
5279 PreserveJVMState pjvms2(this);
5280 set_control(is_obja);
5281 // Generate a direct call to the right arraycopy function(s).
5282 // Clones are always tightly coupled.
5283 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5284 ac->set_clone_oop_array();
5285 Node* n = _gvn.transform(ac);
5286 assert(n == ac, "cannot disappear");
5287 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5288
5289 result_reg->init_req(_objArray_path, control());
5290 result_val->init_req(_objArray_path, alloc_obj);
5291 result_i_o ->set_req(_objArray_path, i_o());
5292 result_mem ->set_req(_objArray_path, reset_memory());
5293 }
5294 }
5295 // Otherwise, there are no barriers to worry about.
5296 // (We can dispense with card marks if we know the allocation
5297 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5298 // causes the non-eden paths to take compensating steps to
5299 // simulate a fresh allocation, so that no further
5300 // card marks are required in compiled code to initialize
5301 // the object.)
5302
5303 if (!stopped()) {
5304 copy_to_clone(array_obj, alloc_obj, array_size, true);
5305
5306 // Present the results of the copy.
5307 result_reg->init_req(_array_path, control());
5308 result_val->init_req(_array_path, alloc_obj);
5309 result_i_o ->set_req(_array_path, i_o());
5310 result_mem ->set_req(_array_path, reset_memory());
5311 }
5312 }
5313
5314 // We only go to the instance fast case code if we pass a number of guards.
5315 // The paths which do not pass are accumulated in the slow_region.
5316 RegionNode* slow_region = new RegionNode(1);
5317 record_for_igvn(slow_region);
5318 if (!stopped()) {
5319 // It's an instance (we did array above). Make the slow-path tests.
5320 // If this is a virtual call, we generate a funny guard. We grab
5321 // the vtable entry corresponding to clone() from the target object.
5322 // If the target method which we are calling happens to be the
5323 // Object clone() method, we pass the guard. We do not need this
5324 // guard for non-virtual calls; the caller is known to be the native
5325 // Object clone().
5326 if (is_virtual) {
5327 generate_virtual_guard(obj_klass, slow_region);
5328 }
5329
5330 // The object must be easily cloneable and must not have a finalizer.
5331 // Both of these conditions may be checked in a single test.
5332 // We could optimize the test further, but we don't care.
5333 generate_misc_flags_guard(obj_klass,
5334 // Test both conditions:
5335 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5336 // Must be cloneable but not finalizer:
5337 KlassFlags::_misc_is_cloneable_fast,
5429 set_jvms(sfpt->jvms());
5430 _reexecute_sp = jvms()->sp();
5431
5432 return saved_jvms;
5433 }
5434 }
5435 }
5436 return nullptr;
5437 }
5438
5439 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5440 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5441 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5442 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5443 uint size = alloc->req();
5444 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5445 old_jvms->set_map(sfpt);
5446 for (uint i = 0; i < size; i++) {
5447 sfpt->init_req(i, alloc->in(i));
5448 }
5449 // re-push array length for deoptimization
5450 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
5451 old_jvms->set_sp(old_jvms->sp()+1);
5452 old_jvms->set_monoff(old_jvms->monoff()+1);
5453 old_jvms->set_scloff(old_jvms->scloff()+1);
5454 old_jvms->set_endoff(old_jvms->endoff()+1);
5455 old_jvms->set_should_reexecute(true);
5456
5457 sfpt->set_i_o(map()->i_o());
5458 sfpt->set_memory(map()->memory());
5459 sfpt->set_control(map()->control());
5460 return sfpt;
5461 }
5462
5463 // In case of a deoptimization, we restart execution at the
5464 // allocation, allocating a new array. We would leave an uninitialized
5465 // array in the heap that GCs wouldn't expect. Move the allocation
5466 // after the traps so we don't allocate the array if we
5467 // deoptimize. This is possible because tightly_coupled_allocation()
5468 // guarantees there's no observer of the allocated array at this point
5469 // and the control flow is simple enough.
5470 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5471 int saved_reexecute_sp, uint new_idx) {
5472 if (saved_jvms_before_guards != nullptr && !stopped()) {
5473 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5474
5475 assert(alloc != nullptr, "only with a tightly coupled allocation");
5476 // restore JVM state to the state at the arraycopy
5477 saved_jvms_before_guards->map()->set_control(map()->control());
5478 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5479 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5480 // If we've improved the types of some nodes (null check) while
5481 // emitting the guards, propagate them to the current state
5482 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5483 set_jvms(saved_jvms_before_guards);
5484 _reexecute_sp = saved_reexecute_sp;
5485
5486 // Remove the allocation from above the guards
5487 CallProjections callprojs;
5488 alloc->extract_projections(&callprojs, true);
5489 InitializeNode* init = alloc->initialization();
5490 Node* alloc_mem = alloc->in(TypeFunc::Memory);
5491 C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5492 init->replace_mem_projs_by(alloc_mem, C);
5493
5494 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5495 // the allocation (i.e. is only valid if the allocation succeeds):
5496 // 1) replace CastIINode with AllocateArrayNode's length here
5497 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5498 //
5499 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5500 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5501 Node* init_control = init->proj_out(TypeFunc::Control);
5502 Node* alloc_length = alloc->Ideal_length();
5503 #ifdef ASSERT
5504 Node* prev_cast = nullptr;
5505 #endif
5506 for (uint i = 0; i < init_control->outcnt(); i++) {
5507 Node* init_out = init_control->raw_out(i);
5508 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5509 #ifdef ASSERT
5510 if (prev_cast == nullptr) {
5511 prev_cast = init_out;
5513 if (prev_cast->cmp(*init_out) == false) {
5514 prev_cast->dump();
5515 init_out->dump();
5516 assert(false, "not equal CastIINode");
5517 }
5518 }
5519 #endif
5520 C->gvn_replace_by(init_out, alloc_length);
5521 }
5522 }
5523 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5524
5525 // move the allocation here (after the guards)
5526 _gvn.hash_delete(alloc);
5527 alloc->set_req(TypeFunc::Control, control());
5528 alloc->set_req(TypeFunc::I_O, i_o());
5529 Node *mem = reset_memory();
5530 set_all_memory(mem);
5531 alloc->set_req(TypeFunc::Memory, mem);
5532 set_control(init->proj_out_or_null(TypeFunc::Control));
5533 set_i_o(callprojs.fallthrough_ioproj);
5534
5535 // Update memory as done in GraphKit::set_output_for_allocation()
5536 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5537 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5538 if (ary_type->isa_aryptr() && length_type != nullptr) {
5539 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5540 }
5541 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5542 int elemidx = C->get_alias_index(telemref);
5543 // Need to properly move every memory projection for the Initialize
5544 #ifdef ASSERT
5545 int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
5546 int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
5547 #endif
5548 auto move_proj = [&](ProjNode* proj) {
5549 int alias_idx = C->get_alias_index(proj->adr_type());
5550 assert(alias_idx == Compile::AliasIdxRaw ||
5551 alias_idx == elemidx ||
5552 alias_idx == mark_idx ||
5553 alias_idx == klass_idx, "should be raw memory or array element type");
5863 top_src = src_type->isa_aryptr();
5864 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5865 src_spec = true;
5866 }
5867 if (!has_dest) {
5868 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5869 dest_type = _gvn.type(dest);
5870 top_dest = dest_type->isa_aryptr();
5871 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5872 dest_spec = true;
5873 }
5874 }
5875 }
5876
5877 if (has_src && has_dest && can_emit_guards) {
5878 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
5879 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
5880 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
5881 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
5882
5883 if (src_elem == dest_elem && src_elem == T_OBJECT) {
5884 // If both arrays are object arrays then having the exact types
5885 // for both will remove the need for a subtype check at runtime
5886 // before the call and may make it possible to pick a faster copy
5887 // routine (without a subtype check on every element)
5888 // Do we have the exact type of src?
5889 bool could_have_src = src_spec;
5890 // Do we have the exact type of dest?
5891 bool could_have_dest = dest_spec;
5892 ciKlass* src_k = nullptr;
5893 ciKlass* dest_k = nullptr;
5894 if (!src_spec) {
5895 src_k = src_type->speculative_type_not_null();
5896 if (src_k != nullptr && src_k->is_array_klass()) {
5897 could_have_src = true;
5898 }
5899 }
5900 if (!dest_spec) {
5901 dest_k = dest_type->speculative_type_not_null();
5902 if (dest_k != nullptr && dest_k->is_array_klass()) {
5903 could_have_dest = true;
5904 }
5905 }
5906 if (could_have_src && could_have_dest) {
5907 // If we can have both exact types, emit the missing guards
5908 if (could_have_src && !src_spec) {
5909 src = maybe_cast_profiled_obj(src, src_k, true);
5910 }
5911 if (could_have_dest && !dest_spec) {
5912 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5913 }
5914 }
5915 }
5916 }
5917
5918 ciMethod* trap_method = method();
5919 int trap_bci = bci();
5920 if (saved_jvms_before_guards != nullptr) {
5921 trap_method = alloc->jvms()->method();
5922 trap_bci = alloc->jvms()->bci();
5923 }
5924
5925 bool negative_length_guard_generated = false;
5926
5927 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5928 can_emit_guards &&
5929 !src->is_top() && !dest->is_top()) {
5930 // validate arguments: enables transformation the ArrayCopyNode
5931 validated = true;
5932
5933 RegionNode* slow_region = new RegionNode(1);
5934 record_for_igvn(slow_region);
5935
5936 // (1) src and dest are arrays.
5937 generate_non_array_guard(load_object_klass(src), slow_region, &src);
5938 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
5939
5940 // (2) src and dest arrays must have elements of the same BasicType
5941 // done at macro expansion or at Ideal transformation time
5942
5943 // (4) src_offset must not be negative.
5944 generate_negative_guard(src_offset, slow_region);
5945
5946 // (5) dest_offset must not be negative.
5947 generate_negative_guard(dest_offset, slow_region);
5948
5949 // (7) src_offset + length must not exceed length of src.
5950 generate_limit_guard(src_offset, length,
5951 load_array_length(src),
5952 slow_region);
5953
5954 // (8) dest_offset + length must not exceed length of dest.
5955 generate_limit_guard(dest_offset, length,
5956 load_array_length(dest),
5957 slow_region);
5958
5959 // (6) length must not be negative.
5960 // This is also checked in generate_arraycopy() during macro expansion, but
5961 // we also have to check it here for the case where the ArrayCopyNode will
5962 // be eliminated by Escape Analysis.
5963 if (EliminateAllocations) {
5964 generate_negative_guard(length, slow_region);
5965 negative_length_guard_generated = true;
5966 }
5967
5968 // (9) each element of an oop array must be assignable
5969 Node* dest_klass = load_object_klass(dest);
5970 if (src != dest) {
5971 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
5972
5973 if (not_subtype_ctrl != top()) {
5974 PreserveJVMState pjvms(this);
5975 set_control(not_subtype_ctrl);
5976 uncommon_trap(Deoptimization::Reason_intrinsic,
5977 Deoptimization::Action_make_not_entrant);
5978 assert(stopped(), "Should be stopped");
5979 }
5980 }
5981 {
5982 PreserveJVMState pjvms(this);
5983 set_control(_gvn.transform(slow_region));
5984 uncommon_trap(Deoptimization::Reason_intrinsic,
5985 Deoptimization::Action_make_not_entrant);
5986 assert(stopped(), "Should be stopped");
5987 }
5988
5989 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
5990 const Type *toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
5991 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
5992 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
5993 }
5994
5995 if (stopped()) {
5996 return true;
5997 }
5998
5999 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6000 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6001 // so the compiler has a chance to eliminate them: during macro expansion,
6002 // we have to set their control (CastPP nodes are eliminated).
6003 load_object_klass(src), load_object_klass(dest),
6004 load_array_length(src), load_array_length(dest));
6005
6006 ac->set_arraycopy(validated);
6007
6008 Node* n = _gvn.transform(ac);
6009 if (n == ac) {
6010 ac->connect_outputs(this);
6011 } else {
6012 assert(validated, "shouldn't transform if all arguments not validated");
6013 set_all_memory(n);
6014 }
6015 clear_upper_avx();
6016
6017
6018 return true;
6019 }
6020
6021
6022 // Helper function which determines if an arraycopy immediately follows
6023 // an allocation, with no intervening tests or other escapes for the object.
|
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:
2289 case vmIntrinsics::_remainderUnsigned_l: {
2290 zero_check_long(argument(2));
2291 // Compile-time detect of null-exception
2292 if (stopped()) {
2293 return true; // keep the graph constructed so far
2294 }
2295 n = new UModLNode(control(), argument(0), argument(2));
2296 break;
2297 }
2298 default: fatal_unexpected_iid(id); break;
2299 }
2300 set_result(_gvn.transform(n));
2301 return true;
2302 }
2303
2304 //----------------------------inline_unsafe_access----------------------------
2305
2306 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2307 // Attempt to infer a sharper value type from the offset and base type.
2308 ciKlass* sharpened_klass = nullptr;
2309 bool null_free = false;
2310
2311 // See if it is an instance field, with an object type.
2312 if (alias_type->field() != nullptr) {
2313 if (alias_type->field()->type()->is_klass()) {
2314 sharpened_klass = alias_type->field()->type()->as_klass();
2315 null_free = alias_type->field()->is_null_free();
2316 }
2317 }
2318
2319 const TypeOopPtr* result = nullptr;
2320 // See if it is a narrow oop array.
2321 if (adr_type->isa_aryptr()) {
2322 if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2323 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2324 null_free = adr_type->is_aryptr()->is_null_free();
2325 if (elem_type != nullptr && elem_type->is_loaded()) {
2326 // Sharpen the value type.
2327 result = elem_type;
2328 }
2329 }
2330 }
2331
2332 // The sharpened class might be unloaded if there is no class loader
2333 // contraint in place.
2334 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2335 // Sharpen the value type.
2336 result = TypeOopPtr::make_from_klass(sharpened_klass);
2337 if (null_free) {
2338 result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2339 }
2340 }
2341 if (result != nullptr) {
2342 #ifndef PRODUCT
2343 if (C->print_intrinsics() || C->print_inlining()) {
2344 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2345 tty->print(" sharpened value: "); result->dump(); tty->cr();
2346 }
2347 #endif
2348 }
2349 return result;
2350 }
2351
2352 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2353 switch (kind) {
2354 case Relaxed:
2355 return MO_UNORDERED;
2356 case Opaque:
2357 return MO_RELAXED;
2358 case Acquire:
2359 return MO_ACQUIRE;
2407 #endif // ASSERT
2408 }
2409 #endif //PRODUCT
2410
2411 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2412
2413 Node* receiver = argument(0); // type: oop
2414
2415 // Build address expression.
2416 Node* heap_base_oop = top();
2417
2418 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2419 Node* base = argument(1); // type: oop
2420 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2421 Node* offset = argument(2); // type: long
2422 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2423 // to be plain byte offsets, which are also the same as those accepted
2424 // by oopDesc::field_addr.
2425 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2426 "fieldOffset must be byte-scaled");
2427
2428 if (base->is_InlineType()) {
2429 assert(!is_store, "InlineTypeNodes are non-larval value objects");
2430 InlineTypeNode* vt = base->as_InlineType();
2431 if (offset->is_Con()) {
2432 long off = find_long_con(offset, 0);
2433 ciInlineKlass* vk = vt->type()->inline_klass();
2434 if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2435 return false;
2436 }
2437
2438 ciField* field = vk->get_non_flat_field_by_offset(off);
2439 if (field != nullptr) {
2440 BasicType bt = type2field[field->type()->basic_type()];
2441 if (bt == T_ARRAY || bt == T_NARROWOOP) {
2442 bt = T_OBJECT;
2443 }
2444 if (bt == type && !field->is_flat()) {
2445 Node* value = vt->field_value_by_offset(off, false);
2446 const Type* value_type = _gvn.type(value);
2447 if (value->is_InlineType()) {
2448 value = value->as_InlineType()->adjust_scalarization_depth(this);
2449 } else if (value_type->is_inlinetypeptr()) {
2450 value = InlineTypeNode::make_from_oop(this, value, value_type->inline_klass());
2451 }
2452 set_result(value);
2453 return true;
2454 }
2455 }
2456 }
2457 {
2458 // Re-execute the unsafe access if allocation triggers deoptimization.
2459 PreserveReexecuteState preexecs(this);
2460 jvms()->set_should_reexecute(true);
2461 vt = vt->buffer(this);
2462 }
2463 base = vt->get_oop();
2464 }
2465
2466 // 32-bit machines ignore the high half!
2467 offset = ConvL2X(offset);
2468
2469 // Save state and restore on bailout
2470 SavedState old_state(this);
2471
2472 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2473 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2474
2475 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2476 if (type != T_OBJECT) {
2477 decorators |= IN_NATIVE; // off-heap primitive access
2478 } else {
2479 return false; // off-heap oop accesses are not supported
2480 }
2481 } else {
2482 heap_base_oop = base; // on-heap or mixed access
2483 }
2484
2485 // Can base be null? Otherwise, always on-heap access.
2489 decorators |= IN_HEAP;
2490 }
2491
2492 Node* val = is_store ? argument(4) : nullptr;
2493
2494 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2495 if (adr_type == TypePtr::NULL_PTR) {
2496 return false; // off-heap access with zero address
2497 }
2498
2499 // Try to categorize the address.
2500 Compile::AliasType* alias_type = C->alias_type(adr_type);
2501 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2502
2503 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2504 alias_type->adr_type() == TypeAryPtr::RANGE) {
2505 return false; // not supported
2506 }
2507
2508 bool mismatched = false;
2509 BasicType bt = T_ILLEGAL;
2510 ciField* field = nullptr;
2511 if (adr_type->isa_instptr()) {
2512 const TypeInstPtr* instptr = adr_type->is_instptr();
2513 ciInstanceKlass* k = instptr->instance_klass();
2514 int off = instptr->offset();
2515 if (instptr->const_oop() != nullptr &&
2516 k == ciEnv::current()->Class_klass() &&
2517 instptr->offset() >= (k->size_helper() * wordSize)) {
2518 k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2519 field = k->get_field_by_offset(off, true);
2520 } else {
2521 field = k->get_non_flat_field_by_offset(off);
2522 }
2523 if (field != nullptr) {
2524 bt = type2field[field->type()->basic_type()];
2525 }
2526 if (bt != alias_type->basic_type()) {
2527 // Type mismatch. Is it an access to a nested flat field?
2528 field = k->get_field_by_offset(off, false);
2529 if (field != nullptr) {
2530 bt = type2field[field->type()->basic_type()];
2531 }
2532 }
2533 assert(bt == alias_type->basic_type(), "should match");
2534 } else {
2535 bt = alias_type->basic_type();
2536 }
2537
2538 if (bt != T_ILLEGAL) {
2539 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2540 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2541 // Alias type doesn't differentiate between byte[] and boolean[]).
2542 // Use address type to get the element type.
2543 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2544 }
2545 if (is_reference_type(bt, true)) {
2546 // accessing an array field with getReference is not a mismatch
2547 bt = T_OBJECT;
2548 }
2549 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2550 // Don't intrinsify mismatched object accesses
2551 return false;
2552 }
2553 mismatched = (bt != type);
2554 } else if (alias_type->adr_type()->isa_oopptr()) {
2555 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2556 }
2557
2558 old_state.discard();
2559 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2560
2561 if (mismatched) {
2562 decorators |= C2_MISMATCHED;
2563 }
2564
2565 // First guess at the value type.
2566 const Type *value_type = Type::get_const_basic_type(type);
2567
2568 // Figure out the memory ordering.
2569 decorators |= mo_decorator_for_access_kind(kind);
2570
2571 if (!is_store) {
2572 if (type == T_OBJECT) {
2573 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2574 if (tjp != nullptr) {
2575 value_type = tjp;
2576 }
2577 }
2578 }
2579
2580 receiver = null_check(receiver);
2581 if (stopped()) {
2582 return true;
2583 }
2584 // Heap pointers get a null-check from the interpreter,
2585 // as a courtesy. However, this is not guaranteed by Unsafe,
2586 // and it is not possible to fully distinguish unintended nulls
2587 // from intended ones in this API.
2588
2589 if (!is_store) {
2590 Node* p = nullptr;
2591 // Try to constant fold a load from a constant field
2592
2593 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2594 // final or stable field
2595 p = make_constant_from_field(field, heap_base_oop);
2596 }
2597
2598 if (p == nullptr) { // Could not constant fold the load
2599 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2600 const TypeOopPtr* ptr = value_type->make_oopptr();
2601 if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2602 // Load a non-flattened inline type from memory
2603 p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2604 }
2605 // Normalize the value returned by getBoolean in the following cases
2606 if (type == T_BOOLEAN &&
2607 (mismatched ||
2608 heap_base_oop == top() || // - heap_base_oop is null or
2609 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2610 // and the unsafe access is made to large offset
2611 // (i.e., larger than the maximum offset necessary for any
2612 // field access)
2613 ) {
2614 IdealKit ideal = IdealKit(this);
2615 #define __ ideal.
2616 IdealVariable normalized_result(ideal);
2617 __ declarations_done();
2618 __ set(normalized_result, p);
2619 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2620 __ set(normalized_result, ideal.ConI(1));
2621 ideal.end_if();
2622 final_sync(ideal);
2623 p = __ value(normalized_result);
2624 #undef __
2628 p = gvn().transform(new CastP2XNode(nullptr, p));
2629 p = ConvX2UL(p);
2630 }
2631 // The load node has the control of the preceding MemBarCPUOrder. All
2632 // following nodes will have the control of the MemBarCPUOrder inserted at
2633 // the end of this method. So, pushing the load onto the stack at a later
2634 // point is fine.
2635 set_result(p);
2636 } else {
2637 if (bt == T_ADDRESS) {
2638 // Repackage the long as a pointer.
2639 val = ConvL2X(val);
2640 val = gvn().transform(new CastX2PNode(val));
2641 }
2642 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2643 }
2644
2645 return true;
2646 }
2647
2648 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2649 #ifdef ASSERT
2650 {
2651 ResourceMark rm;
2652 // Check the signatures.
2653 ciSignature* sig = callee()->signature();
2654 assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2655 assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2656 assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2657 assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2658 if (is_store) {
2659 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2660 assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2661 assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2662 } else {
2663 assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2664 assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2665 }
2666 }
2667 #endif // ASSERT
2668
2669 assert(kind == Relaxed, "Only plain accesses for now");
2670 if (callee()->is_static()) {
2671 // caller must have the capability!
2672 return false;
2673 }
2674 C->set_has_unsafe_access(true);
2675
2676 const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2677 if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2678 // parameter valueType is not a constant
2679 return false;
2680 }
2681 ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2682 if (!mirror_type->is_inlinetype()) {
2683 // Dead code
2684 return false;
2685 }
2686 ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2687
2688 const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2689 if (layout_type == nullptr || !layout_type->is_con()) {
2690 // parameter layoutKind is not a constant
2691 return false;
2692 }
2693 assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2694 layout_type->get_con() < static_cast<int>(LayoutKind::UNKNOWN),
2695 "invalid layoutKind %d", layout_type->get_con());
2696 LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2697 assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2698 layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2699 "unexpected layoutKind %d", layout_type->get_con());
2700
2701 null_check(argument(0));
2702 if (stopped()) {
2703 return true;
2704 }
2705
2706 Node* base = must_be_not_null(argument(1), true);
2707 Node* offset = argument(2);
2708 const Type* base_type = _gvn.type(base);
2709
2710 Node* ptr;
2711 bool immutable_memory = false;
2712 DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2713 if (base_type->isa_instptr()) {
2714 const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2715 if (offset_type == nullptr || !offset_type->is_con()) {
2716 // Offset into a non-array should be a constant
2717 decorators |= C2_MISMATCHED;
2718 } else {
2719 int offset_con = checked_cast<int>(offset_type->get_con());
2720 ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2721 ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2722 if (field == nullptr) {
2723 assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2724 decorators |= C2_MISMATCHED;
2725 } else {
2726 assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2727 offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2728 immutable_memory = field->is_strict() && field->is_final();
2729
2730 if (base->is_InlineType()) {
2731 assert(!is_store, "Cannot store into a non-larval value object");
2732 set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2733 return true;
2734 }
2735 }
2736 }
2737
2738 if (base->is_InlineType()) {
2739 assert(!is_store, "Cannot store into a non-larval value object");
2740 base = base->as_InlineType()->buffer(this, true);
2741 }
2742 ptr = basic_plus_adr(base, ConvL2X(offset));
2743 } else if (base_type->isa_aryptr()) {
2744 decorators |= IS_ARRAY;
2745 if (layout == LayoutKind::REFERENCE) {
2746 if (!base_type->is_aryptr()->is_not_flat()) {
2747 const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2748 // TODO 8350865 This should be a CheckCastPP, can we add a test?
2749 Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2750 replace_in_map(base, new_base);
2751 base = new_base;
2752 }
2753 ptr = basic_plus_adr(base, ConvL2X(offset));
2754 } else {
2755 if (UseArrayFlattening) {
2756 // Flat array must have an exact type
2757 bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2758 bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2759 Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2760 replace_in_map(base, new_base);
2761 base = new_base;
2762 ptr = basic_plus_adr(base, ConvL2X(offset));
2763 const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2764 if (ptr_type->field_offset().get() != 0) {
2765 // TODO 8350865 This should be a CheckCastPP, can we add a test?
2766 ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2767 }
2768 } else {
2769 uncommon_trap(Deoptimization::Reason_intrinsic,
2770 Deoptimization::Action_none);
2771 return true;
2772 }
2773 }
2774 } else {
2775 decorators |= C2_MISMATCHED;
2776 ptr = basic_plus_adr(base, ConvL2X(offset));
2777 }
2778
2779 if (is_store) {
2780 Node* value = argument(6);
2781 const Type* value_type = _gvn.type(value);
2782 if (!value_type->is_inlinetypeptr()) {
2783 value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2784 Node* new_value = _gvn.transform(new CheckCastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2785 new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2786 replace_in_map(value, new_value);
2787 value = new_value;
2788 }
2789
2790 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());
2791 if (layout == LayoutKind::REFERENCE) {
2792 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2793 access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2794 } else {
2795 bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2796 bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2797 value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2798 }
2799
2800 return true;
2801 } else {
2802 decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2803 InlineTypeNode* result;
2804 if (layout == LayoutKind::REFERENCE) {
2805 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2806 Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2807 result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2808 } else {
2809 bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2810 bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2811 result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2812 }
2813
2814 set_result(result);
2815 return true;
2816 }
2817 }
2818
2819 //----------------------------inline_unsafe_load_store----------------------------
2820 // This method serves a couple of different customers (depending on LoadStoreKind):
2821 //
2822 // LS_cmp_swap:
2823 //
2824 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2825 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2826 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2827 //
2828 // LS_cmp_swap_weak:
2829 //
2830 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2831 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2832 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2833 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2834 //
2835 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2836 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2837 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2838 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
3001 }
3002 case LS_cmp_swap:
3003 case LS_cmp_swap_weak:
3004 case LS_get_add:
3005 break;
3006 default:
3007 ShouldNotReachHere();
3008 }
3009
3010 // Null check receiver.
3011 receiver = null_check(receiver);
3012 if (stopped()) {
3013 return true;
3014 }
3015
3016 int alias_idx = C->get_alias_index(adr_type);
3017
3018 if (is_reference_type(type)) {
3019 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3020
3021 if (oldval != nullptr && oldval->is_InlineType()) {
3022 // Re-execute the unsafe access if allocation triggers deoptimization.
3023 PreserveReexecuteState preexecs(this);
3024 jvms()->set_should_reexecute(true);
3025 oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3026 }
3027 if (newval != nullptr && newval->is_InlineType()) {
3028 // Re-execute the unsafe access if allocation triggers deoptimization.
3029 PreserveReexecuteState preexecs(this);
3030 jvms()->set_should_reexecute(true);
3031 newval = newval->as_InlineType()->buffer(this)->get_oop();
3032 }
3033
3034 // Transformation of a value which could be null pointer (CastPP #null)
3035 // could be delayed during Parse (for example, in adjust_map_after_if()).
3036 // Execute transformation here to avoid barrier generation in such case.
3037 if (_gvn.type(newval) == TypePtr::NULL_PTR)
3038 newval = _gvn.makecon(TypePtr::NULL_PTR);
3039
3040 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3041 // Refine the value to a null constant, when it is known to be null
3042 oldval = _gvn.makecon(TypePtr::NULL_PTR);
3043 }
3044 }
3045
3046 Node* result = nullptr;
3047 switch (kind) {
3048 case LS_cmp_exchange: {
3049 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3050 oldval, newval, value_type, type, decorators);
3051 break;
3052 }
3053 case LS_cmp_swap_weak:
3082 insert_mem_bar(Op_MemBarCPUOrder);
3083 switch(id) {
3084 case vmIntrinsics::_loadFence:
3085 insert_mem_bar(Op_LoadFence);
3086 return true;
3087 case vmIntrinsics::_storeFence:
3088 insert_mem_bar(Op_StoreFence);
3089 return true;
3090 case vmIntrinsics::_storeStoreFence:
3091 insert_mem_bar(Op_StoreStoreFence);
3092 return true;
3093 case vmIntrinsics::_fullFence:
3094 insert_mem_bar(Op_MemBarFull);
3095 return true;
3096 default:
3097 fatal_unexpected_iid(id);
3098 return false;
3099 }
3100 }
3101
3102 // private native int arrayInstanceBaseOffset0(Object[] array);
3103 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3104 Node* array = argument(1);
3105 Node* klass_node = load_object_klass(array);
3106
3107 jint layout_con = Klass::_lh_neutral_value;
3108 Node* layout_val = get_layout_helper(klass_node, layout_con);
3109 int layout_is_con = (layout_val == nullptr);
3110
3111 Node* header_size = nullptr;
3112 if (layout_is_con) {
3113 int hsize = Klass::layout_helper_header_size(layout_con);
3114 header_size = intcon(hsize);
3115 } else {
3116 Node* hss = intcon(Klass::_lh_header_size_shift);
3117 Node* hsm = intcon(Klass::_lh_header_size_mask);
3118 header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3119 header_size = _gvn.transform(new AndINode(header_size, hsm));
3120 }
3121 set_result(header_size);
3122 return true;
3123 }
3124
3125 // private native int arrayInstanceIndexScale0(Object[] array);
3126 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3127 Node* array = argument(1);
3128 Node* klass_node = load_object_klass(array);
3129
3130 jint layout_con = Klass::_lh_neutral_value;
3131 Node* layout_val = get_layout_helper(klass_node, layout_con);
3132 int layout_is_con = (layout_val == nullptr);
3133
3134 Node* element_size = nullptr;
3135 if (layout_is_con) {
3136 int log_element_size = Klass::layout_helper_log2_element_size(layout_con);
3137 int elem_size = 1 << log_element_size;
3138 element_size = intcon(elem_size);
3139 } else {
3140 Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3141 Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3142 Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3143 log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3144 element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3145 }
3146 set_result(element_size);
3147 return true;
3148 }
3149
3150 // private native int arrayLayout0(Object[] array);
3151 bool LibraryCallKit::inline_arrayLayout() {
3152 RegionNode* region = new RegionNode(2);
3153 Node* phi = new PhiNode(region, TypeInt::POS);
3154
3155 Node* array = argument(1);
3156 Node* klass_node = load_object_klass(array);
3157 generate_refArray_guard(klass_node, region);
3158 if (region->req() == 3) {
3159 phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3160 }
3161
3162 int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3163 Node* layout_kind_addr = basic_plus_adr(top(), klass_node, layout_kind_offset);
3164 Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3165
3166 region->init_req(1, control());
3167 phi->init_req(1, layout_kind);
3168
3169 set_control(_gvn.transform(region));
3170 set_result(_gvn.transform(phi));
3171 return true;
3172 }
3173
3174 // private native int[] getFieldMap0(Class <?> c);
3175 // int offset = c._klass._acmp_maps_offset;
3176 // return (int[])c.obj_field(offset);
3177 bool LibraryCallKit::inline_getFieldMap() {
3178 Node* mirror = argument(1);
3179 Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3180
3181 int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3182 Node* field_map_offset_addr = basic_plus_adr(top(), klass, field_map_offset_offset);
3183 Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3184 field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3185
3186 Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3187 const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3188 // TODO 8350865 Remove this
3189 val_type = val_type->cast_to_not_flat(true)->cast_to_not_null_free(true);
3190 Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3191
3192 set_result(map);
3193 return true;
3194 }
3195
3196 bool LibraryCallKit::inline_onspinwait() {
3197 insert_mem_bar(Op_OnSpinWait);
3198 return true;
3199 }
3200
3201 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3202 if (!kls->is_Con()) {
3203 return true;
3204 }
3205 const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3206 if (klsptr == nullptr) {
3207 return true;
3208 }
3209 ciInstanceKlass* ik = klsptr->instance_klass();
3210 // don't need a guard for a klass that is already initialized
3211 return !ik->is_initialized();
3212 }
3213
3214 //----------------------------inline_unsafe_writeback0-------------------------
3215 // public native void Unsafe.writeback0(long address)
3294 Deoptimization::Action_make_not_entrant);
3295 }
3296 if (stopped()) {
3297 return true;
3298 }
3299 #endif //INCLUDE_JVMTI
3300
3301 Node* test = nullptr;
3302 if (LibraryCallKit::klass_needs_init_guard(kls)) {
3303 // Note: The argument might still be an illegal value like
3304 // Serializable.class or Object[].class. The runtime will handle it.
3305 // But we must make an explicit check for initialization.
3306 Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
3307 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3308 // can generate code to load it as unsigned byte.
3309 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3310 Node* bits = intcon(InstanceKlass::fully_initialized);
3311 test = _gvn.transform(new SubINode(inst, bits));
3312 // The 'test' is non-zero if we need to take a slow path.
3313 }
3314 Node* obj = new_instance(kls, test);
3315 set_result(obj);
3316 return true;
3317 }
3318
3319 //------------------------inline_native_time_funcs--------------
3320 // inline code for System.currentTimeMillis() and System.nanoTime()
3321 // these have the same type and signature
3322 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3323 const TypeFunc* tf = OptoRuntime::void_long_Type();
3324 const TypePtr* no_memory_effects = nullptr;
3325 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3326 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3327 #ifdef ASSERT
3328 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3329 assert(value_top == top(), "second value must be top");
3330 #endif
3331 set_result(value);
3332 return true;
3333 }
4109 Node* arr = argument(1);
4110 Node* thread = _gvn.transform(new ThreadLocalNode());
4111 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
4112 Node* thread_obj_handle
4113 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4114 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4115 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4116
4117 // Change the _monitor_owner_id of the JavaThread
4118 Node* tid = load_field_from_object(arr, "tid", "J");
4119 Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4120 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4121
4122 JFR_ONLY(extend_setCurrentThread(thread, arr);)
4123 return true;
4124 }
4125
4126 const Type* LibraryCallKit::scopedValueCache_type() {
4127 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4128 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4129 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4130
4131 // Because we create the scopedValue cache lazily we have to make the
4132 // type of the result BotPTR.
4133 bool xk = etype->klass_is_exact();
4134 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4135 return objects_type;
4136 }
4137
4138 Node* LibraryCallKit::scopedValueCache_helper() {
4139 Node* thread = _gvn.transform(new ThreadLocalNode());
4140 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
4141 // We cannot use immutable_memory() because we might flip onto a
4142 // different carrier thread, at which point we'll need to use that
4143 // carrier thread's cache.
4144 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4145 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4146 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4147 }
4148
4149 //------------------------inline_native_scopedValueCache------------------
4150 bool LibraryCallKit::inline_native_scopedValueCache() {
4151 Node* cache_obj_handle = scopedValueCache_helper();
4152 const Type* objects_type = scopedValueCache_type();
4153 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4154
4290 }
4291 return kls;
4292 }
4293
4294 //--------------------(inline_native_Class_query helpers)---------------------
4295 // Use this for JVM_ACC_INTERFACE.
4296 // Fall through if (mods & mask) == bits, take the guard otherwise.
4297 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4298 ByteSize offset, const Type* type, BasicType bt) {
4299 // Branch around if the given klass has the given modifier bit set.
4300 // Like generate_guard, adds a new path onto the region.
4301 Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
4302 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4303 Node* mask = intcon(modifier_mask);
4304 Node* bits = intcon(modifier_bits);
4305 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4306 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4307 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4308 return generate_fair_guard(bol, region);
4309 }
4310
4311 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4312 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4313 InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4314 }
4315
4316 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4317 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4318 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4319 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4320 }
4321
4322 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4323 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4324 }
4325
4326 //-------------------------inline_native_Class_query-------------------
4327 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4328 const Type* return_type = TypeInt::BOOL;
4329 Node* prim_return_value = top(); // what happens if it's a primitive class?
4330 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4416
4417
4418 case vmIntrinsics::_getSuperclass:
4419 // The rules here are somewhat unfortunate, but we can still do better
4420 // with random logic than with a JNI call.
4421 // Interfaces store null or Object as _super, but must report null.
4422 // Arrays store an intermediate super as _super, but must report Object.
4423 // Other types can report the actual _super.
4424 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4425 if (generate_array_guard(kls, region) != nullptr) {
4426 // A guard was added. If the guard is taken, it was an array.
4427 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4428 }
4429 // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4430 // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4431 if (generate_interface_guard(kls, region) != nullptr) {
4432 // A guard was added. If the guard is taken, it was an interface.
4433 phi->add_req(null());
4434 }
4435 // If we fall through, it's a plain class. Get its _super.
4436 if (!stopped()) {
4437 p = basic_plus_adr(top(), kls, in_bytes(Klass::super_offset()));
4438 kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4439 null_ctl = top();
4440 kls = null_check_oop(kls, &null_ctl);
4441 if (null_ctl != top()) {
4442 // If the guard is taken, Object.superClass is null (both klass and mirror).
4443 region->add_req(null_ctl);
4444 phi ->add_req(null());
4445 }
4446 if (!stopped()) {
4447 query_value = load_mirror_from_klass(kls);
4448 }
4449 }
4450 break;
4451
4452 default:
4453 fatal_unexpected_iid(id);
4454 break;
4455 }
4456
4457 // Fall-through is the normal case of a query to a real class.
4458 phi->init_req(1, query_value);
4459 region->init_req(1, control());
4460
4461 C->set_has_split_ifs(true); // Has chance for split-if optimization
4462 set_result(region, phi);
4463 return true;
4464 }
4465
4466
4467 //-------------------------inline_Class_cast-------------------
4468 bool LibraryCallKit::inline_Class_cast() {
4469 Node* mirror = argument(0); // Class
4470 Node* obj = argument(1);
4471 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4472 if (mirror_con == nullptr) {
4473 return false; // dead path (mirror->is_top()).
4474 }
4475 if (obj == nullptr || obj->is_top()) {
4476 return false; // dead path
4477 }
4478 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4479
4480 // First, see if Class.cast() can be folded statically.
4481 // java_mirror_type() returns non-null for compile-time Class constants.
4482 ciType* tm = mirror_con->java_mirror_type();
4483 if (tm != nullptr && tm->is_klass() &&
4484 tp != nullptr) {
4485 if (!tp->is_loaded()) {
4486 // Don't use intrinsic when class is not loaded.
4487 return false;
4488 } else {
4489 const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4490 int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4491 if (static_res == Compile::SSC_always_true) {
4492 // isInstance() is true - fold the code.
4493 set_result(obj);
4494 return true;
4495 } else if (static_res == Compile::SSC_always_false) {
4496 // Don't use intrinsic, have to throw ClassCastException.
4497 // If the reference is null, the non-intrinsic bytecode will
4498 // be optimized appropriately.
4499 return false;
4500 }
4501 }
4502 }
4503
4504 // Bailout intrinsic and do normal inlining if exception path is frequent.
4505 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4506 return false;
4507 }
4508
4509 // Generate dynamic checks.
4510 // Class.cast() is java implementation of _checkcast bytecode.
4511 // Do checkcast (Parse::do_checkcast()) optimizations here.
4512
4513 mirror = null_check(mirror);
4514 // If mirror is dead, only null-path is taken.
4515 if (stopped()) {
4516 return true;
4517 }
4518
4519 // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4520 enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4521 RegionNode* region = new RegionNode(PATH_LIMIT);
4522 record_for_igvn(region);
4523
4524 // Now load the mirror's klass metaobject, and null-check it.
4525 // If kls is null, we have a primitive mirror and
4526 // nothing is an instance of a primitive type.
4527 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4528
4529 Node* res = top();
4530 Node* io = i_o();
4531 Node* mem = merged_memory();
4532 SafePointNode* new_cast_failure_map = nullptr;
4533
4534 if (!stopped()) {
4535
4536 Node* bad_type_ctrl = top();
4537 // Do checkcast optimizations.
4538 res = gen_checkcast(obj, kls, &bad_type_ctrl, &new_cast_failure_map);
4539 region->init_req(_bad_type_path, bad_type_ctrl);
4540 }
4541 if (region->in(_prim_path) != top() ||
4542 region->in(_bad_type_path) != top() ||
4543 region->in(_npe_path) != top()) {
4544 // Let Interpreter throw ClassCastException.
4545 PreserveJVMState pjvms(this);
4546 if (new_cast_failure_map != nullptr) {
4547 // The current map on the success path could have been modified. Use the dedicated failure path map.
4548 set_map(new_cast_failure_map);
4549 }
4550 set_control(_gvn.transform(region));
4551 // Set IO and memory because gen_checkcast may override them when buffering inline types
4552 set_i_o(io);
4553 set_all_memory(mem);
4554 uncommon_trap(Deoptimization::Reason_intrinsic,
4555 Deoptimization::Action_maybe_recompile);
4556 }
4557 if (!stopped()) {
4558 set_result(res);
4559 }
4560 return true;
4561 }
4562
4563
4564 //--------------------------inline_native_subtype_check------------------------
4565 // This intrinsic takes the JNI calls out of the heart of
4566 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4567 bool LibraryCallKit::inline_native_subtype_check() {
4568 // Pull both arguments off the stack.
4569 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4570 args[0] = argument(0);
4571 args[1] = argument(1);
4572 Node* klasses[2]; // corresponding Klasses: superk, subk
4573 klasses[0] = klasses[1] = top();
4574
4575 enum {
4576 // A full decision tree on {superc is prim, subc is prim}:
4577 _prim_0_path = 1, // {P,N} => false
4578 // {P,P} & superc!=subc => false
4579 _prim_same_path, // {P,P} & superc==subc => true
4580 _prim_1_path, // {N,P} => false
4581 _ref_subtype_path, // {N,N} & subtype check wins => true
4582 _both_ref_path, // {N,N} & subtype check loses => false
4583 PATH_LIMIT
4584 };
4585
4586 RegionNode* region = new RegionNode(PATH_LIMIT);
4587 RegionNode* prim_region = new RegionNode(2);
4588 Node* phi = new PhiNode(region, TypeInt::BOOL);
4589 record_for_igvn(region);
4590 record_for_igvn(prim_region);
4591
4592 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4593 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4594 int class_klass_offset = java_lang_Class::klass_offset();
4595
4596 // First null-check both mirrors and load each mirror's klass metaobject.
4597 int which_arg;
4598 for (which_arg = 0; which_arg <= 1; which_arg++) {
4599 Node* arg = args[which_arg];
4600 arg = null_check(arg);
4601 if (stopped()) break;
4602 args[which_arg] = arg;
4603
4604 Node* p = basic_plus_adr(arg, class_klass_offset);
4605 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4606 klasses[which_arg] = _gvn.transform(kls);
4607 }
4608
4609 // Having loaded both klasses, test each for null.
4610 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4611 for (which_arg = 0; which_arg <= 1; which_arg++) {
4612 Node* kls = klasses[which_arg];
4613 Node* null_ctl = top();
4614 kls = null_check_oop(kls, &null_ctl, never_see_null);
4615 if (which_arg == 0) {
4616 prim_region->init_req(1, null_ctl);
4617 } else {
4618 region->init_req(_prim_1_path, null_ctl);
4619 }
4620 if (stopped()) break;
4621 klasses[which_arg] = kls;
4622 }
4623
4624 if (!stopped()) {
4625 // now we have two reference types, in klasses[0..1]
4626 Node* subk = klasses[1]; // the argument to isAssignableFrom
4627 Node* superk = klasses[0]; // the receiver
4628 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4629 region->set_req(_ref_subtype_path, control());
4630 }
4631
4632 // If both operands are primitive (both klasses null), then
4633 // we must return true when they are identical primitives.
4634 // It is convenient to test this after the first null klass check.
4635 // This path is also used if superc is a value mirror.
4636 set_control(_gvn.transform(prim_region));
4637 if (!stopped()) {
4638 // Since superc is primitive, make a guard for the superc==subc case.
4639 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4640 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4641 generate_fair_guard(bol_eq, region);
4642 if (region->req() == PATH_LIMIT+1) {
4643 // A guard was added. If the added guard is taken, superc==subc.
4644 region->swap_edges(PATH_LIMIT, _prim_same_path);
4645 region->del_req(PATH_LIMIT);
4646 }
4647 region->set_req(_prim_0_path, control()); // Not equal after all.
4648 }
4649
4650 // these are the only paths that produce 'true':
4651 phi->set_req(_prim_same_path, intcon(1));
4652 phi->set_req(_ref_subtype_path, intcon(1));
4653
4654 // pull together the cases:
4655 assert(region->req() == PATH_LIMIT, "sane region");
4656 for (uint i = 1; i < region->req(); i++) {
4657 Node* ctl = region->in(i);
4658 if (ctl == nullptr || ctl == top()) {
4659 region->set_req(i, top());
4660 phi ->set_req(i, top());
4661 } else if (phi->in(i) == nullptr) {
4662 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4663 }
4664 }
4665
4666 set_control(_gvn.transform(region));
4667 set_result(_gvn.transform(phi));
4668 return true;
4669 }
4670
4671 //---------------------generate_array_guard_common------------------------
4672 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4673
4674 if (stopped()) {
4675 return nullptr;
4676 }
4677
4678 // Like generate_guard, adds a new path onto the region.
4679 jint layout_con = 0;
4680 Node* layout_val = get_layout_helper(kls, layout_con);
4681 if (layout_val == nullptr) {
4682 bool query = 0;
4683 switch(kind) {
4684 case RefArray: query = Klass::layout_helper_is_refArray(layout_con); break;
4685 case NonRefArray: query = !Klass::layout_helper_is_refArray(layout_con); break;
4686 case TypeArray: query = Klass::layout_helper_is_typeArray(layout_con); break;
4687 case AnyArray: query = Klass::layout_helper_is_array(layout_con); break;
4688 case NonArray: query = !Klass::layout_helper_is_array(layout_con); break;
4689 default:
4690 ShouldNotReachHere();
4691 }
4692 if (!query) {
4693 return nullptr; // never a branch
4694 } else { // always a branch
4695 Node* always_branch = control();
4696 if (region != nullptr)
4697 region->add_req(always_branch);
4698 set_control(top());
4699 return always_branch;
4700 }
4701 }
4702 unsigned int value = 0;
4703 BoolTest::mask btest = BoolTest::illegal;
4704 switch(kind) {
4705 case RefArray:
4706 case NonRefArray: {
4707 value = Klass::_lh_array_tag_ref_value;
4708 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4709 btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4710 break;
4711 }
4712 case TypeArray: {
4713 value = Klass::_lh_array_tag_type_value;
4714 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4715 btest = BoolTest::eq;
4716 break;
4717 }
4718 case AnyArray: value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4719 case NonArray: value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4720 default:
4721 ShouldNotReachHere();
4722 }
4723 // Now test the correct condition.
4724 jint nval = (jint)value;
4725 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4726 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4727 Node* ctrl = generate_fair_guard(bol, region);
4728 Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4729 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4730 // Keep track of the fact that 'obj' is an array to prevent
4731 // array specific accesses from floating above the guard.
4732 *obj = _gvn.transform(new CheckCastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4733 }
4734 return ctrl;
4735 }
4736
4737 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4738 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4739 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4740 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4741 assert(null_free || atomic, "nullable implies atomic");
4742 Node* componentType = argument(0);
4743 Node* length = argument(1);
4744 Node* init_val = null_free ? argument(2) : nullptr;
4745
4746 const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4747 if (tp != nullptr) {
4748 ciInstanceKlass* ik = tp->instance_klass();
4749 if (ik == C->env()->Class_klass()) {
4750 ciType* t = tp->java_mirror_type();
4751 if (t != nullptr && t->is_inlinetype()) {
4752
4753 ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4754 assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4755
4756 // TOOD 8350865 ZGC needs card marks on initializing oop stores
4757 if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4758 return false;
4759 }
4760
4761 if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4762 const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4763 if (null_free) {
4764 if (init_val->is_InlineType()) {
4765 if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4766 // Zeroing is enough because the init value is the all-zero value
4767 init_val = nullptr;
4768 } else {
4769 init_val = init_val->as_InlineType()->buffer(this);
4770 }
4771 }
4772 if (init_val != nullptr) {
4773 #ifdef ASSERT
4774 init_val = null_check(init_val);
4775 Node* wrong_type_ctl = gen_subtype_check(init_val, makecon(TypeKlassPtr::make(array_klass->element_klass())));
4776 {
4777 PreserveJVMState pjvms(this);
4778 set_control(wrong_type_ctl);
4779 halt(control(), frameptr(), "incompatible type for initVal in newArray");
4780 stop_and_kill_map();
4781 }
4782 #endif
4783 init_val = _gvn.transform(new CheckCastPPNode(control(), init_val, TypeOopPtr::make_from_klass(array_klass->element_klass()), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
4784 }
4785 }
4786 Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4787 const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4788 assert(arytype->is_null_free() == null_free, "inconsistency");
4789 assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4790 set_result(obj);
4791 return true;
4792 }
4793 }
4794 }
4795 }
4796 return false;
4797 }
4798
4799 // public static native boolean ValueClass::isFlatArray(Object array);
4800 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4801 // public static native boolean ValueClass::isAtomicArray(Object array);
4802 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4803 Node* array = argument(0);
4804
4805 Node* bol;
4806 switch(check) {
4807 case IsFlat:
4808 // TODO 8350865 Use the object version here instead of loading the klass
4809 // 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
4810 bol = flat_array_test(load_object_klass(array));
4811 break;
4812 case IsNullRestricted:
4813 bol = null_free_array_test(array);
4814 break;
4815 case IsAtomic:
4816 // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4817 // Enable TestIntrinsics::test87/88 once this is implemented
4818 // bol = null_free_atomic_array_test
4819 return false;
4820 default:
4821 ShouldNotReachHere();
4822 }
4823
4824 Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4825 set_result(res);
4826 return true;
4827 }
4828
4829 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4830 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4831 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4832 RegionNode* region = new RegionNode(2);
4833 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4834
4835 if (type_array_guard) {
4836 generate_typeArray_guard(klass_node, region);
4837 if (region->req() == 3) {
4838 phi->add_req(klass_node);
4839 }
4840 }
4841 Node* adr_refined_klass = basic_plus_adr(top(), klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4842 Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4843
4844 // Can be null if not initialized yet, just deopt
4845 Node* null_ctl = top();
4846 refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4847
4848 region->init_req(1, control());
4849 phi->init_req(1, refined_klass);
4850
4851 set_control(_gvn.transform(region));
4852 return _gvn.transform(phi);
4853 }
4854
4855 // Load the non-refined array klass from an ObjArrayKlass.
4856 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4857 const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4858 if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4859 return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4860 }
4861
4862 RegionNode* region = new RegionNode(2);
4863 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4864
4865 generate_typeArray_guard(klass_node, region);
4866 if (region->req() == 3) {
4867 phi->add_req(klass_node);
4868 }
4869 Node* super_adr = basic_plus_adr(top(), klass_node, in_bytes(Klass::super_offset()));
4870 Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4871
4872 region->init_req(1, control());
4873 phi->init_req(1, super_klass);
4874
4875 set_control(_gvn.transform(region));
4876 return _gvn.transform(phi);
4877 }
4878
4879 //-----------------------inline_native_newArray--------------------------
4880 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4881 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4882 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4883 Node* mirror;
4884 Node* count_val;
4885 if (uninitialized) {
4886 null_check_receiver();
4887 mirror = argument(1);
4888 count_val = argument(2);
4889 } else {
4890 mirror = argument(0);
4891 count_val = argument(1);
4892 }
4893
4894 mirror = null_check(mirror);
4895 // If mirror or obj is dead, only null-path is taken.
4896 if (stopped()) return true;
4897
4898 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4899 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4900 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4918 CallJavaNode* slow_call = nullptr;
4919 if (uninitialized) {
4920 // Generate optimized virtual call (holder class 'Unsafe' is final)
4921 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4922 } else {
4923 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4924 }
4925 Node* slow_result = set_results_for_java_call(slow_call);
4926 // this->control() comes from set_results_for_java_call
4927 result_reg->set_req(_slow_path, control());
4928 result_val->set_req(_slow_path, slow_result);
4929 result_io ->set_req(_slow_path, i_o());
4930 result_mem->set_req(_slow_path, reset_memory());
4931 }
4932
4933 set_control(normal_ctl);
4934 if (!stopped()) {
4935 // Normal case: The array type has been cached in the java.lang.Class.
4936 // The following call works fine even if the array type is polymorphic.
4937 // It could be a dynamic mix of int[], boolean[], Object[], etc.
4938
4939 klass_node = load_default_refined_array_klass(klass_node);
4940
4941 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
4942 result_reg->init_req(_normal_path, control());
4943 result_val->init_req(_normal_path, obj);
4944 result_io ->init_req(_normal_path, i_o());
4945 result_mem->init_req(_normal_path, reset_memory());
4946
4947 if (uninitialized) {
4948 // Mark the allocation so that zeroing is skipped
4949 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4950 alloc->maybe_set_complete(&_gvn);
4951 }
4952 }
4953
4954 // Return the combined state.
4955 set_i_o( _gvn.transform(result_io) );
4956 set_all_memory( _gvn.transform(result_mem));
4957
4958 C->set_has_split_ifs(true); // Has chance for split-if optimization
4959 set_result(result_reg, result_val);
4960 return true;
5009 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5010 { PreserveReexecuteState preexecs(this);
5011 jvms()->set_should_reexecute(true);
5012
5013 array_type_mirror = null_check(array_type_mirror);
5014 original = null_check(original);
5015
5016 // Check if a null path was taken unconditionally.
5017 if (stopped()) return true;
5018
5019 Node* orig_length = load_array_length(original);
5020
5021 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5022 klass_node = null_check(klass_node);
5023
5024 RegionNode* bailout = new RegionNode(1);
5025 record_for_igvn(bailout);
5026
5027 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5028 // Bail out if that is so.
5029 // Inline type array may have object field that would require a
5030 // write barrier. Conservatively, go to slow path.
5031 // TODO 8251971: Optimize for the case when flat src/dst are later found
5032 // to not contain oops (i.e., move this check to the macro expansion phase).
5033 // TODO 8382226: Revisit for flat abstract value class arrays
5034 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5035 const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5036 const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5037 bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5038 // Can src array be flat and contain oops?
5039 (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5040 // Can dest array be flat and contain oops?
5041 tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5042 Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5043
5044 Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5045
5046 if (not_objArray != nullptr) {
5047 // Improve the klass node's type from the new optimistic assumption:
5048 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5049 bool not_flat = !UseArrayFlattening;
5050 bool not_null_free = !Arguments::is_valhalla_enabled();
5051 const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5052 Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5053 refined_klass_node = _gvn.transform(cast);
5054 }
5055
5056 // Bail out if either start or end is negative.
5057 generate_negative_guard(start, bailout, &start);
5058 generate_negative_guard(end, bailout, &end);
5059
5060 Node* length = end;
5061 if (_gvn.type(start) != TypeInt::ZERO) {
5062 length = _gvn.transform(new SubINode(end, start));
5063 }
5064
5065 // Bail out if length is negative (i.e., if start > end).
5066 // Without this the new_array would throw
5067 // NegativeArraySizeException but IllegalArgumentException is what
5068 // should be thrown
5069 generate_negative_guard(length, bailout, &length);
5070
5071 // Handle inline type arrays
5072 // TODO 8251971 This is too strong
5073 generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5074 generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5075 generate_fair_guard(null_free_array_test(original), bailout);
5076
5077 // Bail out if start is larger than the original length
5078 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5079 generate_negative_guard(orig_tail, bailout, &orig_tail);
5080
5081 if (bailout->req() > 1) {
5082 PreserveJVMState pjvms(this);
5083 set_control(_gvn.transform(bailout));
5084 uncommon_trap(Deoptimization::Reason_intrinsic,
5085 Deoptimization::Action_maybe_recompile);
5086 }
5087
5088 if (!stopped()) {
5089 // How many elements will we copy from the original?
5090 // The answer is MinI(orig_tail, length).
5091 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5092
5093 // Generate a direct call to the right arraycopy function(s).
5094 // We know the copy is disjoint but we might not know if the
5095 // oop stores need checking.
5096 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
5116 }
5117 }
5118
5119 bool validated = false;
5120 // Reason_class_check rather than Reason_intrinsic because we
5121 // want to intrinsify even if this traps.
5122 if (!too_many_traps(Deoptimization::Reason_class_check)) {
5123 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5124
5125 if (not_subtype_ctrl != top()) {
5126 PreserveJVMState pjvms(this);
5127 set_control(not_subtype_ctrl);
5128 uncommon_trap(Deoptimization::Reason_class_check,
5129 Deoptimization::Action_make_not_entrant);
5130 assert(stopped(), "Should be stopped");
5131 }
5132 validated = true;
5133 }
5134
5135 if (!stopped()) {
5136 newcopy = new_array(refined_klass_node, length, 0); // no arguments to push
5137
5138 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5139 load_object_klass(original), klass_node);
5140 if (!is_copyOfRange) {
5141 ac->set_copyof(validated);
5142 } else {
5143 ac->set_copyofrange(validated);
5144 }
5145 Node* n = _gvn.transform(ac);
5146 if (n == ac) {
5147 ac->connect_outputs(this);
5148 } else {
5149 assert(validated, "shouldn't transform if all arguments not validated");
5150 set_all_memory(n);
5151 }
5152 }
5153 }
5154 } // original reexecute is set back here
5155
5156 C->set_has_split_ifs(true); // Has chance for split-if optimization
5188
5189 //-----------------------generate_method_call----------------------------
5190 // Use generate_method_call to make a slow-call to the real
5191 // method if the fast path fails. An alternative would be to
5192 // use a stub like OptoRuntime::slow_arraycopy_Java.
5193 // This only works for expanding the current library call,
5194 // not another intrinsic. (E.g., don't use this for making an
5195 // arraycopy call inside of the copyOf intrinsic.)
5196 CallJavaNode*
5197 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5198 // When compiling the intrinsic method itself, do not use this technique.
5199 guarantee(callee() != C->method(), "cannot make slow-call to self");
5200
5201 ciMethod* method = callee();
5202 // ensure the JVMS we have will be correct for this call
5203 guarantee(method_id == method->intrinsic_id(), "must match");
5204
5205 const TypeFunc* tf = TypeFunc::make(method);
5206 if (res_not_null) {
5207 assert(tf->return_type() == T_OBJECT, "");
5208 const TypeTuple* range = tf->range_cc();
5209 const Type** fields = TypeTuple::fields(range->cnt());
5210 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5211 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5212 tf = TypeFunc::make(tf->domain_cc(), new_range);
5213 }
5214 CallJavaNode* slow_call;
5215 if (is_static) {
5216 assert(!is_virtual, "");
5217 slow_call = new CallStaticJavaNode(C, tf,
5218 SharedRuntime::get_resolve_static_call_stub(), method);
5219 } else if (is_virtual) {
5220 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5221 int vtable_index = Method::invalid_vtable_index;
5222 if (UseInlineCaches) {
5223 // Suppress the vtable call
5224 } else {
5225 // hashCode and clone are not a miranda methods,
5226 // so the vtable index is fixed.
5227 // No need to use the linkResolver to get it.
5228 vtable_index = method->vtable_index();
5229 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5230 "bad index %d", vtable_index);
5231 }
5232 slow_call = new CallDynamicJavaNode(tf,
5249 set_edges_for_java_call(slow_call);
5250 return slow_call;
5251 }
5252
5253
5254 /**
5255 * Build special case code for calls to hashCode on an object. This call may
5256 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5257 * slightly different code.
5258 */
5259 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5260 assert(is_static == callee()->is_static(), "correct intrinsic selection");
5261 assert(!(is_virtual && is_static), "either virtual, special, or static");
5262
5263 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5264
5265 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5266 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
5267 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
5268 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5269 Node* obj = argument(0);
5270
5271 // Don't intrinsify hashcode on inline types for now.
5272 // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5273 if (gvn().type(obj)->is_inlinetypeptr()) {
5274 return false;
5275 }
5276
5277 if (!is_static) {
5278 // Check for hashing null object
5279 obj = null_check_receiver();
5280 if (stopped()) return true; // unconditionally null
5281 result_reg->init_req(_null_path, top());
5282 result_val->init_req(_null_path, top());
5283 } else {
5284 // Do a null check, and return zero if null.
5285 // System.identityHashCode(null) == 0
5286 Node* null_ctl = top();
5287 obj = null_check_oop(obj, &null_ctl);
5288 result_reg->init_req(_null_path, null_ctl);
5289 result_val->init_req(_null_path, _gvn.intcon(0));
5290 }
5291
5292 // Unconditionally null? Then return right away.
5293 if (stopped()) {
5294 set_control( result_reg->in(_null_path));
5295 if (!stopped())
5296 set_result(result_val->in(_null_path));
5297 return true;
5298 }
5299
5300 // We only go to the fast case code if we pass a number of guards. The
5301 // paths which do not pass are accumulated in the slow_region.
5302 RegionNode* slow_region = new RegionNode(1);
5303 record_for_igvn(slow_region);
5304
5305 // If this is a virtual call, we generate a funny guard. We pull out
5306 // the vtable entry corresponding to hashCode() from the target object.
5307 // If the target method which we are calling happens to be the native
5308 // Object hashCode() method, we pass the guard. We do not need this
5309 // guard for non-virtual calls -- the caller is known to be the native
5310 // Object hashCode().
5311 if (is_virtual) {
5312 // After null check, get the object's klass.
5313 Node* obj_klass = load_object_klass(obj);
5314 generate_virtual_guard(obj_klass, slow_region);
5315 }
5316
5317 // Get the header out of the object, use LoadMarkNode when available
5318 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5319 // The control of the load must be null. Otherwise, the load can move before
5320 // the null check after castPP removal.
5321 Node* no_ctrl = nullptr;
5322 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5323
5324 if (!UseObjectMonitorTable) {
5325 // Test the header to see if it is safe to read w.r.t. locking.
5326 // We cannot use the inline type mask as this may check bits that are overriden
5327 // by an object monitor's pointer when inflating locking.
5328 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
5329 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5330 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
5331 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5332 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5333
5334 generate_slow_guard(test_monitor, slow_region);
5335 }
5336
5337 // Get the hash value and check to see that it has been properly assigned.
5338 // We depend on hash_mask being at most 32 bits and avoid the use of
5339 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5340 // vm: see markWord.hpp.
5341 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
5342 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
5343 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5344 // This hack lets the hash bits live anywhere in the mark object now, as long
5345 // as the shift drops the relevant bits into the low 32 bits. Note that
5346 // Java spec says that HashCode is an int so there's no point in capturing
5347 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5375 // this->control() comes from set_results_for_java_call
5376 result_reg->init_req(_slow_path, control());
5377 result_val->init_req(_slow_path, slow_result);
5378 result_io ->set_req(_slow_path, i_o());
5379 result_mem ->set_req(_slow_path, reset_memory());
5380 }
5381
5382 // Return the combined state.
5383 set_i_o( _gvn.transform(result_io) );
5384 set_all_memory( _gvn.transform(result_mem));
5385
5386 set_result(result_reg, result_val);
5387 return true;
5388 }
5389
5390 //---------------------------inline_native_getClass----------------------------
5391 // public final native Class<?> java.lang.Object.getClass();
5392 //
5393 // Build special case code for calls to getClass on an object.
5394 bool LibraryCallKit::inline_native_getClass() {
5395 Node* obj = argument(0);
5396 if (obj->is_InlineType()) {
5397 const Type* t = _gvn.type(obj);
5398 if (t->maybe_null()) {
5399 null_check(obj);
5400 }
5401 set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5402 return true;
5403 }
5404 obj = null_check_receiver();
5405 if (stopped()) return true;
5406 set_result(load_mirror_from_klass(load_object_klass(obj)));
5407 return true;
5408 }
5409
5410 //-----------------inline_native_Reflection_getCallerClass---------------------
5411 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5412 //
5413 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5414 //
5415 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5416 // in that it must skip particular security frames and checks for
5417 // caller sensitive methods.
5418 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5419 #ifndef PRODUCT
5420 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5421 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5422 }
5423 #endif
5424
5806 // not cloneable or finalizer => slow path to out-of-line Object.clone
5807 //
5808 // The general case has two steps, allocation and copying.
5809 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5810 //
5811 // Copying also has two cases, oop arrays and everything else.
5812 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5813 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5814 //
5815 // These steps fold up nicely if and when the cloned object's klass
5816 // can be sharply typed as an object array, a type array, or an instance.
5817 //
5818 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5819 PhiNode* result_val;
5820
5821 // Set the reexecute bit for the interpreter to reexecute
5822 // the bytecode that invokes Object.clone if deoptimization happens.
5823 { PreserveReexecuteState preexecs(this);
5824 jvms()->set_should_reexecute(true);
5825
5826 Node* obj = argument(0);
5827 obj = null_check_receiver();
5828 if (stopped()) return true;
5829
5830 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5831 if (obj_type->is_inlinetypeptr()) {
5832 // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5833 // no identity.
5834 set_result(obj);
5835 return true;
5836 }
5837
5838 // If we are going to clone an instance, we need its exact type to
5839 // know the number and types of fields to convert the clone to
5840 // loads/stores. Maybe a speculative type can help us.
5841 if (!obj_type->klass_is_exact() &&
5842 obj_type->speculative_type() != nullptr &&
5843 obj_type->speculative_type()->is_instance_klass() &&
5844 !obj_type->speculative_type()->is_inlinetype()) {
5845 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5846 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5847 !spec_ik->has_injected_fields()) {
5848 if (!obj_type->isa_instptr() ||
5849 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5850 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5851 }
5852 }
5853 }
5854
5855 // Conservatively insert a memory barrier on all memory slices.
5856 // Do not let writes into the original float below the clone.
5857 insert_mem_bar(Op_MemBarCPUOrder);
5858
5859 // paths into result_reg:
5860 enum {
5861 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5862 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5863 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5864 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5865 PATH_LIMIT
5866 };
5867 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5868 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5869 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5870 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5871 record_for_igvn(result_reg);
5872
5873 Node* obj_klass = load_object_klass(obj);
5874 // We only go to the fast case code if we pass a number of guards.
5875 // The paths which do not pass are accumulated in the slow_region.
5876 RegionNode* slow_region = new RegionNode(1);
5877 record_for_igvn(slow_region);
5878
5879 Node* array_obj = obj;
5880 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5881 if (array_ctl != nullptr) {
5882 // It's an array.
5883 PreserveJVMState pjvms(this);
5884 set_control(array_ctl);
5885
5886 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5887 const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5888 if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5889 obj_type->can_be_inline_array() &&
5890 (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5891 // Flat inline type array may have object field that would require a
5892 // write barrier. Conservatively, go to slow path.
5893 generate_fair_guard(flat_array_test(obj_klass), slow_region);
5894 }
5895
5896 if (!stopped()) {
5897 Node* obj_length = load_array_length(array_obj);
5898 Node* array_size = nullptr; // Size of the array without object alignment padding.
5899 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5900
5901 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5902 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5903 // If it is an oop array, it requires very special treatment,
5904 // because gc barriers are required when accessing the array.
5905 Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
5906 if (is_obja != nullptr) {
5907 PreserveJVMState pjvms2(this);
5908 set_control(is_obja);
5909 // Generate a direct call to the right arraycopy function(s).
5910 // Clones are always tightly coupled.
5911 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5912 ac->set_clone_oop_array();
5913 Node* n = _gvn.transform(ac);
5914 assert(n == ac, "cannot disappear");
5915 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5916
5917 result_reg->init_req(_objArray_path, control());
5918 result_val->init_req(_objArray_path, alloc_obj);
5919 result_i_o ->set_req(_objArray_path, i_o());
5920 result_mem ->set_req(_objArray_path, reset_memory());
5921 }
5922 }
5923 // Otherwise, there are no barriers to worry about.
5924 // (We can dispense with card marks if we know the allocation
5925 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5926 // causes the non-eden paths to take compensating steps to
5927 // simulate a fresh allocation, so that no further
5928 // card marks are required in compiled code to initialize
5929 // the object.)
5930
5931 if (!stopped()) {
5932 copy_to_clone(obj, alloc_obj, array_size, true);
5933
5934 // Present the results of the copy.
5935 result_reg->init_req(_array_path, control());
5936 result_val->init_req(_array_path, alloc_obj);
5937 result_i_o ->set_req(_array_path, i_o());
5938 result_mem ->set_req(_array_path, reset_memory());
5939 }
5940 }
5941 }
5942
5943 if (!stopped()) {
5944 // It's an instance (we did array above). Make the slow-path tests.
5945 // If this is a virtual call, we generate a funny guard. We grab
5946 // the vtable entry corresponding to clone() from the target object.
5947 // If the target method which we are calling happens to be the
5948 // Object clone() method, we pass the guard. We do not need this
5949 // guard for non-virtual calls; the caller is known to be the native
5950 // Object clone().
5951 if (is_virtual) {
5952 generate_virtual_guard(obj_klass, slow_region);
5953 }
5954
5955 // The object must be easily cloneable and must not have a finalizer.
5956 // Both of these conditions may be checked in a single test.
5957 // We could optimize the test further, but we don't care.
5958 generate_misc_flags_guard(obj_klass,
5959 // Test both conditions:
5960 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5961 // Must be cloneable but not finalizer:
5962 KlassFlags::_misc_is_cloneable_fast,
6054 set_jvms(sfpt->jvms());
6055 _reexecute_sp = jvms()->sp();
6056
6057 return saved_jvms;
6058 }
6059 }
6060 }
6061 return nullptr;
6062 }
6063
6064 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6065 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6066 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6067 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6068 uint size = alloc->req();
6069 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6070 old_jvms->set_map(sfpt);
6071 for (uint i = 0; i < size; i++) {
6072 sfpt->init_req(i, alloc->in(i));
6073 }
6074 int adjustment = 1;
6075 const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6076 if (ary_klass_ptr->is_null_free()) {
6077 // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6078 // also requires the componentType and initVal on stack for re-execution.
6079 // Re-create and push the componentType.
6080 ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6081 ciInstance* instance = klass->component_mirror_instance();
6082 const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6083 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6084 adjustment++;
6085 }
6086 // re-push array length for deoptimization
6087 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6088 if (ary_klass_ptr->is_null_free()) {
6089 // Re-create and push the initVal.
6090 Node* init_val = alloc->in(AllocateNode::InitValue);
6091 if (init_val == nullptr) {
6092 init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6093 } else if (UseCompressedOops) {
6094 init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6095 }
6096 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6097 adjustment++;
6098 }
6099 old_jvms->set_sp(old_jvms->sp() + adjustment);
6100 old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6101 old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6102 old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6103 old_jvms->set_should_reexecute(true);
6104
6105 sfpt->set_i_o(map()->i_o());
6106 sfpt->set_memory(map()->memory());
6107 sfpt->set_control(map()->control());
6108 return sfpt;
6109 }
6110
6111 // In case of a deoptimization, we restart execution at the
6112 // allocation, allocating a new array. We would leave an uninitialized
6113 // array in the heap that GCs wouldn't expect. Move the allocation
6114 // after the traps so we don't allocate the array if we
6115 // deoptimize. This is possible because tightly_coupled_allocation()
6116 // guarantees there's no observer of the allocated array at this point
6117 // and the control flow is simple enough.
6118 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6119 int saved_reexecute_sp, uint new_idx) {
6120 if (saved_jvms_before_guards != nullptr && !stopped()) {
6121 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6122
6123 assert(alloc != nullptr, "only with a tightly coupled allocation");
6124 // restore JVM state to the state at the arraycopy
6125 saved_jvms_before_guards->map()->set_control(map()->control());
6126 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6127 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6128 // If we've improved the types of some nodes (null check) while
6129 // emitting the guards, propagate them to the current state
6130 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6131 set_jvms(saved_jvms_before_guards);
6132 _reexecute_sp = saved_reexecute_sp;
6133
6134 // Remove the allocation from above the guards
6135 CallProjections* callprojs = alloc->extract_projections(true);
6136 InitializeNode* init = alloc->initialization();
6137 Node* alloc_mem = alloc->in(TypeFunc::Memory);
6138 C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6139 init->replace_mem_projs_by(alloc_mem, C);
6140
6141 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6142 // the allocation (i.e. is only valid if the allocation succeeds):
6143 // 1) replace CastIINode with AllocateArrayNode's length here
6144 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6145 //
6146 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6147 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6148 Node* init_control = init->proj_out(TypeFunc::Control);
6149 Node* alloc_length = alloc->Ideal_length();
6150 #ifdef ASSERT
6151 Node* prev_cast = nullptr;
6152 #endif
6153 for (uint i = 0; i < init_control->outcnt(); i++) {
6154 Node* init_out = init_control->raw_out(i);
6155 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6156 #ifdef ASSERT
6157 if (prev_cast == nullptr) {
6158 prev_cast = init_out;
6160 if (prev_cast->cmp(*init_out) == false) {
6161 prev_cast->dump();
6162 init_out->dump();
6163 assert(false, "not equal CastIINode");
6164 }
6165 }
6166 #endif
6167 C->gvn_replace_by(init_out, alloc_length);
6168 }
6169 }
6170 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6171
6172 // move the allocation here (after the guards)
6173 _gvn.hash_delete(alloc);
6174 alloc->set_req(TypeFunc::Control, control());
6175 alloc->set_req(TypeFunc::I_O, i_o());
6176 Node *mem = reset_memory();
6177 set_all_memory(mem);
6178 alloc->set_req(TypeFunc::Memory, mem);
6179 set_control(init->proj_out_or_null(TypeFunc::Control));
6180 set_i_o(callprojs->fallthrough_ioproj);
6181
6182 // Update memory as done in GraphKit::set_output_for_allocation()
6183 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6184 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6185 if (ary_type->isa_aryptr() && length_type != nullptr) {
6186 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6187 }
6188 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6189 int elemidx = C->get_alias_index(telemref);
6190 // Need to properly move every memory projection for the Initialize
6191 #ifdef ASSERT
6192 int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6193 int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6194 #endif
6195 auto move_proj = [&](ProjNode* proj) {
6196 int alias_idx = C->get_alias_index(proj->adr_type());
6197 assert(alias_idx == Compile::AliasIdxRaw ||
6198 alias_idx == elemidx ||
6199 alias_idx == mark_idx ||
6200 alias_idx == klass_idx, "should be raw memory or array element type");
6510 top_src = src_type->isa_aryptr();
6511 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6512 src_spec = true;
6513 }
6514 if (!has_dest) {
6515 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6516 dest_type = _gvn.type(dest);
6517 top_dest = dest_type->isa_aryptr();
6518 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6519 dest_spec = true;
6520 }
6521 }
6522 }
6523
6524 if (has_src && has_dest && can_emit_guards) {
6525 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6526 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6527 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6528 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6529
6530 if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6531 // If both arrays are object arrays then having the exact types
6532 // for both will remove the need for a subtype check at runtime
6533 // before the call and may make it possible to pick a faster copy
6534 // routine (without a subtype check on every element)
6535 // Do we have the exact type of src?
6536 bool could_have_src = src_spec;
6537 // Do we have the exact type of dest?
6538 bool could_have_dest = dest_spec;
6539 ciKlass* src_k = nullptr;
6540 ciKlass* dest_k = nullptr;
6541 if (!src_spec) {
6542 src_k = src_type->speculative_type_not_null();
6543 if (src_k != nullptr && src_k->is_array_klass()) {
6544 could_have_src = true;
6545 }
6546 }
6547 if (!dest_spec) {
6548 dest_k = dest_type->speculative_type_not_null();
6549 if (dest_k != nullptr && dest_k->is_array_klass()) {
6550 could_have_dest = true;
6551 }
6552 }
6553 if (could_have_src && could_have_dest) {
6554 // If we can have both exact types, emit the missing guards
6555 if (could_have_src && !src_spec) {
6556 src = maybe_cast_profiled_obj(src, src_k, true);
6557 src_type = _gvn.type(src);
6558 top_src = src_type->isa_aryptr();
6559 }
6560 if (could_have_dest && !dest_spec) {
6561 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6562 dest_type = _gvn.type(dest);
6563 top_dest = dest_type->isa_aryptr();
6564 }
6565 }
6566 }
6567 }
6568
6569 ciMethod* trap_method = method();
6570 int trap_bci = bci();
6571 if (saved_jvms_before_guards != nullptr) {
6572 trap_method = alloc->jvms()->method();
6573 trap_bci = alloc->jvms()->bci();
6574 }
6575
6576 bool negative_length_guard_generated = false;
6577
6578 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6579 can_emit_guards && !src->is_top() && !dest->is_top()) {
6580 // validate arguments: enables transformation the ArrayCopyNode
6581 validated = true;
6582
6583 RegionNode* slow_region = new RegionNode(1);
6584 record_for_igvn(slow_region);
6585
6586 // (1) src and dest are arrays.
6587 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6588 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6589
6590 // (2) src and dest arrays must have elements of the same BasicType
6591 // done at macro expansion or at Ideal transformation time
6592
6593 // (4) src_offset must not be negative.
6594 generate_negative_guard(src_offset, slow_region);
6595
6596 // (5) dest_offset must not be negative.
6597 generate_negative_guard(dest_offset, slow_region);
6598
6599 // (7) src_offset + length must not exceed length of src.
6600 generate_limit_guard(src_offset, length,
6601 load_array_length(src),
6602 slow_region);
6603
6604 // (8) dest_offset + length must not exceed length of dest.
6605 generate_limit_guard(dest_offset, length,
6606 load_array_length(dest),
6607 slow_region);
6608
6609 // (6) length must not be negative.
6610 // This is also checked in generate_arraycopy() during macro expansion, but
6611 // we also have to check it here for the case where the ArrayCopyNode will
6612 // be eliminated by Escape Analysis.
6613 if (EliminateAllocations) {
6614 generate_negative_guard(length, slow_region);
6615 negative_length_guard_generated = true;
6616 }
6617
6618 // (9) each element of an oop array must be assignable
6619 Node* dest_klass = load_object_klass(dest);
6620 Node* refined_dest_klass = dest_klass;
6621 if (src != dest) {
6622 dest_klass = load_non_refined_array_klass(refined_dest_klass);
6623 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6624 slow_region->add_req(not_subtype_ctrl);
6625 }
6626
6627 // TODO 8251971 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6628 // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6629 Node* src_klass = load_object_klass(src);
6630 Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset()));
6631 Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src,
6632 _gvn.type(adr_prop_src)->is_ptr(), TypeInt::INT, T_INT,
6633 MemNode::unordered));
6634 Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6635 Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest,
6636 _gvn.type(adr_prop_dest)->is_ptr(), TypeInt::INT, T_INT,
6637 MemNode::unordered));
6638
6639 const ArrayProperties props_null_restricted = ArrayProperties::Default().with_null_restricted();
6640 jint props_value = (jint)props_null_restricted.value();
6641
6642 prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(props_value)));
6643 prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6644 prop_src = _gvn.transform(new AndINode(prop_src, intcon(props_value)));
6645
6646 Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(props_value)));
6647 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6648 generate_fair_guard(tst, slow_region);
6649
6650 // TODO 8251971 This is too strong
6651 generate_fair_guard(flat_array_test(src), slow_region);
6652 generate_fair_guard(flat_array_test(dest), slow_region);
6653
6654 {
6655 PreserveJVMState pjvms(this);
6656 set_control(_gvn.transform(slow_region));
6657 uncommon_trap(Deoptimization::Reason_intrinsic,
6658 Deoptimization::Action_make_not_entrant);
6659 assert(stopped(), "Should be stopped");
6660 }
6661
6662 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6663 if (dest_klass_t == nullptr) {
6664 // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6665 // are in a dead path.
6666 uncommon_trap(Deoptimization::Reason_intrinsic,
6667 Deoptimization::Action_make_not_entrant);
6668 return true;
6669 }
6670
6671 const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6672 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6673 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6674 }
6675
6676 if (stopped()) {
6677 return true;
6678 }
6679
6680 Node* dest_klass = load_object_klass(dest);
6681 dest_klass = load_non_refined_array_klass(dest_klass);
6682
6683 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6684 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6685 // so the compiler has a chance to eliminate them: during macro expansion,
6686 // we have to set their control (CastPP nodes are eliminated).
6687 load_object_klass(src), dest_klass,
6688 load_array_length(src), load_array_length(dest));
6689
6690 ac->set_arraycopy(validated);
6691
6692 Node* n = _gvn.transform(ac);
6693 if (n == ac) {
6694 ac->connect_outputs(this);
6695 } else {
6696 assert(validated, "shouldn't transform if all arguments not validated");
6697 set_all_memory(n);
6698 }
6699 clear_upper_avx();
6700
6701
6702 return true;
6703 }
6704
6705
6706 // Helper function which determines if an arraycopy immediately follows
6707 // an allocation, with no intervening tests or other escapes for the object.
|