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