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"
54 #include "prims/jvmtiExport.hpp"
55 #include "prims/jvmtiThreadState.hpp"
56 #include "prims/unsafe.hpp"
57 #include "runtime/jniHandles.inline.hpp"
58 #include "runtime/objectMonitor.hpp"
59 #include "runtime/sharedRuntime.hpp"
60 #include "runtime/stubRoutines.hpp"
61 #include "utilities/macros.hpp"
62 #include "utilities/powerOfTwo.hpp"
63
64 //---------------------------make_vm_intrinsic----------------------------
65 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
66 vmIntrinsicID id = m->intrinsic_id();
67 assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
68
69 if (!m->is_loaded()) {
70 // Do not attempt to inline unloaded methods.
71 return nullptr;
72 }
73
74 C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
75 bool is_available = false;
76
77 {
78 // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
79 // the compiler must transition to '_thread_in_vm' state because both
80 // methods access VM-internal data.
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);
388 case vmIntrinsics::_getReferenceOpaque: return inline_unsafe_access(!is_store, T_OBJECT, Opaque, false);
389 case vmIntrinsics::_getBooleanOpaque: return inline_unsafe_access(!is_store, T_BOOLEAN, Opaque, false);
390 case vmIntrinsics::_getByteOpaque: return inline_unsafe_access(!is_store, T_BYTE, Opaque, false);
391 case vmIntrinsics::_getShortOpaque: return inline_unsafe_access(!is_store, T_SHORT, Opaque, false);
392 case vmIntrinsics::_getCharOpaque: return inline_unsafe_access(!is_store, T_CHAR, Opaque, false);
393 case vmIntrinsics::_getIntOpaque: return inline_unsafe_access(!is_store, T_INT, Opaque, false);
394 case vmIntrinsics::_getLongOpaque: return inline_unsafe_access(!is_store, T_LONG, Opaque, false);
395 case vmIntrinsics::_getFloatOpaque: return inline_unsafe_access(!is_store, T_FLOAT, Opaque, false);
396 case vmIntrinsics::_getDoubleOpaque: return inline_unsafe_access(!is_store, T_DOUBLE, Opaque, false);
397
398 case vmIntrinsics::_putReferenceOpaque: return inline_unsafe_access( is_store, T_OBJECT, Opaque, false);
399 case vmIntrinsics::_putBooleanOpaque: return inline_unsafe_access( is_store, T_BOOLEAN, Opaque, false);
400 case vmIntrinsics::_putByteOpaque: return inline_unsafe_access( is_store, T_BYTE, Opaque, false);
401 case vmIntrinsics::_putShortOpaque: return inline_unsafe_access( is_store, T_SHORT, Opaque, false);
402 case vmIntrinsics::_putCharOpaque: return inline_unsafe_access( is_store, T_CHAR, Opaque, false);
403 case vmIntrinsics::_putIntOpaque: return inline_unsafe_access( is_store, T_INT, Opaque, false);
404 case vmIntrinsics::_putLongOpaque: return inline_unsafe_access( is_store, T_LONG, Opaque, false);
405 case vmIntrinsics::_putFloatOpaque: return inline_unsafe_access( is_store, T_FLOAT, Opaque, false);
406 case vmIntrinsics::_putDoubleOpaque: return inline_unsafe_access( is_store, T_DOUBLE, Opaque, false);
407
408 case vmIntrinsics::_compareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap, Volatile);
409 case vmIntrinsics::_compareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap, Volatile);
410 case vmIntrinsics::_compareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap, Volatile);
411 case vmIntrinsics::_compareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap, Volatile);
412 case vmIntrinsics::_compareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap, Volatile);
413
414 case vmIntrinsics::_weakCompareAndSetReferencePlain: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
415 case vmIntrinsics::_weakCompareAndSetReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
416 case vmIntrinsics::_weakCompareAndSetReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
417 case vmIntrinsics::_weakCompareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
418 case vmIntrinsics::_weakCompareAndSetBytePlain: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Relaxed);
419 case vmIntrinsics::_weakCompareAndSetByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Acquire);
420 case vmIntrinsics::_weakCompareAndSetByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Release);
421 case vmIntrinsics::_weakCompareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Volatile);
422 case vmIntrinsics::_weakCompareAndSetShortPlain: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Relaxed);
423 case vmIntrinsics::_weakCompareAndSetShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Acquire);
424 case vmIntrinsics::_weakCompareAndSetShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Release);
425 case vmIntrinsics::_weakCompareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Volatile);
426 case vmIntrinsics::_weakCompareAndSetIntPlain: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Relaxed);
427 case vmIntrinsics::_weakCompareAndSetIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Acquire);
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:
2292 case vmIntrinsics::_remainderUnsigned_l: {
2293 zero_check_long(argument(2));
2294 // Compile-time detect of null-exception
2295 if (stopped()) {
2296 return true; // keep the graph constructed so far
2297 }
2298 n = new UModLNode(control(), argument(0), argument(2));
2299 break;
2300 }
2301 default: fatal_unexpected_iid(id); break;
2302 }
2303 set_result(_gvn.transform(n));
2304 return true;
2305 }
2306
2307 //----------------------------inline_unsafe_access----------------------------
2308
2309 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2310 // Attempt to infer a sharper value type from the offset and base type.
2311 ciKlass* sharpened_klass = nullptr;
2312
2313 // See if it is an instance field, with an object type.
2314 if (alias_type->field() != nullptr) {
2315 if (alias_type->field()->type()->is_klass()) {
2316 sharpened_klass = alias_type->field()->type()->as_klass();
2317 }
2318 }
2319
2320 const TypeOopPtr* result = nullptr;
2321 // See if it is a narrow oop array.
2322 if (adr_type->isa_aryptr()) {
2323 if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2324 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2325 if (elem_type != nullptr && elem_type->is_loaded()) {
2326 // Sharpen the value type.
2327 result = elem_type;
2328 }
2329 }
2330 }
2331
2332 // The sharpened class might be unloaded if there is no class loader
2333 // contraint in place.
2334 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2335 // Sharpen the value type.
2336 result = TypeOopPtr::make_from_klass(sharpened_klass);
2337 }
2338 if (result != nullptr) {
2339 #ifndef PRODUCT
2340 if (C->print_intrinsics() || C->print_inlining()) {
2341 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2342 tty->print(" sharpened value: "); result->dump(); tty->cr();
2343 }
2344 #endif
2345 }
2346 return result;
2347 }
2348
2349 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2350 switch (kind) {
2351 case Relaxed:
2352 return MO_UNORDERED;
2353 case Opaque:
2354 return MO_RELAXED;
2355 case Acquire:
2356 return MO_ACQUIRE;
2357 case Release:
2358 return MO_RELEASE;
2359 case Volatile:
2360 return MO_SEQ_CST;
2361 default:
2362 ShouldNotReachHere();
2363 return 0;
2364 }
2365 }
2366
2367 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2368 if (callee()->is_static()) return false; // caller must have the capability!
2369 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2370 guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2371 guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2372 assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2373
2374 if (is_reference_type(type)) {
2375 decorators |= ON_UNKNOWN_OOP_REF;
2376 }
2377
2378 if (unaligned) {
2379 decorators |= C2_UNALIGNED;
2380 }
2381
2382 #ifndef PRODUCT
2383 {
2384 ResourceMark rm;
2385 // Check the signatures.
2386 ciSignature* sig = callee()->signature();
2387 #ifdef ASSERT
2388 if (!is_store) {
2389 // Object getReference(Object base, int/long offset), etc.
2390 BasicType rtype = sig->return_type()->basic_type();
2391 assert(rtype == type, "getter must return the expected value");
2392 assert(sig->count() == 2, "oop getter has 2 arguments");
2393 assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2394 assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2395 } else {
2396 // void putReference(Object base, int/long offset, Object x), etc.
2397 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2398 assert(sig->count() == 3, "oop putter has 3 arguments");
2399 assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2400 assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2401 BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2402 assert(vtype == type, "putter must accept the expected value");
2403 }
2404 #endif // ASSERT
2405 }
2406 #endif //PRODUCT
2407
2408 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2409
2410 Node* receiver = argument(0); // type: oop
2411
2412 // Build address expression.
2413 Node* heap_base_oop = top();
2414
2415 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2416 Node* base = argument(1); // type: oop
2417 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2418 Node* offset = argument(2); // type: long
2419 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2420 // to be plain byte offsets, which are also the same as those accepted
2421 // by oopDesc::field_addr.
2422 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2423 "fieldOffset must be byte-scaled");
2424 // 32-bit machines ignore the high half!
2425 offset = ConvL2X(offset);
2426
2427 // Save state and restore on bailout
2428 uint old_sp = sp();
2429 SafePointNode* old_map = clone_map();
2430
2431 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2432 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2433
2434 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2435 if (type != T_OBJECT) {
2436 decorators |= IN_NATIVE; // off-heap primitive access
2437 } else {
2438 set_map(old_map);
2439 set_sp(old_sp);
2440 return false; // off-heap oop accesses are not supported
2441 }
2442 } else {
2443 heap_base_oop = base; // on-heap or mixed access
2444 }
2445
2446 // Can base be null? Otherwise, always on-heap access.
2447 bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2448
2449 if (!can_access_non_heap) {
2450 decorators |= IN_HEAP;
2451 }
2452
2453 Node* val = is_store ? argument(4) : nullptr;
2454
2455 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2456 if (adr_type == TypePtr::NULL_PTR) {
2457 set_map(old_map);
2458 set_sp(old_sp);
2459 return false; // off-heap access with zero address
2460 }
2461
2462 // Try to categorize the address.
2463 Compile::AliasType* alias_type = C->alias_type(adr_type);
2464 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2465
2466 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2467 alias_type->adr_type() == TypeAryPtr::RANGE) {
2468 set_map(old_map);
2469 set_sp(old_sp);
2470 return false; // not supported
2471 }
2472
2473 bool mismatched = false;
2474 BasicType bt = alias_type->basic_type();
2475 if (bt != T_ILLEGAL) {
2476 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2477 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2478 // Alias type doesn't differentiate between byte[] and boolean[]).
2479 // Use address type to get the element type.
2480 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2481 }
2482 if (is_reference_type(bt, true)) {
2483 // accessing an array field with getReference is not a mismatch
2484 bt = T_OBJECT;
2485 }
2486 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2487 // Don't intrinsify mismatched object accesses
2488 set_map(old_map);
2489 set_sp(old_sp);
2490 return false;
2491 }
2492 mismatched = (bt != type);
2493 } else if (alias_type->adr_type()->isa_oopptr()) {
2494 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2495 }
2496
2497 destruct_map_clone(old_map);
2498 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2499
2500 if (mismatched) {
2501 decorators |= C2_MISMATCHED;
2502 }
2503
2504 // First guess at the value type.
2505 const Type *value_type = Type::get_const_basic_type(type);
2506
2507 // Figure out the memory ordering.
2508 decorators |= mo_decorator_for_access_kind(kind);
2509
2510 if (!is_store && type == T_OBJECT) {
2511 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2512 if (tjp != nullptr) {
2513 value_type = tjp;
2514 }
2515 }
2516
2517 receiver = null_check(receiver);
2518 if (stopped()) {
2519 return true;
2520 }
2521 // Heap pointers get a null-check from the interpreter,
2522 // as a courtesy. However, this is not guaranteed by Unsafe,
2523 // and it is not possible to fully distinguish unintended nulls
2524 // from intended ones in this API.
2525
2526 if (!is_store) {
2527 Node* p = nullptr;
2528 // Try to constant fold a load from a constant field
2529 ciField* field = alias_type->field();
2530 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !mismatched) {
2531 // final or stable field
2532 p = make_constant_from_field(field, heap_base_oop);
2533 }
2534
2535 if (p == nullptr) { // Could not constant fold the load
2536 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2537 // Normalize the value returned by getBoolean in the following cases
2538 if (type == T_BOOLEAN &&
2539 (mismatched ||
2540 heap_base_oop == top() || // - heap_base_oop is null or
2541 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2542 // and the unsafe access is made to large offset
2543 // (i.e., larger than the maximum offset necessary for any
2544 // field access)
2545 ) {
2546 IdealKit ideal = IdealKit(this);
2547 #define __ ideal.
2548 IdealVariable normalized_result(ideal);
2549 __ declarations_done();
2550 __ set(normalized_result, p);
2551 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2552 __ set(normalized_result, ideal.ConI(1));
2553 ideal.end_if();
2554 final_sync(ideal);
2555 p = __ value(normalized_result);
2556 #undef __
2557 }
2558 }
2559 if (type == T_ADDRESS) {
2560 p = gvn().transform(new CastP2XNode(nullptr, p));
2561 p = ConvX2UL(p);
2562 }
2563 // The load node has the control of the preceding MemBarCPUOrder. All
2564 // following nodes will have the control of the MemBarCPUOrder inserted at
2565 // the end of this method. So, pushing the load onto the stack at a later
2566 // point is fine.
2567 set_result(p);
2568 } else {
2569 if (bt == T_ADDRESS) {
2570 // Repackage the long as a pointer.
2571 val = ConvL2X(val);
2572 val = gvn().transform(new CastX2PNode(val));
2573 }
2574 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2575 }
2576
2577 return true;
2578 }
2579
2580 //----------------------------inline_unsafe_load_store----------------------------
2581 // This method serves a couple of different customers (depending on LoadStoreKind):
2582 //
2583 // LS_cmp_swap:
2584 //
2585 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2586 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2587 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2588 //
2589 // LS_cmp_swap_weak:
2590 //
2591 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2592 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2593 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2594 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2595 //
2596 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2765 }
2766 case LS_cmp_swap:
2767 case LS_cmp_swap_weak:
2768 case LS_get_add:
2769 break;
2770 default:
2771 ShouldNotReachHere();
2772 }
2773
2774 // Null check receiver.
2775 receiver = null_check(receiver);
2776 if (stopped()) {
2777 return true;
2778 }
2779
2780 int alias_idx = C->get_alias_index(adr_type);
2781
2782 if (is_reference_type(type)) {
2783 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2784
2785 // Transformation of a value which could be null pointer (CastPP #null)
2786 // could be delayed during Parse (for example, in adjust_map_after_if()).
2787 // Execute transformation here to avoid barrier generation in such case.
2788 if (_gvn.type(newval) == TypePtr::NULL_PTR)
2789 newval = _gvn.makecon(TypePtr::NULL_PTR);
2790
2791 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2792 // Refine the value to a null constant, when it is known to be null
2793 oldval = _gvn.makecon(TypePtr::NULL_PTR);
2794 }
2795 }
2796
2797 Node* result = nullptr;
2798 switch (kind) {
2799 case LS_cmp_exchange: {
2800 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2801 oldval, newval, value_type, type, decorators);
2802 break;
2803 }
2804 case LS_cmp_swap_weak:
2951 Deoptimization::Action_make_not_entrant);
2952 }
2953 if (stopped()) {
2954 return true;
2955 }
2956 #endif //INCLUDE_JVMTI
2957
2958 Node* test = nullptr;
2959 if (LibraryCallKit::klass_needs_init_guard(kls)) {
2960 // Note: The argument might still be an illegal value like
2961 // Serializable.class or Object[].class. The runtime will handle it.
2962 // But we must make an explicit check for initialization.
2963 Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
2964 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
2965 // can generate code to load it as unsigned byte.
2966 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
2967 Node* bits = intcon(InstanceKlass::fully_initialized);
2968 test = _gvn.transform(new SubINode(inst, bits));
2969 // The 'test' is non-zero if we need to take a slow path.
2970 }
2971
2972 Node* obj = new_instance(kls, test);
2973 set_result(obj);
2974 return true;
2975 }
2976
2977 //------------------------inline_native_time_funcs--------------
2978 // inline code for System.currentTimeMillis() and System.nanoTime()
2979 // these have the same type and signature
2980 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
2981 const TypeFunc* tf = OptoRuntime::void_long_Type();
2982 const TypePtr* no_memory_effects = nullptr;
2983 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
2984 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
2985 #ifdef ASSERT
2986 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
2987 assert(value_top == top(), "second value must be top");
2988 #endif
2989 set_result(value);
2990 return true;
2991 }
2992
3733 Node* thread = _gvn.transform(new ThreadLocalNode());
3734 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
3735 Node* thread_obj_handle
3736 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3737 thread_obj_handle = _gvn.transform(thread_obj_handle);
3738 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3739 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3740
3741 // Change the _monitor_owner_id of the JavaThread
3742 Node* tid = load_field_from_object(arr, "tid", "J");
3743 Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3744 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3745
3746 JFR_ONLY(extend_setCurrentThread(thread, arr);)
3747 return true;
3748 }
3749
3750 const Type* LibraryCallKit::scopedValueCache_type() {
3751 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3752 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3753 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS);
3754
3755 // Because we create the scopedValue cache lazily we have to make the
3756 // type of the result BotPTR.
3757 bool xk = etype->klass_is_exact();
3758 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, 0);
3759 return objects_type;
3760 }
3761
3762 Node* LibraryCallKit::scopedValueCache_helper() {
3763 Node* thread = _gvn.transform(new ThreadLocalNode());
3764 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
3765 // We cannot use immutable_memory() because we might flip onto a
3766 // different carrier thread, at which point we'll need to use that
3767 // carrier thread's cache.
3768 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3769 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3770 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3771 }
3772
3773 //------------------------inline_native_scopedValueCache------------------
3774 bool LibraryCallKit::inline_native_scopedValueCache() {
3775 Node* cache_obj_handle = scopedValueCache_helper();
3776 const Type* objects_type = scopedValueCache_type();
3777 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3778
3862 store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
3863
3864 // Result of top level CFG and Memory.
3865 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3866 record_for_igvn(result_rgn);
3867 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3868 record_for_igvn(result_mem);
3869
3870 result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
3871 result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
3872 result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3873 result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
3874
3875 // Set output state.
3876 set_control(_gvn.transform(result_rgn));
3877 set_all_memory(_gvn.transform(result_mem));
3878
3879 return true;
3880 }
3881
3882 //---------------------------load_mirror_from_klass----------------------------
3883 // Given a klass oop, load its java mirror (a java.lang.Class oop).
3884 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
3885 Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
3886 Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3887 // mirror = ((OopHandle)mirror)->resolve();
3888 return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
3889 }
3890
3891 //-----------------------load_klass_from_mirror_common-------------------------
3892 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
3893 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
3894 // and branch to the given path on the region.
3895 // If never_see_null, take an uncommon trap on null, so we can optimistically
3896 // compile for the non-null case.
3897 // If the region is null, force never_see_null = true.
3898 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
3899 bool never_see_null,
3900 RegionNode* region,
3901 int null_path,
3902 int offset) {
3903 if (region == nullptr) never_see_null = true;
3904 Node* p = basic_plus_adr(mirror, offset);
3905 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
3906 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
3907 Node* null_ctl = top();
3908 kls = null_check_oop(kls, &null_ctl, never_see_null);
3909 if (region != nullptr) {
3910 // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
3914 }
3915 return kls;
3916 }
3917
3918 //--------------------(inline_native_Class_query helpers)---------------------
3919 // Use this for JVM_ACC_INTERFACE.
3920 // Fall through if (mods & mask) == bits, take the guard otherwise.
3921 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
3922 ByteSize offset, const Type* type, BasicType bt) {
3923 // Branch around if the given klass has the given modifier bit set.
3924 // Like generate_guard, adds a new path onto the region.
3925 Node* modp = basic_plus_adr(kls, in_bytes(offset));
3926 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
3927 Node* mask = intcon(modifier_mask);
3928 Node* bits = intcon(modifier_bits);
3929 Node* mbit = _gvn.transform(new AndINode(mods, mask));
3930 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
3931 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3932 return generate_fair_guard(bol, region);
3933 }
3934 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3935 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
3936 Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
3937 }
3938
3939 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
3940 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3941 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
3942 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
3943 }
3944
3945 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
3946 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
3947 }
3948
3949 //-------------------------inline_native_Class_query-------------------
3950 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
3951 const Type* return_type = TypeInt::BOOL;
3952 Node* prim_return_value = top(); // what happens if it's a primitive class?
3953 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4072
4073 case vmIntrinsics::_getClassAccessFlags:
4074 p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
4075 query_value = make_load(nullptr, p, TypeInt::CHAR, T_CHAR, MemNode::unordered);
4076 break;
4077
4078 default:
4079 fatal_unexpected_iid(id);
4080 break;
4081 }
4082
4083 // Fall-through is the normal case of a query to a real class.
4084 phi->init_req(1, query_value);
4085 region->init_req(1, control());
4086
4087 C->set_has_split_ifs(true); // Has chance for split-if optimization
4088 set_result(region, phi);
4089 return true;
4090 }
4091
4092 //-------------------------inline_Class_cast-------------------
4093 bool LibraryCallKit::inline_Class_cast() {
4094 Node* mirror = argument(0); // Class
4095 Node* obj = argument(1);
4096 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4097 if (mirror_con == nullptr) {
4098 return false; // dead path (mirror->is_top()).
4099 }
4100 if (obj == nullptr || obj->is_top()) {
4101 return false; // dead path
4102 }
4103 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4104
4105 // First, see if Class.cast() can be folded statically.
4106 // java_mirror_type() returns non-null for compile-time Class constants.
4107 ciType* tm = mirror_con->java_mirror_type();
4108 if (tm != nullptr && tm->is_klass() &&
4109 tp != nullptr) {
4110 if (!tp->is_loaded()) {
4111 // Don't use intrinsic when class is not loaded.
4112 return false;
4113 } else {
4114 int static_res = C->static_subtype_check(TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces), tp->as_klass_type());
4115 if (static_res == Compile::SSC_always_true) {
4116 // isInstance() is true - fold the code.
4117 set_result(obj);
4118 return true;
4119 } else if (static_res == Compile::SSC_always_false) {
4120 // Don't use intrinsic, have to throw ClassCastException.
4121 // If the reference is null, the non-intrinsic bytecode will
4122 // be optimized appropriately.
4123 return false;
4124 }
4125 }
4126 }
4127
4128 // Bailout intrinsic and do normal inlining if exception path is frequent.
4129 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4130 return false;
4131 }
4132
4133 // Generate dynamic checks.
4134 // Class.cast() is java implementation of _checkcast bytecode.
4135 // Do checkcast (Parse::do_checkcast()) optimizations here.
4136
4137 mirror = null_check(mirror);
4138 // If mirror is dead, only null-path is taken.
4139 if (stopped()) {
4140 return true;
4141 }
4142
4143 // Not-subtype or the mirror's klass ptr is null (in case it is a primitive).
4144 enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
4145 RegionNode* region = new RegionNode(PATH_LIMIT);
4146 record_for_igvn(region);
4147
4148 // Now load the mirror's klass metaobject, and null-check it.
4149 // If kls is null, we have a primitive mirror and
4150 // nothing is an instance of a primitive type.
4151 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4152
4153 Node* res = top();
4154 if (!stopped()) {
4155 Node* bad_type_ctrl = top();
4156 // Do checkcast optimizations.
4157 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4158 region->init_req(_bad_type_path, bad_type_ctrl);
4159 }
4160 if (region->in(_prim_path) != top() ||
4161 region->in(_bad_type_path) != top()) {
4162 // Let Interpreter throw ClassCastException.
4163 PreserveJVMState pjvms(this);
4164 set_control(_gvn.transform(region));
4165 uncommon_trap(Deoptimization::Reason_intrinsic,
4166 Deoptimization::Action_maybe_recompile);
4167 }
4168 if (!stopped()) {
4169 set_result(res);
4170 }
4171 return true;
4172 }
4173
4174
4175 //--------------------------inline_native_subtype_check------------------------
4176 // This intrinsic takes the JNI calls out of the heart of
4177 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4178 bool LibraryCallKit::inline_native_subtype_check() {
4179 // Pull both arguments off the stack.
4180 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4181 args[0] = argument(0);
4182 args[1] = argument(1);
4183 Node* klasses[2]; // corresponding Klasses: superk, subk
4184 klasses[0] = klasses[1] = top();
4185
4186 enum {
4187 // A full decision tree on {superc is prim, subc is prim}:
4188 _prim_0_path = 1, // {P,N} => false
4189 // {P,P} & superc!=subc => false
4190 _prim_same_path, // {P,P} & superc==subc => true
4191 _prim_1_path, // {N,P} => false
4192 _ref_subtype_path, // {N,N} & subtype check wins => true
4193 _both_ref_path, // {N,N} & subtype check loses => false
4194 PATH_LIMIT
4195 };
4196
4197 RegionNode* region = new RegionNode(PATH_LIMIT);
4198 Node* phi = new PhiNode(region, TypeInt::BOOL);
4199 record_for_igvn(region);
4200
4201 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4202 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4203 int class_klass_offset = java_lang_Class::klass_offset();
4204
4205 // First null-check both mirrors and load each mirror's klass metaobject.
4206 int which_arg;
4207 for (which_arg = 0; which_arg <= 1; which_arg++) {
4208 Node* arg = args[which_arg];
4209 arg = null_check(arg);
4210 if (stopped()) break;
4211 args[which_arg] = arg;
4212
4213 Node* p = basic_plus_adr(arg, class_klass_offset);
4214 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4215 klasses[which_arg] = _gvn.transform(kls);
4216 }
4217
4218 // Having loaded both klasses, test each for null.
4219 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4220 for (which_arg = 0; which_arg <= 1; which_arg++) {
4221 Node* kls = klasses[which_arg];
4222 Node* null_ctl = top();
4223 kls = null_check_oop(kls, &null_ctl, never_see_null);
4224 int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
4225 region->init_req(prim_path, null_ctl);
4226 if (stopped()) break;
4227 klasses[which_arg] = kls;
4228 }
4229
4230 if (!stopped()) {
4231 // now we have two reference types, in klasses[0..1]
4232 Node* subk = klasses[1]; // the argument to isAssignableFrom
4233 Node* superk = klasses[0]; // the receiver
4234 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4235 // now we have a successful reference subtype check
4236 region->set_req(_ref_subtype_path, control());
4237 }
4238
4239 // If both operands are primitive (both klasses null), then
4240 // we must return true when they are identical primitives.
4241 // It is convenient to test this after the first null klass check.
4242 set_control(region->in(_prim_0_path)); // go back to first null check
4243 if (!stopped()) {
4244 // Since superc is primitive, make a guard for the superc==subc case.
4245 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4246 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4247 generate_guard(bol_eq, region, PROB_FAIR);
4248 if (region->req() == PATH_LIMIT+1) {
4249 // A guard was added. If the added guard is taken, superc==subc.
4250 region->swap_edges(PATH_LIMIT, _prim_same_path);
4251 region->del_req(PATH_LIMIT);
4252 }
4253 region->set_req(_prim_0_path, control()); // Not equal after all.
4254 }
4255
4256 // these are the only paths that produce 'true':
4257 phi->set_req(_prim_same_path, intcon(1));
4258 phi->set_req(_ref_subtype_path, intcon(1));
4259
4260 // pull together the cases:
4261 assert(region->req() == PATH_LIMIT, "sane region");
4262 for (uint i = 1; i < region->req(); i++) {
4263 Node* ctl = region->in(i);
4264 if (ctl == nullptr || ctl == top()) {
4265 region->set_req(i, top());
4266 phi ->set_req(i, top());
4267 } else if (phi->in(i) == nullptr) {
4268 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4269 }
4270 }
4271
4272 set_control(_gvn.transform(region));
4273 set_result(_gvn.transform(phi));
4274 return true;
4275 }
4276
4277 //---------------------generate_array_guard_common------------------------
4278 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
4279 bool obj_array, bool not_array, Node** obj) {
4280
4281 if (stopped()) {
4282 return nullptr;
4283 }
4284
4285 // If obj_array/non_array==false/false:
4286 // Branch around if the given klass is in fact an array (either obj or prim).
4287 // If obj_array/non_array==false/true:
4288 // Branch around if the given klass is not an array klass of any kind.
4289 // If obj_array/non_array==true/true:
4290 // Branch around if the kls is not an oop array (kls is int[], String, etc.)
4291 // If obj_array/non_array==true/false:
4292 // Branch around if the kls is an oop array (Object[] or subtype)
4293 //
4294 // Like generate_guard, adds a new path onto the region.
4295 jint layout_con = 0;
4296 Node* layout_val = get_layout_helper(kls, layout_con);
4297 if (layout_val == nullptr) {
4298 bool query = (obj_array
4299 ? Klass::layout_helper_is_objArray(layout_con)
4300 : Klass::layout_helper_is_array(layout_con));
4301 if (query == not_array) {
4302 return nullptr; // never a branch
4303 } else { // always a branch
4304 Node* always_branch = control();
4305 if (region != nullptr)
4306 region->add_req(always_branch);
4307 set_control(top());
4308 return always_branch;
4309 }
4310 }
4311 // Now test the correct condition.
4312 jint nval = (obj_array
4313 ? (jint)(Klass::_lh_array_tag_type_value
4314 << Klass::_lh_array_tag_shift)
4315 : Klass::_lh_neutral_value);
4316 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4317 BoolTest::mask btest = BoolTest::lt; // correct for testing is_[obj]array
4318 // invert the test if we are looking for a non-array
4319 if (not_array) btest = BoolTest(btest).negate();
4320 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4321 Node* ctrl = generate_fair_guard(bol, region);
4322 Node* is_array_ctrl = not_array ? control() : ctrl;
4323 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4324 // Keep track of the fact that 'obj' is an array to prevent
4325 // array specific accesses from floating above the guard.
4326 *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4327 }
4328 return ctrl;
4329 }
4330
4331
4332 //-----------------------inline_native_newArray--------------------------
4333 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
4334 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4335 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4336 Node* mirror;
4337 Node* count_val;
4338 if (uninitialized) {
4339 null_check_receiver();
4340 mirror = argument(1);
4341 count_val = argument(2);
4342 } else {
4343 mirror = argument(0);
4344 count_val = argument(1);
4345 }
4346
4347 mirror = null_check(mirror);
4348 // If mirror or obj is dead, only null-path is taken.
4349 if (stopped()) return true;
4350
4351 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4352 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4353 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4459 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4460 { PreserveReexecuteState preexecs(this);
4461 jvms()->set_should_reexecute(true);
4462
4463 array_type_mirror = null_check(array_type_mirror);
4464 original = null_check(original);
4465
4466 // Check if a null path was taken unconditionally.
4467 if (stopped()) return true;
4468
4469 Node* orig_length = load_array_length(original);
4470
4471 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4472 klass_node = null_check(klass_node);
4473
4474 RegionNode* bailout = new RegionNode(1);
4475 record_for_igvn(bailout);
4476
4477 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4478 // Bail out if that is so.
4479 Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
4480 if (not_objArray != nullptr) {
4481 // Improve the klass node's type from the new optimistic assumption:
4482 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4483 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
4484 Node* cast = new CastPPNode(control(), klass_node, akls);
4485 klass_node = _gvn.transform(cast);
4486 }
4487
4488 // Bail out if either start or end is negative.
4489 generate_negative_guard(start, bailout, &start);
4490 generate_negative_guard(end, bailout, &end);
4491
4492 Node* length = end;
4493 if (_gvn.type(start) != TypeInt::ZERO) {
4494 length = _gvn.transform(new SubINode(end, start));
4495 }
4496
4497 // Bail out if length is negative (i.e., if start > end).
4498 // Without this the new_array would throw
4499 // NegativeArraySizeException but IllegalArgumentException is what
4500 // should be thrown
4501 generate_negative_guard(length, bailout, &length);
4502
4503 // Bail out if start is larger than the original length
4504 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4505 generate_negative_guard(orig_tail, bailout, &orig_tail);
4506
4507 if (bailout->req() > 1) {
4508 PreserveJVMState pjvms(this);
4509 set_control(_gvn.transform(bailout));
4510 uncommon_trap(Deoptimization::Reason_intrinsic,
4511 Deoptimization::Action_maybe_recompile);
4512 }
4513
4514 if (!stopped()) {
4515 // How many elements will we copy from the original?
4516 // The answer is MinI(orig_tail, length).
4517 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4518
4519 // Generate a direct call to the right arraycopy function(s).
4520 // We know the copy is disjoint but we might not know if the
4521 // oop stores need checking.
4522 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
4528 // to the copyOf to be validated, including that the copy to the
4529 // new array won't trigger an ArrayStoreException. That subtype
4530 // check can be optimized if we know something on the type of
4531 // the input array from type speculation.
4532 if (_gvn.type(klass_node)->singleton()) {
4533 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
4534 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
4535
4536 int test = C->static_subtype_check(superk, subk);
4537 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4538 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4539 if (t_original->speculative_type() != nullptr) {
4540 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4541 }
4542 }
4543 }
4544
4545 bool validated = false;
4546 // Reason_class_check rather than Reason_intrinsic because we
4547 // want to intrinsify even if this traps.
4548 if (!too_many_traps(Deoptimization::Reason_class_check)) {
4549 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4550
4551 if (not_subtype_ctrl != top()) {
4552 PreserveJVMState pjvms(this);
4553 set_control(not_subtype_ctrl);
4554 uncommon_trap(Deoptimization::Reason_class_check,
4555 Deoptimization::Action_make_not_entrant);
4556 assert(stopped(), "Should be stopped");
4557 }
4558 validated = true;
4559 }
4560
4561 if (!stopped()) {
4562 newcopy = new_array(klass_node, length, 0); // no arguments to push
4563
4564 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4565 load_object_klass(original), klass_node);
4566 if (!is_copyOfRange) {
4567 ac->set_copyof(validated);
4568 } else {
4614
4615 //-----------------------generate_method_call----------------------------
4616 // Use generate_method_call to make a slow-call to the real
4617 // method if the fast path fails. An alternative would be to
4618 // use a stub like OptoRuntime::slow_arraycopy_Java.
4619 // This only works for expanding the current library call,
4620 // not another intrinsic. (E.g., don't use this for making an
4621 // arraycopy call inside of the copyOf intrinsic.)
4622 CallJavaNode*
4623 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4624 // When compiling the intrinsic method itself, do not use this technique.
4625 guarantee(callee() != C->method(), "cannot make slow-call to self");
4626
4627 ciMethod* method = callee();
4628 // ensure the JVMS we have will be correct for this call
4629 guarantee(method_id == method->intrinsic_id(), "must match");
4630
4631 const TypeFunc* tf = TypeFunc::make(method);
4632 if (res_not_null) {
4633 assert(tf->return_type() == T_OBJECT, "");
4634 const TypeTuple* range = tf->range();
4635 const Type** fields = TypeTuple::fields(range->cnt());
4636 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4637 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4638 tf = TypeFunc::make(tf->domain(), new_range);
4639 }
4640 CallJavaNode* slow_call;
4641 if (is_static) {
4642 assert(!is_virtual, "");
4643 slow_call = new CallStaticJavaNode(C, tf,
4644 SharedRuntime::get_resolve_static_call_stub(), method);
4645 } else if (is_virtual) {
4646 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4647 int vtable_index = Method::invalid_vtable_index;
4648 if (UseInlineCaches) {
4649 // Suppress the vtable call
4650 } else {
4651 // hashCode and clone are not a miranda methods,
4652 // so the vtable index is fixed.
4653 // No need to use the linkResolver to get it.
4654 vtable_index = method->vtable_index();
4655 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4656 "bad index %d", vtable_index);
4657 }
4658 slow_call = new CallDynamicJavaNode(tf,
4675 set_edges_for_java_call(slow_call);
4676 return slow_call;
4677 }
4678
4679
4680 /**
4681 * Build special case code for calls to hashCode on an object. This call may
4682 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4683 * slightly different code.
4684 */
4685 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4686 assert(is_static == callee()->is_static(), "correct intrinsic selection");
4687 assert(!(is_virtual && is_static), "either virtual, special, or static");
4688
4689 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4690
4691 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4692 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
4693 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
4694 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4695 Node* obj = nullptr;
4696 if (!is_static) {
4697 // Check for hashing null object
4698 obj = null_check_receiver();
4699 if (stopped()) return true; // unconditionally null
4700 result_reg->init_req(_null_path, top());
4701 result_val->init_req(_null_path, top());
4702 } else {
4703 // Do a null check, and return zero if null.
4704 // System.identityHashCode(null) == 0
4705 obj = argument(0);
4706 Node* null_ctl = top();
4707 obj = null_check_oop(obj, &null_ctl);
4708 result_reg->init_req(_null_path, null_ctl);
4709 result_val->init_req(_null_path, _gvn.intcon(0));
4710 }
4711
4712 // Unconditionally null? Then return right away.
4713 if (stopped()) {
4714 set_control( result_reg->in(_null_path));
4715 if (!stopped())
4716 set_result(result_val->in(_null_path));
4717 return true;
4718 }
4719
4720 // We only go to the fast case code if we pass a number of guards. The
4721 // paths which do not pass are accumulated in the slow_region.
4722 RegionNode* slow_region = new RegionNode(1);
4723 record_for_igvn(slow_region);
4724
4725 // If this is a virtual call, we generate a funny guard. We pull out
4726 // the vtable entry corresponding to hashCode() from the target object.
4727 // If the target method which we are calling happens to be the native
4728 // Object hashCode() method, we pass the guard. We do not need this
4729 // guard for non-virtual calls -- the caller is known to be the native
4730 // Object hashCode().
4731 if (is_virtual) {
4732 // After null check, get the object's klass.
4733 Node* obj_klass = load_object_klass(obj);
4734 generate_virtual_guard(obj_klass, slow_region);
4735 }
4736
4737 // Get the header out of the object, use LoadMarkNode when available
4738 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4739 // The control of the load must be null. Otherwise, the load can move before
4740 // the null check after castPP removal.
4741 Node* no_ctrl = nullptr;
4742 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4743
4744 if (!UseObjectMonitorTable) {
4745 // Test the header to see if it is safe to read w.r.t. locking.
4746 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
4747 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4748 if (LockingMode == LM_LIGHTWEIGHT) {
4749 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
4750 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
4751 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
4752
4753 generate_slow_guard(test_monitor, slow_region);
4754 } else {
4755 Node *unlocked_val = _gvn.MakeConX(markWord::unlocked_value);
4756 Node *chk_unlocked = _gvn.transform(new CmpXNode(lmasked_header, unlocked_val));
4757 Node *test_not_unlocked = _gvn.transform(new BoolNode(chk_unlocked, BoolTest::ne));
4758
4759 generate_slow_guard(test_not_unlocked, slow_region);
4760 }
4761 }
4762
4763 // Get the hash value and check to see that it has been properly assigned.
4764 // We depend on hash_mask being at most 32 bits and avoid the use of
4765 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4766 // vm: see markWord.hpp.
4801 // this->control() comes from set_results_for_java_call
4802 result_reg->init_req(_slow_path, control());
4803 result_val->init_req(_slow_path, slow_result);
4804 result_io ->set_req(_slow_path, i_o());
4805 result_mem ->set_req(_slow_path, reset_memory());
4806 }
4807
4808 // Return the combined state.
4809 set_i_o( _gvn.transform(result_io) );
4810 set_all_memory( _gvn.transform(result_mem));
4811
4812 set_result(result_reg, result_val);
4813 return true;
4814 }
4815
4816 //---------------------------inline_native_getClass----------------------------
4817 // public final native Class<?> java.lang.Object.getClass();
4818 //
4819 // Build special case code for calls to getClass on an object.
4820 bool LibraryCallKit::inline_native_getClass() {
4821 Node* obj = null_check_receiver();
4822 if (stopped()) return true;
4823 set_result(load_mirror_from_klass(load_object_klass(obj)));
4824 return true;
4825 }
4826
4827 //-----------------inline_native_Reflection_getCallerClass---------------------
4828 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4829 //
4830 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4831 //
4832 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4833 // in that it must skip particular security frames and checks for
4834 // caller sensitive methods.
4835 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4836 #ifndef PRODUCT
4837 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4838 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4839 }
4840 #endif
4841
5153 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5154
5155 flags |= RC_NARROW_MEM; // narrow in memory
5156 }
5157
5158 // Call it. Note that the length argument is not scaled.
5159 make_runtime_call(flags,
5160 OptoRuntime::unsafe_setmemory_Type(),
5161 StubRoutines::unsafe_setmemory(),
5162 "unsafe_setmemory",
5163 dst_type,
5164 dst_addr, size XTOP, byte);
5165
5166 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5167
5168 return true;
5169 }
5170
5171 #undef XTOP
5172
5173 //------------------------clone_coping-----------------------------------
5174 // Helper function for inline_native_clone.
5175 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5176 assert(obj_size != nullptr, "");
5177 Node* raw_obj = alloc_obj->in(1);
5178 assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5179
5180 AllocateNode* alloc = nullptr;
5181 if (ReduceBulkZeroing &&
5182 // If we are implementing an array clone without knowing its source type
5183 // (can happen when compiling the array-guarded branch of a reflective
5184 // Object.clone() invocation), initialize the array within the allocation.
5185 // This is needed because some GCs (e.g. ZGC) might fall back in this case
5186 // to a runtime clone call that assumes fully initialized source arrays.
5187 (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5188 // We will be completely responsible for initializing this object -
5189 // mark Initialize node as complete.
5190 alloc = AllocateNode::Ideal_allocation(alloc_obj);
5191 // The object was just allocated - there should be no any stores!
5192 guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5223 // not cloneable or finalizer => slow path to out-of-line Object.clone
5224 //
5225 // The general case has two steps, allocation and copying.
5226 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5227 //
5228 // Copying also has two cases, oop arrays and everything else.
5229 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5230 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5231 //
5232 // These steps fold up nicely if and when the cloned object's klass
5233 // can be sharply typed as an object array, a type array, or an instance.
5234 //
5235 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5236 PhiNode* result_val;
5237
5238 // Set the reexecute bit for the interpreter to reexecute
5239 // the bytecode that invokes Object.clone if deoptimization happens.
5240 { PreserveReexecuteState preexecs(this);
5241 jvms()->set_should_reexecute(true);
5242
5243 Node* obj = null_check_receiver();
5244 if (stopped()) return true;
5245
5246 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5247
5248 // If we are going to clone an instance, we need its exact type to
5249 // know the number and types of fields to convert the clone to
5250 // loads/stores. Maybe a speculative type can help us.
5251 if (!obj_type->klass_is_exact() &&
5252 obj_type->speculative_type() != nullptr &&
5253 obj_type->speculative_type()->is_instance_klass()) {
5254 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5255 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5256 !spec_ik->has_injected_fields()) {
5257 if (!obj_type->isa_instptr() ||
5258 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5259 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5260 }
5261 }
5262 }
5263
5264 // Conservatively insert a memory barrier on all memory slices.
5265 // Do not let writes into the original float below the clone.
5266 insert_mem_bar(Op_MemBarCPUOrder);
5267
5268 // paths into result_reg:
5269 enum {
5270 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5271 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5272 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5273 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5274 PATH_LIMIT
5275 };
5276 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5277 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5278 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5279 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5280 record_for_igvn(result_reg);
5281
5282 Node* obj_klass = load_object_klass(obj);
5283 Node* array_obj = obj;
5284 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5285 if (array_ctl != nullptr) {
5286 // It's an array.
5287 PreserveJVMState pjvms(this);
5288 set_control(array_ctl);
5289 Node* obj_length = load_array_length(array_obj);
5290 Node* array_size = nullptr; // Size of the array without object alignment padding.
5291 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5292
5293 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5294 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5295 // If it is an oop array, it requires very special treatment,
5296 // because gc barriers are required when accessing the array.
5297 Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5298 if (is_obja != nullptr) {
5299 PreserveJVMState pjvms2(this);
5300 set_control(is_obja);
5301 // Generate a direct call to the right arraycopy function(s).
5302 // Clones are always tightly coupled.
5303 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5304 ac->set_clone_oop_array();
5305 Node* n = _gvn.transform(ac);
5306 assert(n == ac, "cannot disappear");
5307 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5308
5309 result_reg->init_req(_objArray_path, control());
5310 result_val->init_req(_objArray_path, alloc_obj);
5311 result_i_o ->set_req(_objArray_path, i_o());
5312 result_mem ->set_req(_objArray_path, reset_memory());
5313 }
5314 }
5315 // Otherwise, there are no barriers to worry about.
5316 // (We can dispense with card marks if we know the allocation
5317 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5318 // causes the non-eden paths to take compensating steps to
5319 // simulate a fresh allocation, so that no further
5320 // card marks are required in compiled code to initialize
5321 // the object.)
5322
5323 if (!stopped()) {
5324 copy_to_clone(array_obj, alloc_obj, array_size, true);
5325
5326 // Present the results of the copy.
5327 result_reg->init_req(_array_path, control());
5328 result_val->init_req(_array_path, alloc_obj);
5329 result_i_o ->set_req(_array_path, i_o());
5330 result_mem ->set_req(_array_path, reset_memory());
5331 }
5332 }
5333
5334 // We only go to the instance fast case code if we pass a number of guards.
5335 // The paths which do not pass are accumulated in the slow_region.
5336 RegionNode* slow_region = new RegionNode(1);
5337 record_for_igvn(slow_region);
5338 if (!stopped()) {
5339 // It's an instance (we did array above). Make the slow-path tests.
5340 // If this is a virtual call, we generate a funny guard. We grab
5341 // the vtable entry corresponding to clone() from the target object.
5342 // If the target method which we are calling happens to be the
5343 // Object clone() method, we pass the guard. We do not need this
5344 // guard for non-virtual calls; the caller is known to be the native
5345 // Object clone().
5346 if (is_virtual) {
5347 generate_virtual_guard(obj_klass, slow_region);
5348 }
5349
5350 // The object must be easily cloneable and must not have a finalizer.
5351 // Both of these conditions may be checked in a single test.
5352 // We could optimize the test further, but we don't care.
5353 generate_misc_flags_guard(obj_klass,
5354 // Test both conditions:
5355 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5356 // Must be cloneable but not finalizer:
5357 KlassFlags::_misc_is_cloneable_fast,
5449 set_jvms(sfpt->jvms());
5450 _reexecute_sp = jvms()->sp();
5451
5452 return saved_jvms;
5453 }
5454 }
5455 }
5456 return nullptr;
5457 }
5458
5459 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5460 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5461 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5462 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5463 uint size = alloc->req();
5464 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5465 old_jvms->set_map(sfpt);
5466 for (uint i = 0; i < size; i++) {
5467 sfpt->init_req(i, alloc->in(i));
5468 }
5469 // re-push array length for deoptimization
5470 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
5471 old_jvms->set_sp(old_jvms->sp()+1);
5472 old_jvms->set_monoff(old_jvms->monoff()+1);
5473 old_jvms->set_scloff(old_jvms->scloff()+1);
5474 old_jvms->set_endoff(old_jvms->endoff()+1);
5475 old_jvms->set_should_reexecute(true);
5476
5477 sfpt->set_i_o(map()->i_o());
5478 sfpt->set_memory(map()->memory());
5479 sfpt->set_control(map()->control());
5480 return sfpt;
5481 }
5482
5483 // In case of a deoptimization, we restart execution at the
5484 // allocation, allocating a new array. We would leave an uninitialized
5485 // array in the heap that GCs wouldn't expect. Move the allocation
5486 // after the traps so we don't allocate the array if we
5487 // deoptimize. This is possible because tightly_coupled_allocation()
5488 // guarantees there's no observer of the allocated array at this point
5489 // and the control flow is simple enough.
5490 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5491 int saved_reexecute_sp, uint new_idx) {
5492 if (saved_jvms_before_guards != nullptr && !stopped()) {
5493 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5494
5495 assert(alloc != nullptr, "only with a tightly coupled allocation");
5496 // restore JVM state to the state at the arraycopy
5497 saved_jvms_before_guards->map()->set_control(map()->control());
5498 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5499 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5500 // If we've improved the types of some nodes (null check) while
5501 // emitting the guards, propagate them to the current state
5502 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5503 set_jvms(saved_jvms_before_guards);
5504 _reexecute_sp = saved_reexecute_sp;
5505
5506 // Remove the allocation from above the guards
5507 CallProjections callprojs;
5508 alloc->extract_projections(&callprojs, true);
5509 InitializeNode* init = alloc->initialization();
5510 Node* alloc_mem = alloc->in(TypeFunc::Memory);
5511 C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5512 C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
5513
5514 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5515 // the allocation (i.e. is only valid if the allocation succeeds):
5516 // 1) replace CastIINode with AllocateArrayNode's length here
5517 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5518 //
5519 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5520 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5521 Node* init_control = init->proj_out(TypeFunc::Control);
5522 Node* alloc_length = alloc->Ideal_length();
5523 #ifdef ASSERT
5524 Node* prev_cast = nullptr;
5525 #endif
5526 for (uint i = 0; i < init_control->outcnt(); i++) {
5527 Node* init_out = init_control->raw_out(i);
5528 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5529 #ifdef ASSERT
5530 if (prev_cast == nullptr) {
5531 prev_cast = init_out;
5533 if (prev_cast->cmp(*init_out) == false) {
5534 prev_cast->dump();
5535 init_out->dump();
5536 assert(false, "not equal CastIINode");
5537 }
5538 }
5539 #endif
5540 C->gvn_replace_by(init_out, alloc_length);
5541 }
5542 }
5543 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5544
5545 // move the allocation here (after the guards)
5546 _gvn.hash_delete(alloc);
5547 alloc->set_req(TypeFunc::Control, control());
5548 alloc->set_req(TypeFunc::I_O, i_o());
5549 Node *mem = reset_memory();
5550 set_all_memory(mem);
5551 alloc->set_req(TypeFunc::Memory, mem);
5552 set_control(init->proj_out_or_null(TypeFunc::Control));
5553 set_i_o(callprojs.fallthrough_ioproj);
5554
5555 // Update memory as done in GraphKit::set_output_for_allocation()
5556 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5557 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5558 if (ary_type->isa_aryptr() && length_type != nullptr) {
5559 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5560 }
5561 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5562 int elemidx = C->get_alias_index(telemref);
5563 set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
5564 set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
5565
5566 Node* allocx = _gvn.transform(alloc);
5567 assert(allocx == alloc, "where has the allocation gone?");
5568 assert(dest->is_CheckCastPP(), "not an allocation result?");
5569
5570 _gvn.hash_delete(dest);
5571 dest->set_req(0, control());
5572 Node* destx = _gvn.transform(dest);
5573 assert(destx == dest, "where has the allocation result gone?");
5871 top_src = src_type->isa_aryptr();
5872 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5873 src_spec = true;
5874 }
5875 if (!has_dest) {
5876 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5877 dest_type = _gvn.type(dest);
5878 top_dest = dest_type->isa_aryptr();
5879 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5880 dest_spec = true;
5881 }
5882 }
5883 }
5884
5885 if (has_src && has_dest && can_emit_guards) {
5886 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
5887 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
5888 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
5889 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
5890
5891 if (src_elem == dest_elem && src_elem == T_OBJECT) {
5892 // If both arrays are object arrays then having the exact types
5893 // for both will remove the need for a subtype check at runtime
5894 // before the call and may make it possible to pick a faster copy
5895 // routine (without a subtype check on every element)
5896 // Do we have the exact type of src?
5897 bool could_have_src = src_spec;
5898 // Do we have the exact type of dest?
5899 bool could_have_dest = dest_spec;
5900 ciKlass* src_k = nullptr;
5901 ciKlass* dest_k = nullptr;
5902 if (!src_spec) {
5903 src_k = src_type->speculative_type_not_null();
5904 if (src_k != nullptr && src_k->is_array_klass()) {
5905 could_have_src = true;
5906 }
5907 }
5908 if (!dest_spec) {
5909 dest_k = dest_type->speculative_type_not_null();
5910 if (dest_k != nullptr && dest_k->is_array_klass()) {
5911 could_have_dest = true;
5912 }
5913 }
5914 if (could_have_src && could_have_dest) {
5915 // If we can have both exact types, emit the missing guards
5916 if (could_have_src && !src_spec) {
5917 src = maybe_cast_profiled_obj(src, src_k, true);
5918 }
5919 if (could_have_dest && !dest_spec) {
5920 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5921 }
5922 }
5923 }
5924 }
5925
5926 ciMethod* trap_method = method();
5927 int trap_bci = bci();
5928 if (saved_jvms_before_guards != nullptr) {
5929 trap_method = alloc->jvms()->method();
5930 trap_bci = alloc->jvms()->bci();
5931 }
5932
5933 bool negative_length_guard_generated = false;
5934
5935 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5936 can_emit_guards &&
5937 !src->is_top() && !dest->is_top()) {
5938 // validate arguments: enables transformation the ArrayCopyNode
5939 validated = true;
5940
5941 RegionNode* slow_region = new RegionNode(1);
5942 record_for_igvn(slow_region);
5943
5944 // (1) src and dest are arrays.
5945 generate_non_array_guard(load_object_klass(src), slow_region, &src);
5946 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
5947
5948 // (2) src and dest arrays must have elements of the same BasicType
5949 // done at macro expansion or at Ideal transformation time
5950
5951 // (4) src_offset must not be negative.
5952 generate_negative_guard(src_offset, slow_region);
5953
5954 // (5) dest_offset must not be negative.
5955 generate_negative_guard(dest_offset, slow_region);
5956
5957 // (7) src_offset + length must not exceed length of src.
5960 slow_region);
5961
5962 // (8) dest_offset + length must not exceed length of dest.
5963 generate_limit_guard(dest_offset, length,
5964 load_array_length(dest),
5965 slow_region);
5966
5967 // (6) length must not be negative.
5968 // This is also checked in generate_arraycopy() during macro expansion, but
5969 // we also have to check it here for the case where the ArrayCopyNode will
5970 // be eliminated by Escape Analysis.
5971 if (EliminateAllocations) {
5972 generate_negative_guard(length, slow_region);
5973 negative_length_guard_generated = true;
5974 }
5975
5976 // (9) each element of an oop array must be assignable
5977 Node* dest_klass = load_object_klass(dest);
5978 if (src != dest) {
5979 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
5980
5981 if (not_subtype_ctrl != top()) {
5982 PreserveJVMState pjvms(this);
5983 set_control(not_subtype_ctrl);
5984 uncommon_trap(Deoptimization::Reason_intrinsic,
5985 Deoptimization::Action_make_not_entrant);
5986 assert(stopped(), "Should be stopped");
5987 }
5988 }
5989 {
5990 PreserveJVMState pjvms(this);
5991 set_control(_gvn.transform(slow_region));
5992 uncommon_trap(Deoptimization::Reason_intrinsic,
5993 Deoptimization::Action_make_not_entrant);
5994 assert(stopped(), "Should be stopped");
5995 }
5996
5997 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
5998 const Type *toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
5999 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6000 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6001 }
6002
6003 if (stopped()) {
6004 return true;
6005 }
6006
6007 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6008 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6009 // so the compiler has a chance to eliminate them: during macro expansion,
6010 // we have to set their control (CastPP nodes are eliminated).
6011 load_object_klass(src), load_object_klass(dest),
6012 load_array_length(src), load_array_length(dest));
6013
6014 ac->set_arraycopy(validated);
6015
6016 Node* n = _gvn.transform(ac);
6017 if (n == ac) {
6018 ac->connect_outputs(this);
6019 } 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/ciArrayKlass.hpp"
27 #include "ci/ciFlatArrayKlass.hpp"
28 #include "ci/ciInstanceKlass.hpp"
29 #include "ci/ciUtilities.inline.hpp"
30 #include "ci/ciSymbols.hpp"
31 #include "classfile/vmIntrinsics.hpp"
32 #include "compiler/compileBroker.hpp"
33 #include "compiler/compileLog.hpp"
34 #include "gc/shared/barrierSet.hpp"
35 #include "gc/shared/c2/barrierSetC2.hpp"
36 #include "jfr/support/jfrIntrinsics.hpp"
37 #include "memory/resourceArea.hpp"
38 #include "oops/accessDecorators.hpp"
39 #include "oops/klass.inline.hpp"
40 #include "oops/layoutKind.hpp"
41 #include "oops/objArrayKlass.hpp"
42 #include "opto/addnode.hpp"
43 #include "opto/arraycopynode.hpp"
44 #include "opto/c2compiler.hpp"
45 #include "opto/castnode.hpp"
46 #include "opto/cfgnode.hpp"
47 #include "opto/convertnode.hpp"
48 #include "opto/countbitsnode.hpp"
49 #include "opto/graphKit.hpp"
50 #include "opto/idealKit.hpp"
51 #include "opto/library_call.hpp"
52 #include "opto/inlinetypenode.hpp"
53 #include "opto/mathexactnode.hpp"
54 #include "opto/mulnode.hpp"
55 #include "opto/narrowptrnode.hpp"
56 #include "opto/opaquenode.hpp"
57 #include "opto/opcodes.hpp"
58 #include "opto/parse.hpp"
59 #include "opto/runtime.hpp"
60 #include "opto/rootnode.hpp"
61 #include "opto/subnode.hpp"
62 #include "opto/type.hpp"
63 #include "opto/vectornode.hpp"
64 #include "prims/jvmtiExport.hpp"
65 #include "prims/jvmtiThreadState.hpp"
66 #include "prims/unsafe.hpp"
67 #include "runtime/jniHandles.inline.hpp"
68 #include "runtime/objectMonitor.hpp"
69 #include "runtime/sharedRuntime.hpp"
70 #include "runtime/stubRoutines.hpp"
71 #include "utilities/globalDefinitions.hpp"
72 #include "utilities/macros.hpp"
73 #include "utilities/powerOfTwo.hpp"
74
75 //---------------------------make_vm_intrinsic----------------------------
76 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
77 vmIntrinsicID id = m->intrinsic_id();
78 assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
79
80 if (!m->is_loaded()) {
81 // Do not attempt to inline unloaded methods.
82 return nullptr;
83 }
84
85 C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
86 bool is_available = false;
87
88 {
89 // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
90 // the compiler must transition to '_thread_in_vm' state because both
91 // methods access VM-internal data.
309 case vmIntrinsics::_indexOfIL: return inline_string_indexOfI(StrIntrinsicNode::LL);
310 case vmIntrinsics::_indexOfIU: return inline_string_indexOfI(StrIntrinsicNode::UU);
311 case vmIntrinsics::_indexOfIUL: return inline_string_indexOfI(StrIntrinsicNode::UL);
312 case vmIntrinsics::_indexOfU_char: return inline_string_indexOfChar(StrIntrinsicNode::U);
313 case vmIntrinsics::_indexOfL_char: return inline_string_indexOfChar(StrIntrinsicNode::L);
314
315 case vmIntrinsics::_equalsL: return inline_string_equals(StrIntrinsicNode::LL);
316
317 case vmIntrinsics::_vectorizedHashCode: return inline_vectorizedHashCode();
318
319 case vmIntrinsics::_toBytesStringU: return inline_string_toBytesU();
320 case vmIntrinsics::_getCharsStringU: return inline_string_getCharsU();
321 case vmIntrinsics::_getCharStringU: return inline_string_char_access(!is_store);
322 case vmIntrinsics::_putCharStringU: return inline_string_char_access( is_store);
323
324 case vmIntrinsics::_compressStringC:
325 case vmIntrinsics::_compressStringB: return inline_string_copy( is_compress);
326 case vmIntrinsics::_inflateStringC:
327 case vmIntrinsics::_inflateStringB: return inline_string_copy(!is_compress);
328
329 case vmIntrinsics::_makePrivateBuffer: return inline_unsafe_make_private_buffer();
330 case vmIntrinsics::_finishPrivateBuffer: return inline_unsafe_finish_private_buffer();
331 case vmIntrinsics::_getReference: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false);
332 case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_store, T_BOOLEAN, Relaxed, false);
333 case vmIntrinsics::_getByte: return inline_unsafe_access(!is_store, T_BYTE, Relaxed, false);
334 case vmIntrinsics::_getShort: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, false);
335 case vmIntrinsics::_getChar: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, false);
336 case vmIntrinsics::_getInt: return inline_unsafe_access(!is_store, T_INT, Relaxed, false);
337 case vmIntrinsics::_getLong: return inline_unsafe_access(!is_store, T_LONG, Relaxed, false);
338 case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_store, T_FLOAT, Relaxed, false);
339 case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_store, T_DOUBLE, Relaxed, false);
340 case vmIntrinsics::_getValue: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false, true);
341
342 case vmIntrinsics::_putReference: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false);
343 case vmIntrinsics::_putBoolean: return inline_unsafe_access( is_store, T_BOOLEAN, Relaxed, false);
344 case vmIntrinsics::_putByte: return inline_unsafe_access( is_store, T_BYTE, Relaxed, false);
345 case vmIntrinsics::_putShort: return inline_unsafe_access( is_store, T_SHORT, Relaxed, false);
346 case vmIntrinsics::_putChar: return inline_unsafe_access( is_store, T_CHAR, Relaxed, false);
347 case vmIntrinsics::_putInt: return inline_unsafe_access( is_store, T_INT, Relaxed, false);
348 case vmIntrinsics::_putLong: return inline_unsafe_access( is_store, T_LONG, Relaxed, false);
349 case vmIntrinsics::_putFloat: return inline_unsafe_access( is_store, T_FLOAT, Relaxed, false);
350 case vmIntrinsics::_putDouble: return inline_unsafe_access( is_store, T_DOUBLE, Relaxed, false);
351 case vmIntrinsics::_putValue: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false, true);
352
353 case vmIntrinsics::_getReferenceVolatile: return inline_unsafe_access(!is_store, T_OBJECT, Volatile, false);
354 case vmIntrinsics::_getBooleanVolatile: return inline_unsafe_access(!is_store, T_BOOLEAN, Volatile, false);
355 case vmIntrinsics::_getByteVolatile: return inline_unsafe_access(!is_store, T_BYTE, Volatile, false);
356 case vmIntrinsics::_getShortVolatile: return inline_unsafe_access(!is_store, T_SHORT, Volatile, false);
357 case vmIntrinsics::_getCharVolatile: return inline_unsafe_access(!is_store, T_CHAR, Volatile, false);
358 case vmIntrinsics::_getIntVolatile: return inline_unsafe_access(!is_store, T_INT, Volatile, false);
359 case vmIntrinsics::_getLongVolatile: return inline_unsafe_access(!is_store, T_LONG, Volatile, false);
360 case vmIntrinsics::_getFloatVolatile: return inline_unsafe_access(!is_store, T_FLOAT, Volatile, false);
361 case vmIntrinsics::_getDoubleVolatile: return inline_unsafe_access(!is_store, T_DOUBLE, Volatile, false);
362
363 case vmIntrinsics::_putReferenceVolatile: return inline_unsafe_access( is_store, T_OBJECT, Volatile, false);
364 case vmIntrinsics::_putBooleanVolatile: return inline_unsafe_access( is_store, T_BOOLEAN, Volatile, false);
365 case vmIntrinsics::_putByteVolatile: return inline_unsafe_access( is_store, T_BYTE, Volatile, false);
366 case vmIntrinsics::_putShortVolatile: return inline_unsafe_access( is_store, T_SHORT, Volatile, false);
367 case vmIntrinsics::_putCharVolatile: return inline_unsafe_access( is_store, T_CHAR, Volatile, false);
368 case vmIntrinsics::_putIntVolatile: return inline_unsafe_access( is_store, T_INT, Volatile, false);
369 case vmIntrinsics::_putLongVolatile: return inline_unsafe_access( is_store, T_LONG, Volatile, false);
370 case vmIntrinsics::_putFloatVolatile: return inline_unsafe_access( is_store, T_FLOAT, Volatile, false);
371 case vmIntrinsics::_putDoubleVolatile: return inline_unsafe_access( is_store, T_DOUBLE, Volatile, false);
403 case vmIntrinsics::_getReferenceOpaque: return inline_unsafe_access(!is_store, T_OBJECT, Opaque, false);
404 case vmIntrinsics::_getBooleanOpaque: return inline_unsafe_access(!is_store, T_BOOLEAN, Opaque, false);
405 case vmIntrinsics::_getByteOpaque: return inline_unsafe_access(!is_store, T_BYTE, Opaque, false);
406 case vmIntrinsics::_getShortOpaque: return inline_unsafe_access(!is_store, T_SHORT, Opaque, false);
407 case vmIntrinsics::_getCharOpaque: return inline_unsafe_access(!is_store, T_CHAR, Opaque, false);
408 case vmIntrinsics::_getIntOpaque: return inline_unsafe_access(!is_store, T_INT, Opaque, false);
409 case vmIntrinsics::_getLongOpaque: return inline_unsafe_access(!is_store, T_LONG, Opaque, false);
410 case vmIntrinsics::_getFloatOpaque: return inline_unsafe_access(!is_store, T_FLOAT, Opaque, false);
411 case vmIntrinsics::_getDoubleOpaque: return inline_unsafe_access(!is_store, T_DOUBLE, Opaque, false);
412
413 case vmIntrinsics::_putReferenceOpaque: return inline_unsafe_access( is_store, T_OBJECT, Opaque, false);
414 case vmIntrinsics::_putBooleanOpaque: return inline_unsafe_access( is_store, T_BOOLEAN, Opaque, false);
415 case vmIntrinsics::_putByteOpaque: return inline_unsafe_access( is_store, T_BYTE, Opaque, false);
416 case vmIntrinsics::_putShortOpaque: return inline_unsafe_access( is_store, T_SHORT, Opaque, false);
417 case vmIntrinsics::_putCharOpaque: return inline_unsafe_access( is_store, T_CHAR, Opaque, false);
418 case vmIntrinsics::_putIntOpaque: return inline_unsafe_access( is_store, T_INT, Opaque, false);
419 case vmIntrinsics::_putLongOpaque: return inline_unsafe_access( is_store, T_LONG, Opaque, false);
420 case vmIntrinsics::_putFloatOpaque: return inline_unsafe_access( is_store, T_FLOAT, Opaque, false);
421 case vmIntrinsics::_putDoubleOpaque: return inline_unsafe_access( is_store, T_DOUBLE, Opaque, false);
422
423 case vmIntrinsics::_getFlatValue: return inline_unsafe_flat_access(!is_store, Relaxed);
424 case vmIntrinsics::_putFlatValue: return inline_unsafe_flat_access( is_store, Relaxed);
425
426 case vmIntrinsics::_compareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap, Volatile);
427 case vmIntrinsics::_compareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap, Volatile);
428 case vmIntrinsics::_compareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap, Volatile);
429 case vmIntrinsics::_compareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap, Volatile);
430 case vmIntrinsics::_compareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap, Volatile);
431
432 case vmIntrinsics::_weakCompareAndSetReferencePlain: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
433 case vmIntrinsics::_weakCompareAndSetReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
434 case vmIntrinsics::_weakCompareAndSetReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
435 case vmIntrinsics::_weakCompareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
436 case vmIntrinsics::_weakCompareAndSetBytePlain: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Relaxed);
437 case vmIntrinsics::_weakCompareAndSetByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Acquire);
438 case vmIntrinsics::_weakCompareAndSetByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Release);
439 case vmIntrinsics::_weakCompareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Volatile);
440 case vmIntrinsics::_weakCompareAndSetShortPlain: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Relaxed);
441 case vmIntrinsics::_weakCompareAndSetShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Acquire);
442 case vmIntrinsics::_weakCompareAndSetShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Release);
443 case vmIntrinsics::_weakCompareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Volatile);
444 case vmIntrinsics::_weakCompareAndSetIntPlain: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Relaxed);
445 case vmIntrinsics::_weakCompareAndSetIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Acquire);
501 "notifyJvmtiEnd", false, true);
502 case vmIntrinsics::_notifyJvmtiVThreadMount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_mount()),
503 "notifyJvmtiMount", false, false);
504 case vmIntrinsics::_notifyJvmtiVThreadUnmount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_unmount()),
505 "notifyJvmtiUnmount", false, false);
506 case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
507 #endif
508
509 #ifdef JFR_HAVE_INTRINSICS
510 case vmIntrinsics::_counterTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
511 case vmIntrinsics::_getEventWriter: return inline_native_getEventWriter();
512 case vmIntrinsics::_jvm_commit: return inline_native_jvm_commit();
513 #endif
514 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
515 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
516 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
517 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
518 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
519 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
520 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
521 case vmIntrinsics::_isFlatArray: return inline_unsafe_isFlatArray();
522 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
523 case vmIntrinsics::_getLength: return inline_native_getLength();
524 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
525 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
526 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
527 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
528 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
529 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
530 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
531
532 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
533 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
534 case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
535 case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
536 case vmIntrinsics::_newNullableAtomicArray: return inline_newArray(/* null_free */ false, /* atomic */ true);
537
538 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
539
540 case vmIntrinsics::_isInstance:
541 case vmIntrinsics::_isHidden:
542 case vmIntrinsics::_getSuperclass:
543 case vmIntrinsics::_getClassAccessFlags: return inline_native_Class_query(intrinsic_id());
544
545 case vmIntrinsics::_floatToRawIntBits:
546 case vmIntrinsics::_floatToIntBits:
547 case vmIntrinsics::_intBitsToFloat:
548 case vmIntrinsics::_doubleToRawLongBits:
549 case vmIntrinsics::_doubleToLongBits:
550 case vmIntrinsics::_longBitsToDouble:
551 case vmIntrinsics::_floatToFloat16:
552 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
553 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
554 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
555 case vmIntrinsics::_floatIsFinite:
556 case vmIntrinsics::_floatIsInfinite:
2314 case vmIntrinsics::_remainderUnsigned_l: {
2315 zero_check_long(argument(2));
2316 // Compile-time detect of null-exception
2317 if (stopped()) {
2318 return true; // keep the graph constructed so far
2319 }
2320 n = new UModLNode(control(), argument(0), argument(2));
2321 break;
2322 }
2323 default: fatal_unexpected_iid(id); break;
2324 }
2325 set_result(_gvn.transform(n));
2326 return true;
2327 }
2328
2329 //----------------------------inline_unsafe_access----------------------------
2330
2331 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2332 // Attempt to infer a sharper value type from the offset and base type.
2333 ciKlass* sharpened_klass = nullptr;
2334 bool null_free = false;
2335
2336 // See if it is an instance field, with an object type.
2337 if (alias_type->field() != nullptr) {
2338 if (alias_type->field()->type()->is_klass()) {
2339 sharpened_klass = alias_type->field()->type()->as_klass();
2340 null_free = alias_type->field()->is_null_free();
2341 }
2342 }
2343
2344 const TypeOopPtr* result = nullptr;
2345 // See if it is a narrow oop array.
2346 if (adr_type->isa_aryptr()) {
2347 if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2348 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2349 null_free = adr_type->is_aryptr()->is_null_free();
2350 if (elem_type != nullptr && elem_type->is_loaded()) {
2351 // Sharpen the value type.
2352 result = elem_type;
2353 }
2354 }
2355 }
2356
2357 // The sharpened class might be unloaded if there is no class loader
2358 // contraint in place.
2359 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2360 // Sharpen the value type.
2361 result = TypeOopPtr::make_from_klass(sharpened_klass);
2362 if (null_free) {
2363 result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2364 }
2365 }
2366 if (result != nullptr) {
2367 #ifndef PRODUCT
2368 if (C->print_intrinsics() || C->print_inlining()) {
2369 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2370 tty->print(" sharpened value: "); result->dump(); tty->cr();
2371 }
2372 #endif
2373 }
2374 return result;
2375 }
2376
2377 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2378 switch (kind) {
2379 case Relaxed:
2380 return MO_UNORDERED;
2381 case Opaque:
2382 return MO_RELAXED;
2383 case Acquire:
2384 return MO_ACQUIRE;
2385 case Release:
2386 return MO_RELEASE;
2387 case Volatile:
2388 return MO_SEQ_CST;
2389 default:
2390 ShouldNotReachHere();
2391 return 0;
2392 }
2393 }
2394
2395 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned, const bool is_flat) {
2396 if (callee()->is_static()) return false; // caller must have the capability!
2397 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2398 guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2399 guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2400 assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2401
2402 if (is_reference_type(type)) {
2403 decorators |= ON_UNKNOWN_OOP_REF;
2404 }
2405
2406 if (unaligned) {
2407 decorators |= C2_UNALIGNED;
2408 }
2409
2410 #ifndef PRODUCT
2411 {
2412 ResourceMark rm;
2413 // Check the signatures.
2414 ciSignature* sig = callee()->signature();
2415 #ifdef ASSERT
2416 if (!is_store) {
2417 // Object getReference(Object base, int/long offset), etc.
2418 BasicType rtype = sig->return_type()->basic_type();
2419 assert(rtype == type, "getter must return the expected value");
2420 assert(sig->count() == 2 || (is_flat && sig->count() == 3), "oop getter has 2 or 3 arguments");
2421 assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2422 assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2423 } else {
2424 // void putReference(Object base, int/long offset, Object x), etc.
2425 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2426 assert(sig->count() == 3 || (is_flat && sig->count() == 4), "oop putter has 3 arguments");
2427 assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2428 assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2429 BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2430 assert(vtype == type, "putter must accept the expected value");
2431 }
2432 #endif // ASSERT
2433 }
2434 #endif //PRODUCT
2435
2436 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2437
2438 Node* receiver = argument(0); // type: oop
2439
2440 // Build address expression.
2441 Node* heap_base_oop = top();
2442
2443 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2444 Node* base = argument(1); // type: oop
2445 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2446 Node* offset = argument(2); // type: long
2447 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2448 // to be plain byte offsets, which are also the same as those accepted
2449 // by oopDesc::field_addr.
2450 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2451 "fieldOffset must be byte-scaled");
2452
2453 ciInlineKlass* inline_klass = nullptr;
2454 if (is_flat) {
2455 const TypeInstPtr* cls = _gvn.type(argument(4))->isa_instptr();
2456 if (cls == nullptr || cls->const_oop() == nullptr) {
2457 return false;
2458 }
2459 ciType* mirror_type = cls->const_oop()->as_instance()->java_mirror_type();
2460 if (!mirror_type->is_inlinetype()) {
2461 return false;
2462 }
2463 inline_klass = mirror_type->as_inline_klass();
2464 }
2465
2466 if (base->is_InlineType()) {
2467 assert(!is_store, "InlineTypeNodes are non-larval value objects");
2468 InlineTypeNode* vt = base->as_InlineType();
2469 if (offset->is_Con()) {
2470 long off = find_long_con(offset, 0);
2471 ciInlineKlass* vk = vt->type()->inline_klass();
2472 if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2473 return false;
2474 }
2475
2476 ciField* field = vk->get_non_flat_field_by_offset(off);
2477 if (field != nullptr) {
2478 BasicType bt = type2field[field->type()->basic_type()];
2479 if (bt == T_ARRAY || bt == T_NARROWOOP) {
2480 bt = T_OBJECT;
2481 }
2482 if (bt == type && (!field->is_flat() || field->type() == inline_klass)) {
2483 Node* value = vt->field_value_by_offset(off, false);
2484 if (value->is_InlineType()) {
2485 value = value->as_InlineType()->adjust_scalarization_depth(this);
2486 }
2487 set_result(value);
2488 return true;
2489 }
2490 }
2491 }
2492 {
2493 // Re-execute the unsafe access if allocation triggers deoptimization.
2494 PreserveReexecuteState preexecs(this);
2495 jvms()->set_should_reexecute(true);
2496 vt = vt->buffer(this);
2497 }
2498 base = vt->get_oop();
2499 }
2500
2501 // 32-bit machines ignore the high half!
2502 offset = ConvL2X(offset);
2503
2504 // Save state and restore on bailout
2505 uint old_sp = sp();
2506 SafePointNode* old_map = clone_map();
2507
2508 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2509 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2510
2511 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2512 if (type != T_OBJECT && (inline_klass == nullptr || !inline_klass->has_object_fields())) {
2513 decorators |= IN_NATIVE; // off-heap primitive access
2514 } else {
2515 set_map(old_map);
2516 set_sp(old_sp);
2517 return false; // off-heap oop accesses are not supported
2518 }
2519 } else {
2520 heap_base_oop = base; // on-heap or mixed access
2521 }
2522
2523 // Can base be null? Otherwise, always on-heap access.
2524 bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2525
2526 if (!can_access_non_heap) {
2527 decorators |= IN_HEAP;
2528 }
2529
2530 Node* val = is_store ? argument(4 + (is_flat ? 1 : 0)) : nullptr;
2531
2532 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2533 if (adr_type == TypePtr::NULL_PTR) {
2534 set_map(old_map);
2535 set_sp(old_sp);
2536 return false; // off-heap access with zero address
2537 }
2538
2539 // Try to categorize the address.
2540 Compile::AliasType* alias_type = C->alias_type(adr_type);
2541 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2542
2543 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2544 alias_type->adr_type() == TypeAryPtr::RANGE) {
2545 set_map(old_map);
2546 set_sp(old_sp);
2547 return false; // not supported
2548 }
2549
2550 bool mismatched = false;
2551 BasicType bt = T_ILLEGAL;
2552 ciField* field = nullptr;
2553 if (adr_type->isa_instptr()) {
2554 const TypeInstPtr* instptr = adr_type->is_instptr();
2555 ciInstanceKlass* k = instptr->instance_klass();
2556 int off = instptr->offset();
2557 if (instptr->const_oop() != nullptr &&
2558 k == ciEnv::current()->Class_klass() &&
2559 instptr->offset() >= (k->size_helper() * wordSize)) {
2560 k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2561 field = k->get_field_by_offset(off, true);
2562 } else {
2563 field = k->get_non_flat_field_by_offset(off);
2564 }
2565 if (field != nullptr) {
2566 bt = type2field[field->type()->basic_type()];
2567 }
2568 if (bt != alias_type->basic_type()) {
2569 // Type mismatch. Is it an access to a nested flat field?
2570 field = k->get_field_by_offset(off, false);
2571 if (field != nullptr) {
2572 bt = type2field[field->type()->basic_type()];
2573 }
2574 }
2575 assert(bt == alias_type->basic_type() || is_flat, "should match");
2576 } else {
2577 bt = alias_type->basic_type();
2578 }
2579
2580 if (bt != T_ILLEGAL) {
2581 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2582 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2583 // Alias type doesn't differentiate between byte[] and boolean[]).
2584 // Use address type to get the element type.
2585 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2586 }
2587 if (is_reference_type(bt, true)) {
2588 // accessing an array field with getReference is not a mismatch
2589 bt = T_OBJECT;
2590 }
2591 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2592 // Don't intrinsify mismatched object accesses
2593 set_map(old_map);
2594 set_sp(old_sp);
2595 return false;
2596 }
2597 mismatched = (bt != type);
2598 } else if (alias_type->adr_type()->isa_oopptr()) {
2599 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2600 }
2601
2602 if (is_flat) {
2603 if (adr_type->isa_instptr()) {
2604 if (field == nullptr || field->type() != inline_klass) {
2605 mismatched = true;
2606 }
2607 } else if (adr_type->isa_aryptr()) {
2608 const Type* elem = adr_type->is_aryptr()->elem();
2609 if (!adr_type->is_flat() || elem->inline_klass() != inline_klass) {
2610 mismatched = true;
2611 }
2612 } else {
2613 mismatched = true;
2614 }
2615 if (is_store) {
2616 const Type* val_t = _gvn.type(val);
2617 if (!val_t->is_inlinetypeptr() || val_t->inline_klass() != inline_klass) {
2618 set_map(old_map);
2619 set_sp(old_sp);
2620 return false;
2621 }
2622 }
2623 }
2624
2625 destruct_map_clone(old_map);
2626 assert(!mismatched || is_flat || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2627
2628 if (mismatched) {
2629 decorators |= C2_MISMATCHED;
2630 }
2631
2632 // First guess at the value type.
2633 const Type *value_type = Type::get_const_basic_type(type);
2634
2635 // Figure out the memory ordering.
2636 decorators |= mo_decorator_for_access_kind(kind);
2637
2638 if (!is_store) {
2639 if (type == T_OBJECT && !is_flat) {
2640 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2641 if (tjp != nullptr) {
2642 value_type = tjp;
2643 }
2644 }
2645 }
2646
2647 receiver = null_check(receiver);
2648 if (stopped()) {
2649 return true;
2650 }
2651 // Heap pointers get a null-check from the interpreter,
2652 // as a courtesy. However, this is not guaranteed by Unsafe,
2653 // and it is not possible to fully distinguish unintended nulls
2654 // from intended ones in this API.
2655
2656 if (!is_store) {
2657 Node* p = nullptr;
2658 // Try to constant fold a load from a constant field
2659
2660 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2661 // final or stable field
2662 p = make_constant_from_field(field, heap_base_oop);
2663 }
2664
2665 if (p == nullptr) { // Could not constant fold the load
2666 if (is_flat) {
2667 p = InlineTypeNode::make_from_flat(this, inline_klass, base, adr, adr_type, false, false, true);
2668 } else {
2669 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2670 const TypeOopPtr* ptr = value_type->make_oopptr();
2671 if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2672 // Load a non-flattened inline type from memory
2673 p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2674 }
2675 }
2676 // Normalize the value returned by getBoolean in the following cases
2677 if (type == T_BOOLEAN &&
2678 (mismatched ||
2679 heap_base_oop == top() || // - heap_base_oop is null or
2680 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2681 // and the unsafe access is made to large offset
2682 // (i.e., larger than the maximum offset necessary for any
2683 // field access)
2684 ) {
2685 IdealKit ideal = IdealKit(this);
2686 #define __ ideal.
2687 IdealVariable normalized_result(ideal);
2688 __ declarations_done();
2689 __ set(normalized_result, p);
2690 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2691 __ set(normalized_result, ideal.ConI(1));
2692 ideal.end_if();
2693 final_sync(ideal);
2694 p = __ value(normalized_result);
2695 #undef __
2696 }
2697 }
2698 if (type == T_ADDRESS) {
2699 p = gvn().transform(new CastP2XNode(nullptr, p));
2700 p = ConvX2UL(p);
2701 }
2702 // The load node has the control of the preceding MemBarCPUOrder. All
2703 // following nodes will have the control of the MemBarCPUOrder inserted at
2704 // the end of this method. So, pushing the load onto the stack at a later
2705 // point is fine.
2706 set_result(p);
2707 } else {
2708 if (bt == T_ADDRESS) {
2709 // Repackage the long as a pointer.
2710 val = ConvL2X(val);
2711 val = gvn().transform(new CastX2PNode(val));
2712 }
2713 if (is_flat) {
2714 val->as_InlineType()->store_flat(this, base, adr, false, false, true, decorators);
2715 } else {
2716 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2717 }
2718 }
2719
2720 return true;
2721 }
2722
2723 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2724 #ifdef ASSERT
2725 {
2726 ResourceMark rm;
2727 // Check the signatures.
2728 ciSignature* sig = callee()->signature();
2729 assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2730 assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2731 assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2732 assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2733 if (is_store) {
2734 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2735 assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2736 assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2737 } else {
2738 assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2739 assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2740 }
2741 }
2742 #endif // ASSERT
2743
2744 assert(kind == Relaxed, "Only plain accesses for now");
2745 if (callee()->is_static()) {
2746 // caller must have the capability!
2747 return false;
2748 }
2749 C->set_has_unsafe_access(true);
2750
2751 const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2752 if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2753 // parameter valueType is not a constant
2754 return false;
2755 }
2756 ciInlineKlass* value_klass = value_klass_node->const_oop()->as_instance()->java_mirror_type()->as_inline_klass();
2757
2758 const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2759 if (layout_type == nullptr || !layout_type->is_con()) {
2760 // parameter layoutKind is not a constant
2761 return false;
2762 }
2763 assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2764 layout_type->get_con() <= static_cast<int>(LayoutKind::UNKNOWN),
2765 "invalid layoutKind %d", layout_type->get_con());
2766 LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2767 assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NON_ATOMIC_FLAT ||
2768 layout == LayoutKind::ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2769 "unexpected layoutKind %d", layout_type->get_con());
2770
2771 null_check(argument(0));
2772 if (stopped()) {
2773 return true;
2774 }
2775
2776 Node* base = must_be_not_null(argument(1), true);
2777 Node* offset = argument(2);
2778 const Type* base_type = _gvn.type(base);
2779
2780 Node* ptr;
2781 bool immutable_memory = false;
2782 DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2783 if (base_type->isa_instptr()) {
2784 const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2785 if (offset_type == nullptr || !offset_type->is_con()) {
2786 // Offset into a non-array should be a constant
2787 decorators |= C2_MISMATCHED;
2788 } else {
2789 int offset_con = checked_cast<int>(offset_type->get_con());
2790 ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2791 ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2792 if (field == nullptr) {
2793 assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2794 decorators |= C2_MISMATCHED;
2795 } else {
2796 assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2797 offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2798 immutable_memory = field->is_strict() && field->is_final();
2799
2800 if (base->is_InlineType()) {
2801 assert(!is_store, "Cannot store into a non-larval value object");
2802 set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2803 return true;
2804 }
2805 }
2806 }
2807
2808 if (base->is_InlineType()) {
2809 assert(!is_store, "Cannot store into a non-larval value object");
2810 base = base->as_InlineType()->buffer(this, true);
2811 }
2812 ptr = basic_plus_adr(base, ConvL2X(offset));
2813 } else if (base_type->isa_aryptr()) {
2814 decorators |= IS_ARRAY;
2815 if (layout == LayoutKind::REFERENCE) {
2816 if (!base_type->is_aryptr()->is_not_flat()) {
2817 const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2818 Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::StrongDependency));
2819 replace_in_map(base, new_base);
2820 base = new_base;
2821 }
2822 ptr = basic_plus_adr(base, ConvL2X(offset));
2823 } else {
2824 // Flat array must have an exact type
2825 bool is_null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2826 bool is_atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2827 Node* new_base = cast_to_flat_array(base, value_klass, is_null_free, !is_null_free, is_atomic);
2828 replace_in_map(base, new_base);
2829 base = new_base;
2830 ptr = basic_plus_adr(base, ConvL2X(offset));
2831 const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2832 if (ptr_type->field_offset().get() != 0) {
2833 ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::StrongDependency));
2834 }
2835 }
2836 } else {
2837 decorators |= C2_MISMATCHED;
2838 ptr = basic_plus_adr(base, ConvL2X(offset));
2839 }
2840
2841 if (is_store) {
2842 Node* value = argument(6);
2843 const Type* value_type = _gvn.type(value);
2844 if (!value_type->is_inlinetypeptr()) {
2845 value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2846 Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::StrongDependency));
2847 new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2848 replace_in_map(value, new_value);
2849 value = new_value;
2850 }
2851
2852 assert(value_type->inline_klass() == value_klass, "value is of type %s while valueType is %s", value_type->inline_klass()->name()->as_utf8(), value_klass->name()->as_utf8());
2853 if (layout == LayoutKind::REFERENCE) {
2854 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2855 access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2856 } else {
2857 bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2858 bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2859 value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2860 }
2861
2862 return true;
2863 } else {
2864 decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2865 InlineTypeNode* result;
2866 if (layout == LayoutKind::REFERENCE) {
2867 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2868 Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2869 result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2870 } else {
2871 bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2872 bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2873 result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2874 }
2875
2876 set_result(result);
2877 return true;
2878 }
2879 }
2880
2881 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2882 Node* receiver = argument(0);
2883 Node* value = argument(1);
2884
2885 const Type* type = gvn().type(value);
2886 if (!type->is_inlinetypeptr()) {
2887 C->record_method_not_compilable("value passed to Unsafe::makePrivateBuffer is not of a constant value type");
2888 return false;
2889 }
2890
2891 null_check(receiver);
2892 if (stopped()) {
2893 return true;
2894 }
2895
2896 value = null_check(value);
2897 if (stopped()) {
2898 return true;
2899 }
2900
2901 ciInlineKlass* vk = type->inline_klass();
2902 Node* klass = makecon(TypeKlassPtr::make(vk));
2903 Node* obj = new_instance(klass);
2904 AllocateNode::Ideal_allocation(obj)->_larval = true;
2905
2906 assert(value->is_InlineType(), "must be an InlineTypeNode");
2907 Node* payload_ptr = basic_plus_adr(obj, vk->payload_offset());
2908 value->as_InlineType()->store_flat(this, obj, payload_ptr, false, true, true, IN_HEAP | MO_UNORDERED);
2909
2910 set_result(obj);
2911 return true;
2912 }
2913
2914 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2915 Node* receiver = argument(0);
2916 Node* buffer = argument(1);
2917
2918 const Type* type = gvn().type(buffer);
2919 if (!type->is_inlinetypeptr()) {
2920 C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer is not of a constant value type");
2921 return false;
2922 }
2923
2924 AllocateNode* alloc = AllocateNode::Ideal_allocation(buffer);
2925 if (alloc == nullptr) {
2926 C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer must be allocated by Unsafe::makePrivateBuffer");
2927 return false;
2928 }
2929
2930 null_check(receiver);
2931 if (stopped()) {
2932 return true;
2933 }
2934
2935 // Unset the larval bit in the object header
2936 Node* old_header = make_load(control(), buffer, TypeX_X, TypeX_X->basic_type(), MemNode::unordered, LoadNode::Pinned);
2937 Node* new_header = gvn().transform(new AndXNode(old_header, MakeConX(~markWord::larval_bit_in_place)));
2938 access_store_at(buffer, buffer, type->is_ptr(), new_header, TypeX_X, TypeX_X->basic_type(), MO_UNORDERED | IN_HEAP);
2939
2940 // We must ensure that the buffer is properly published
2941 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
2942 assert(!type->maybe_null(), "result of an allocation should not be null");
2943 set_result(InlineTypeNode::make_from_oop(this, buffer, type->inline_klass()));
2944 return true;
2945 }
2946
2947 //----------------------------inline_unsafe_load_store----------------------------
2948 // This method serves a couple of different customers (depending on LoadStoreKind):
2949 //
2950 // LS_cmp_swap:
2951 //
2952 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2953 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2954 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2955 //
2956 // LS_cmp_swap_weak:
2957 //
2958 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2959 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2960 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2961 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2962 //
2963 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
3132 }
3133 case LS_cmp_swap:
3134 case LS_cmp_swap_weak:
3135 case LS_get_add:
3136 break;
3137 default:
3138 ShouldNotReachHere();
3139 }
3140
3141 // Null check receiver.
3142 receiver = null_check(receiver);
3143 if (stopped()) {
3144 return true;
3145 }
3146
3147 int alias_idx = C->get_alias_index(adr_type);
3148
3149 if (is_reference_type(type)) {
3150 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3151
3152 if (oldval != nullptr && oldval->is_InlineType()) {
3153 // Re-execute the unsafe access if allocation triggers deoptimization.
3154 PreserveReexecuteState preexecs(this);
3155 jvms()->set_should_reexecute(true);
3156 oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3157 }
3158 if (newval != nullptr && newval->is_InlineType()) {
3159 // Re-execute the unsafe access if allocation triggers deoptimization.
3160 PreserveReexecuteState preexecs(this);
3161 jvms()->set_should_reexecute(true);
3162 newval = newval->as_InlineType()->buffer(this)->get_oop();
3163 }
3164
3165 // Transformation of a value which could be null pointer (CastPP #null)
3166 // could be delayed during Parse (for example, in adjust_map_after_if()).
3167 // Execute transformation here to avoid barrier generation in such case.
3168 if (_gvn.type(newval) == TypePtr::NULL_PTR)
3169 newval = _gvn.makecon(TypePtr::NULL_PTR);
3170
3171 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3172 // Refine the value to a null constant, when it is known to be null
3173 oldval = _gvn.makecon(TypePtr::NULL_PTR);
3174 }
3175 }
3176
3177 Node* result = nullptr;
3178 switch (kind) {
3179 case LS_cmp_exchange: {
3180 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3181 oldval, newval, value_type, type, decorators);
3182 break;
3183 }
3184 case LS_cmp_swap_weak:
3331 Deoptimization::Action_make_not_entrant);
3332 }
3333 if (stopped()) {
3334 return true;
3335 }
3336 #endif //INCLUDE_JVMTI
3337
3338 Node* test = nullptr;
3339 if (LibraryCallKit::klass_needs_init_guard(kls)) {
3340 // Note: The argument might still be an illegal value like
3341 // Serializable.class or Object[].class. The runtime will handle it.
3342 // But we must make an explicit check for initialization.
3343 Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3344 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3345 // can generate code to load it as unsigned byte.
3346 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3347 Node* bits = intcon(InstanceKlass::fully_initialized);
3348 test = _gvn.transform(new SubINode(inst, bits));
3349 // The 'test' is non-zero if we need to take a slow path.
3350 }
3351 Node* obj = nullptr;
3352 const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3353 if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3354 obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3355 } else {
3356 obj = new_instance(kls, test);
3357 }
3358 set_result(obj);
3359 return true;
3360 }
3361
3362 //------------------------inline_native_time_funcs--------------
3363 // inline code for System.currentTimeMillis() and System.nanoTime()
3364 // these have the same type and signature
3365 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3366 const TypeFunc* tf = OptoRuntime::void_long_Type();
3367 const TypePtr* no_memory_effects = nullptr;
3368 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3369 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3370 #ifdef ASSERT
3371 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3372 assert(value_top == top(), "second value must be top");
3373 #endif
3374 set_result(value);
3375 return true;
3376 }
3377
4118 Node* thread = _gvn.transform(new ThreadLocalNode());
4119 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4120 Node* thread_obj_handle
4121 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4122 thread_obj_handle = _gvn.transform(thread_obj_handle);
4123 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4124 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4125
4126 // Change the _monitor_owner_id of the JavaThread
4127 Node* tid = load_field_from_object(arr, "tid", "J");
4128 Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4129 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4130
4131 JFR_ONLY(extend_setCurrentThread(thread, arr);)
4132 return true;
4133 }
4134
4135 const Type* LibraryCallKit::scopedValueCache_type() {
4136 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4137 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4138 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true);
4139
4140 // Because we create the scopedValue cache lazily we have to make the
4141 // type of the result BotPTR.
4142 bool xk = etype->klass_is_exact();
4143 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4144 return objects_type;
4145 }
4146
4147 Node* LibraryCallKit::scopedValueCache_helper() {
4148 Node* thread = _gvn.transform(new ThreadLocalNode());
4149 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4150 // We cannot use immutable_memory() because we might flip onto a
4151 // different carrier thread, at which point we'll need to use that
4152 // carrier thread's cache.
4153 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4154 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4155 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4156 }
4157
4158 //------------------------inline_native_scopedValueCache------------------
4159 bool LibraryCallKit::inline_native_scopedValueCache() {
4160 Node* cache_obj_handle = scopedValueCache_helper();
4161 const Type* objects_type = scopedValueCache_type();
4162 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4163
4247 store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4248
4249 // Result of top level CFG and Memory.
4250 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4251 record_for_igvn(result_rgn);
4252 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4253 record_for_igvn(result_mem);
4254
4255 result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4256 result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4257 result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4258 result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4259
4260 // Set output state.
4261 set_control(_gvn.transform(result_rgn));
4262 set_all_memory(_gvn.transform(result_mem));
4263
4264 return true;
4265 }
4266
4267 //-----------------------load_klass_from_mirror_common-------------------------
4268 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4269 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4270 // and branch to the given path on the region.
4271 // If never_see_null, take an uncommon trap on null, so we can optimistically
4272 // compile for the non-null case.
4273 // If the region is null, force never_see_null = true.
4274 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4275 bool never_see_null,
4276 RegionNode* region,
4277 int null_path,
4278 int offset) {
4279 if (region == nullptr) never_see_null = true;
4280 Node* p = basic_plus_adr(mirror, offset);
4281 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4282 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4283 Node* null_ctl = top();
4284 kls = null_check_oop(kls, &null_ctl, never_see_null);
4285 if (region != nullptr) {
4286 // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4290 }
4291 return kls;
4292 }
4293
4294 //--------------------(inline_native_Class_query helpers)---------------------
4295 // Use this for JVM_ACC_INTERFACE.
4296 // Fall through if (mods & mask) == bits, take the guard otherwise.
4297 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4298 ByteSize offset, const Type* type, BasicType bt) {
4299 // Branch around if the given klass has the given modifier bit set.
4300 // Like generate_guard, adds a new path onto the region.
4301 Node* modp = basic_plus_adr(kls, in_bytes(offset));
4302 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4303 Node* mask = intcon(modifier_mask);
4304 Node* bits = intcon(modifier_bits);
4305 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4306 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4307 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4308 return generate_fair_guard(bol, region);
4309 }
4310
4311 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4312 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4313 Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4314 }
4315
4316 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4317 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4318 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4319 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4320 }
4321
4322 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4323 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4324 }
4325
4326 //-------------------------inline_native_Class_query-------------------
4327 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4328 const Type* return_type = TypeInt::BOOL;
4329 Node* prim_return_value = top(); // what happens if it's a primitive class?
4330 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4449
4450 case vmIntrinsics::_getClassAccessFlags:
4451 p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
4452 query_value = make_load(nullptr, p, TypeInt::CHAR, T_CHAR, MemNode::unordered);
4453 break;
4454
4455 default:
4456 fatal_unexpected_iid(id);
4457 break;
4458 }
4459
4460 // Fall-through is the normal case of a query to a real class.
4461 phi->init_req(1, query_value);
4462 region->init_req(1, control());
4463
4464 C->set_has_split_ifs(true); // Has chance for split-if optimization
4465 set_result(region, phi);
4466 return true;
4467 }
4468
4469
4470 //-------------------------inline_Class_cast-------------------
4471 bool LibraryCallKit::inline_Class_cast() {
4472 Node* mirror = argument(0); // Class
4473 Node* obj = argument(1);
4474 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4475 if (mirror_con == nullptr) {
4476 return false; // dead path (mirror->is_top()).
4477 }
4478 if (obj == nullptr || obj->is_top()) {
4479 return false; // dead path
4480 }
4481 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4482
4483 // First, see if Class.cast() can be folded statically.
4484 // java_mirror_type() returns non-null for compile-time Class constants.
4485 bool is_null_free_array = false;
4486 ciType* tm = mirror_con->java_mirror_type(&is_null_free_array);
4487 if (tm != nullptr && tm->is_klass() &&
4488 tp != nullptr) {
4489 if (!tp->is_loaded()) {
4490 // Don't use intrinsic when class is not loaded.
4491 return false;
4492 } else {
4493 const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4494 if (is_null_free_array) {
4495 tklass = tklass->is_aryklassptr()->cast_to_null_free();
4496 }
4497 int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4498 if (static_res == Compile::SSC_always_true) {
4499 // isInstance() is true - fold the code.
4500 set_result(obj);
4501 return true;
4502 } else if (static_res == Compile::SSC_always_false) {
4503 // Don't use intrinsic, have to throw ClassCastException.
4504 // If the reference is null, the non-intrinsic bytecode will
4505 // be optimized appropriately.
4506 return false;
4507 }
4508 }
4509 }
4510
4511 // Bailout intrinsic and do normal inlining if exception path is frequent.
4512 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4513 return false;
4514 }
4515
4516 // Generate dynamic checks.
4517 // Class.cast() is java implementation of _checkcast bytecode.
4518 // Do checkcast (Parse::do_checkcast()) optimizations here.
4519
4520 mirror = null_check(mirror);
4521 // If mirror is dead, only null-path is taken.
4522 if (stopped()) {
4523 return true;
4524 }
4525
4526 // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4527 enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4528 RegionNode* region = new RegionNode(PATH_LIMIT);
4529 record_for_igvn(region);
4530
4531 // Now load the mirror's klass metaobject, and null-check it.
4532 // If kls is null, we have a primitive mirror and
4533 // nothing is an instance of a primitive type.
4534 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4535
4536 Node* res = top();
4537 Node* io = i_o();
4538 Node* mem = merged_memory();
4539 if (!stopped()) {
4540
4541 Node* bad_type_ctrl = top();
4542 // Do checkcast optimizations.
4543 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4544 region->init_req(_bad_type_path, bad_type_ctrl);
4545 }
4546 if (region->in(_prim_path) != top() ||
4547 region->in(_bad_type_path) != top() ||
4548 region->in(_npe_path) != top()) {
4549 // Let Interpreter throw ClassCastException.
4550 PreserveJVMState pjvms(this);
4551 set_control(_gvn.transform(region));
4552 // Set IO and memory because gen_checkcast may override them when buffering inline types
4553 set_i_o(io);
4554 set_all_memory(mem);
4555 uncommon_trap(Deoptimization::Reason_intrinsic,
4556 Deoptimization::Action_maybe_recompile);
4557 }
4558 if (!stopped()) {
4559 set_result(res);
4560 }
4561 return true;
4562 }
4563
4564
4565 //--------------------------inline_native_subtype_check------------------------
4566 // This intrinsic takes the JNI calls out of the heart of
4567 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4568 bool LibraryCallKit::inline_native_subtype_check() {
4569 // Pull both arguments off the stack.
4570 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4571 args[0] = argument(0);
4572 args[1] = argument(1);
4573 Node* klasses[2]; // corresponding Klasses: superk, subk
4574 klasses[0] = klasses[1] = top();
4575
4576 enum {
4577 // A full decision tree on {superc is prim, subc is prim}:
4578 _prim_0_path = 1, // {P,N} => false
4579 // {P,P} & superc!=subc => false
4580 _prim_same_path, // {P,P} & superc==subc => true
4581 _prim_1_path, // {N,P} => false
4582 _ref_subtype_path, // {N,N} & subtype check wins => true
4583 _both_ref_path, // {N,N} & subtype check loses => false
4584 PATH_LIMIT
4585 };
4586
4587 RegionNode* region = new RegionNode(PATH_LIMIT);
4588 RegionNode* prim_region = new RegionNode(2);
4589 Node* phi = new PhiNode(region, TypeInt::BOOL);
4590 record_for_igvn(region);
4591 record_for_igvn(prim_region);
4592
4593 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4594 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4595 int class_klass_offset = java_lang_Class::klass_offset();
4596
4597 // First null-check both mirrors and load each mirror's klass metaobject.
4598 int which_arg;
4599 for (which_arg = 0; which_arg <= 1; which_arg++) {
4600 Node* arg = args[which_arg];
4601 arg = null_check(arg);
4602 if (stopped()) break;
4603 args[which_arg] = arg;
4604
4605 Node* p = basic_plus_adr(arg, class_klass_offset);
4606 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4607 klasses[which_arg] = _gvn.transform(kls);
4608 }
4609
4610 // Having loaded both klasses, test each for null.
4611 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4612 for (which_arg = 0; which_arg <= 1; which_arg++) {
4613 Node* kls = klasses[which_arg];
4614 Node* null_ctl = top();
4615 kls = null_check_oop(kls, &null_ctl, never_see_null);
4616 if (which_arg == 0) {
4617 prim_region->init_req(1, null_ctl);
4618 } else {
4619 region->init_req(_prim_1_path, null_ctl);
4620 }
4621 if (stopped()) break;
4622 klasses[which_arg] = kls;
4623 }
4624
4625 if (!stopped()) {
4626 // now we have two reference types, in klasses[0..1]
4627 Node* subk = klasses[1]; // the argument to isAssignableFrom
4628 Node* superk = klasses[0]; // the receiver
4629 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4630 region->set_req(_ref_subtype_path, control());
4631 }
4632
4633 // If both operands are primitive (both klasses null), then
4634 // we must return true when they are identical primitives.
4635 // It is convenient to test this after the first null klass check.
4636 // This path is also used if superc is a value mirror.
4637 set_control(_gvn.transform(prim_region));
4638 if (!stopped()) {
4639 // Since superc is primitive, make a guard for the superc==subc case.
4640 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4641 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4642 generate_fair_guard(bol_eq, region);
4643 if (region->req() == PATH_LIMIT+1) {
4644 // A guard was added. If the added guard is taken, superc==subc.
4645 region->swap_edges(PATH_LIMIT, _prim_same_path);
4646 region->del_req(PATH_LIMIT);
4647 }
4648 region->set_req(_prim_0_path, control()); // Not equal after all.
4649 }
4650
4651 // these are the only paths that produce 'true':
4652 phi->set_req(_prim_same_path, intcon(1));
4653 phi->set_req(_ref_subtype_path, intcon(1));
4654
4655 // pull together the cases:
4656 assert(region->req() == PATH_LIMIT, "sane region");
4657 for (uint i = 1; i < region->req(); i++) {
4658 Node* ctl = region->in(i);
4659 if (ctl == nullptr || ctl == top()) {
4660 region->set_req(i, top());
4661 phi ->set_req(i, top());
4662 } else if (phi->in(i) == nullptr) {
4663 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4664 }
4665 }
4666
4667 set_control(_gvn.transform(region));
4668 set_result(_gvn.transform(phi));
4669 return true;
4670 }
4671
4672 //---------------------generate_array_guard_common------------------------
4673 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4674
4675 if (stopped()) {
4676 return nullptr;
4677 }
4678
4679 // Like generate_guard, adds a new path onto the region.
4680 jint layout_con = 0;
4681 Node* layout_val = get_layout_helper(kls, layout_con);
4682 if (layout_val == nullptr) {
4683 bool query = 0;
4684 switch(kind) {
4685 case ObjectArray: query = Klass::layout_helper_is_objArray(layout_con); break;
4686 case NonObjectArray: query = !Klass::layout_helper_is_objArray(layout_con); break;
4687 case TypeArray: query = Klass::layout_helper_is_typeArray(layout_con); break;
4688 case AnyArray: query = Klass::layout_helper_is_array(layout_con); break;
4689 case NonArray: query = !Klass::layout_helper_is_array(layout_con); break;
4690 default:
4691 ShouldNotReachHere();
4692 }
4693 if (!query) {
4694 return nullptr; // never a branch
4695 } else { // always a branch
4696 Node* always_branch = control();
4697 if (region != nullptr)
4698 region->add_req(always_branch);
4699 set_control(top());
4700 return always_branch;
4701 }
4702 }
4703 unsigned int value = 0;
4704 BoolTest::mask btest = BoolTest::illegal;
4705 switch(kind) {
4706 case ObjectArray:
4707 case NonObjectArray: {
4708 value = Klass::_lh_array_tag_obj_value;
4709 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4710 btest = (kind == ObjectArray) ? BoolTest::eq : BoolTest::ne;
4711 break;
4712 }
4713 case TypeArray: {
4714 value = Klass::_lh_array_tag_type_value;
4715 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4716 btest = BoolTest::eq;
4717 break;
4718 }
4719 case AnyArray: value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4720 case NonArray: value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4721 default:
4722 ShouldNotReachHere();
4723 }
4724 // Now test the correct condition.
4725 jint nval = (jint)value;
4726 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4727 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4728 Node* ctrl = generate_fair_guard(bol, region);
4729 Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4730 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4731 // Keep track of the fact that 'obj' is an array to prevent
4732 // array specific accesses from floating above the guard.
4733 *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4734 }
4735 return ctrl;
4736 }
4737
4738 // public static native Object[] newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4739 // public static native Object[] newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4740 // public static native Object[] newNullableAtomicArray(Class<?> componentType, int length);
4741 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4742 assert(null_free || atomic, "nullable implies atomic");
4743 Node* componentType = argument(0);
4744 Node* length = argument(1);
4745 Node* init_val = null_free ? argument(2) : nullptr;
4746
4747 const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4748 if (tp != nullptr) {
4749 ciInstanceKlass* ik = tp->instance_klass();
4750 if (ik == C->env()->Class_klass()) {
4751 ciType* t = tp->java_mirror_type();
4752 if (t != nullptr && t->is_inlinetype()) {
4753 ciInlineKlass* vk = t->as_inline_klass();
4754 bool flat = vk->maybe_flat_in_array();
4755 if (flat && atomic) {
4756 // Only flat if we have a corresponding atomic layout
4757 flat = null_free ? vk->has_atomic_layout() : vk->has_nullable_atomic_layout();
4758 }
4759 // TODO 8350865 refactor
4760 if (flat && !atomic) {
4761 flat = vk->has_non_atomic_layout();
4762 }
4763
4764 // TOOD 8350865 ZGC needs card marks on initializing oop stores
4765 if (UseZGC && null_free && !flat) {
4766 return false;
4767 }
4768
4769 ciArrayKlass* array_klass = ciArrayKlass::make(t, flat, null_free, atomic);
4770 if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4771 const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4772 if (null_free) {
4773 if (init_val->is_InlineType()) {
4774 if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4775 // Zeroing is enough because the init value is the all-zero value
4776 init_val = nullptr;
4777 } else {
4778 init_val = init_val->as_InlineType()->buffer(this);
4779 }
4780 }
4781 // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4782 }
4783 Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4784 const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4785 assert(arytype->is_null_free() == null_free, "inconsistency");
4786 assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4787 assert(arytype->is_flat() == flat, "inconsistency");
4788 assert(arytype->is_aryptr()->is_not_flat() == !flat, "inconsistency");
4789 set_result(obj);
4790 return true;
4791 }
4792 }
4793 }
4794 }
4795 return false;
4796 }
4797
4798 //-----------------------inline_native_newArray--------------------------
4799 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4800 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4801 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4802 Node* mirror;
4803 Node* count_val;
4804 if (uninitialized) {
4805 null_check_receiver();
4806 mirror = argument(1);
4807 count_val = argument(2);
4808 } else {
4809 mirror = argument(0);
4810 count_val = argument(1);
4811 }
4812
4813 mirror = null_check(mirror);
4814 // If mirror or obj is dead, only null-path is taken.
4815 if (stopped()) return true;
4816
4817 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4818 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4819 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4925 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4926 { PreserveReexecuteState preexecs(this);
4927 jvms()->set_should_reexecute(true);
4928
4929 array_type_mirror = null_check(array_type_mirror);
4930 original = null_check(original);
4931
4932 // Check if a null path was taken unconditionally.
4933 if (stopped()) return true;
4934
4935 Node* orig_length = load_array_length(original);
4936
4937 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4938 klass_node = null_check(klass_node);
4939
4940 RegionNode* bailout = new RegionNode(1);
4941 record_for_igvn(bailout);
4942
4943 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4944 // Bail out if that is so.
4945 // Inline type array may have object field that would require a
4946 // write barrier. Conservatively, go to slow path.
4947 // TODO 8251971: Optimize for the case when flat src/dst are later found
4948 // to not contain oops (i.e., move this check to the macro expansion phase).
4949 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4950 const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
4951 const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
4952 bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
4953 // Can src array be flat and contain oops?
4954 (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
4955 // Can dest array be flat and contain oops?
4956 tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
4957 Node* not_objArray = exclude_flat ? generate_non_objArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
4958 if (not_objArray != nullptr) {
4959 // Improve the klass node's type from the new optimistic assumption:
4960 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4961 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0));
4962 Node* cast = new CastPPNode(control(), klass_node, akls);
4963 klass_node = _gvn.transform(cast);
4964 }
4965
4966 // Bail out if either start or end is negative.
4967 generate_negative_guard(start, bailout, &start);
4968 generate_negative_guard(end, bailout, &end);
4969
4970 Node* length = end;
4971 if (_gvn.type(start) != TypeInt::ZERO) {
4972 length = _gvn.transform(new SubINode(end, start));
4973 }
4974
4975 // Bail out if length is negative (i.e., if start > end).
4976 // Without this the new_array would throw
4977 // NegativeArraySizeException but IllegalArgumentException is what
4978 // should be thrown
4979 generate_negative_guard(length, bailout, &length);
4980
4981 // Handle inline type arrays
4982 bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
4983 if (!stopped()) {
4984 // TODO JDK-8329224
4985 if (!orig_t->is_null_free()) {
4986 // Not statically known to be null free, add a check
4987 generate_fair_guard(null_free_array_test(original), bailout);
4988 }
4989 orig_t = _gvn.type(original)->isa_aryptr();
4990 if (orig_t != nullptr && orig_t->is_flat()) {
4991 // Src is flat, check that dest is flat as well
4992 if (exclude_flat) {
4993 // Dest can't be flat, bail out
4994 bailout->add_req(control());
4995 set_control(top());
4996 } else {
4997 generate_fair_guard(flat_array_test(klass_node, /* flat = */ false), bailout);
4998 }
4999 // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5000 } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5001 // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5002 ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5003 // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5004 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5005 generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5006 if (orig_t != nullptr) {
5007 orig_t = orig_t->cast_to_not_flat();
5008 original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5009 }
5010 }
5011 if (!can_validate) {
5012 // No validation. The subtype check emitted at macro expansion time will not go to the slow
5013 // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5014 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5015 generate_fair_guard(flat_array_test(klass_node), bailout);
5016 generate_fair_guard(null_free_array_test(original), bailout);
5017 }
5018 }
5019
5020 // Bail out if start is larger than the original length
5021 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5022 generate_negative_guard(orig_tail, bailout, &orig_tail);
5023
5024 if (bailout->req() > 1) {
5025 PreserveJVMState pjvms(this);
5026 set_control(_gvn.transform(bailout));
5027 uncommon_trap(Deoptimization::Reason_intrinsic,
5028 Deoptimization::Action_maybe_recompile);
5029 }
5030
5031 if (!stopped()) {
5032 // How many elements will we copy from the original?
5033 // The answer is MinI(orig_tail, length).
5034 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5035
5036 // Generate a direct call to the right arraycopy function(s).
5037 // We know the copy is disjoint but we might not know if the
5038 // oop stores need checking.
5039 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
5045 // to the copyOf to be validated, including that the copy to the
5046 // new array won't trigger an ArrayStoreException. That subtype
5047 // check can be optimized if we know something on the type of
5048 // the input array from type speculation.
5049 if (_gvn.type(klass_node)->singleton()) {
5050 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5051 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5052
5053 int test = C->static_subtype_check(superk, subk);
5054 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5055 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5056 if (t_original->speculative_type() != nullptr) {
5057 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5058 }
5059 }
5060 }
5061
5062 bool validated = false;
5063 // Reason_class_check rather than Reason_intrinsic because we
5064 // want to intrinsify even if this traps.
5065 if (can_validate) {
5066 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5067
5068 if (not_subtype_ctrl != top()) {
5069 PreserveJVMState pjvms(this);
5070 set_control(not_subtype_ctrl);
5071 uncommon_trap(Deoptimization::Reason_class_check,
5072 Deoptimization::Action_make_not_entrant);
5073 assert(stopped(), "Should be stopped");
5074 }
5075 validated = true;
5076 }
5077
5078 if (!stopped()) {
5079 newcopy = new_array(klass_node, length, 0); // no arguments to push
5080
5081 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5082 load_object_klass(original), klass_node);
5083 if (!is_copyOfRange) {
5084 ac->set_copyof(validated);
5085 } else {
5131
5132 //-----------------------generate_method_call----------------------------
5133 // Use generate_method_call to make a slow-call to the real
5134 // method if the fast path fails. An alternative would be to
5135 // use a stub like OptoRuntime::slow_arraycopy_Java.
5136 // This only works for expanding the current library call,
5137 // not another intrinsic. (E.g., don't use this for making an
5138 // arraycopy call inside of the copyOf intrinsic.)
5139 CallJavaNode*
5140 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5141 // When compiling the intrinsic method itself, do not use this technique.
5142 guarantee(callee() != C->method(), "cannot make slow-call to self");
5143
5144 ciMethod* method = callee();
5145 // ensure the JVMS we have will be correct for this call
5146 guarantee(method_id == method->intrinsic_id(), "must match");
5147
5148 const TypeFunc* tf = TypeFunc::make(method);
5149 if (res_not_null) {
5150 assert(tf->return_type() == T_OBJECT, "");
5151 const TypeTuple* range = tf->range_cc();
5152 const Type** fields = TypeTuple::fields(range->cnt());
5153 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5154 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5155 tf = TypeFunc::make(tf->domain_cc(), new_range);
5156 }
5157 CallJavaNode* slow_call;
5158 if (is_static) {
5159 assert(!is_virtual, "");
5160 slow_call = new CallStaticJavaNode(C, tf,
5161 SharedRuntime::get_resolve_static_call_stub(), method);
5162 } else if (is_virtual) {
5163 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5164 int vtable_index = Method::invalid_vtable_index;
5165 if (UseInlineCaches) {
5166 // Suppress the vtable call
5167 } else {
5168 // hashCode and clone are not a miranda methods,
5169 // so the vtable index is fixed.
5170 // No need to use the linkResolver to get it.
5171 vtable_index = method->vtable_index();
5172 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5173 "bad index %d", vtable_index);
5174 }
5175 slow_call = new CallDynamicJavaNode(tf,
5192 set_edges_for_java_call(slow_call);
5193 return slow_call;
5194 }
5195
5196
5197 /**
5198 * Build special case code for calls to hashCode on an object. This call may
5199 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5200 * slightly different code.
5201 */
5202 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5203 assert(is_static == callee()->is_static(), "correct intrinsic selection");
5204 assert(!(is_virtual && is_static), "either virtual, special, or static");
5205
5206 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5207
5208 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5209 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
5210 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
5211 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5212 Node* obj = argument(0);
5213
5214 // Don't intrinsify hashcode on inline types for now.
5215 // The "is locked" runtime check below also serves as inline type check and goes to the slow path.
5216 if (gvn().type(obj)->is_inlinetypeptr()) {
5217 return false;
5218 }
5219
5220 if (!is_static) {
5221 // Check for hashing null object
5222 obj = null_check_receiver();
5223 if (stopped()) return true; // unconditionally null
5224 result_reg->init_req(_null_path, top());
5225 result_val->init_req(_null_path, top());
5226 } else {
5227 // Do a null check, and return zero if null.
5228 // System.identityHashCode(null) == 0
5229 Node* null_ctl = top();
5230 obj = null_check_oop(obj, &null_ctl);
5231 result_reg->init_req(_null_path, null_ctl);
5232 result_val->init_req(_null_path, _gvn.intcon(0));
5233 }
5234
5235 // Unconditionally null? Then return right away.
5236 if (stopped()) {
5237 set_control( result_reg->in(_null_path));
5238 if (!stopped())
5239 set_result(result_val->in(_null_path));
5240 return true;
5241 }
5242
5243 // We only go to the fast case code if we pass a number of guards. The
5244 // paths which do not pass are accumulated in the slow_region.
5245 RegionNode* slow_region = new RegionNode(1);
5246 record_for_igvn(slow_region);
5247
5248 // If this is a virtual call, we generate a funny guard. We pull out
5249 // the vtable entry corresponding to hashCode() from the target object.
5250 // If the target method which we are calling happens to be the native
5251 // Object hashCode() method, we pass the guard. We do not need this
5252 // guard for non-virtual calls -- the caller is known to be the native
5253 // Object hashCode().
5254 if (is_virtual) {
5255 // After null check, get the object's klass.
5256 Node* obj_klass = load_object_klass(obj);
5257 generate_virtual_guard(obj_klass, slow_region);
5258 }
5259
5260 // Get the header out of the object, use LoadMarkNode when available
5261 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5262 // The control of the load must be null. Otherwise, the load can move before
5263 // the null check after castPP removal.
5264 Node* no_ctrl = nullptr;
5265 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5266
5267 if (!UseObjectMonitorTable) {
5268 // Test the header to see if it is safe to read w.r.t. locking.
5269 // This also serves as guard against inline types
5270 Node *lock_mask = _gvn.MakeConX(markWord::inline_type_mask_in_place);
5271 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5272 if (LockingMode == LM_LIGHTWEIGHT) {
5273 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
5274 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5275 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5276
5277 generate_slow_guard(test_monitor, slow_region);
5278 } else {
5279 Node *unlocked_val = _gvn.MakeConX(markWord::unlocked_value);
5280 Node *chk_unlocked = _gvn.transform(new CmpXNode(lmasked_header, unlocked_val));
5281 Node *test_not_unlocked = _gvn.transform(new BoolNode(chk_unlocked, BoolTest::ne));
5282
5283 generate_slow_guard(test_not_unlocked, slow_region);
5284 }
5285 }
5286
5287 // Get the hash value and check to see that it has been properly assigned.
5288 // We depend on hash_mask being at most 32 bits and avoid the use of
5289 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5290 // vm: see markWord.hpp.
5325 // this->control() comes from set_results_for_java_call
5326 result_reg->init_req(_slow_path, control());
5327 result_val->init_req(_slow_path, slow_result);
5328 result_io ->set_req(_slow_path, i_o());
5329 result_mem ->set_req(_slow_path, reset_memory());
5330 }
5331
5332 // Return the combined state.
5333 set_i_o( _gvn.transform(result_io) );
5334 set_all_memory( _gvn.transform(result_mem));
5335
5336 set_result(result_reg, result_val);
5337 return true;
5338 }
5339
5340 //---------------------------inline_native_getClass----------------------------
5341 // public final native Class<?> java.lang.Object.getClass();
5342 //
5343 // Build special case code for calls to getClass on an object.
5344 bool LibraryCallKit::inline_native_getClass() {
5345 Node* obj = argument(0);
5346 if (obj->is_InlineType()) {
5347 const Type* t = _gvn.type(obj);
5348 if (t->maybe_null()) {
5349 null_check(obj);
5350 }
5351 set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5352 return true;
5353 }
5354 obj = null_check_receiver();
5355 if (stopped()) return true;
5356 set_result(load_mirror_from_klass(load_object_klass(obj)));
5357 return true;
5358 }
5359
5360 //-----------------inline_native_Reflection_getCallerClass---------------------
5361 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5362 //
5363 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5364 //
5365 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5366 // in that it must skip particular security frames and checks for
5367 // caller sensitive methods.
5368 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5369 #ifndef PRODUCT
5370 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5371 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5372 }
5373 #endif
5374
5686 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5687
5688 flags |= RC_NARROW_MEM; // narrow in memory
5689 }
5690
5691 // Call it. Note that the length argument is not scaled.
5692 make_runtime_call(flags,
5693 OptoRuntime::unsafe_setmemory_Type(),
5694 StubRoutines::unsafe_setmemory(),
5695 "unsafe_setmemory",
5696 dst_type,
5697 dst_addr, size XTOP, byte);
5698
5699 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5700
5701 return true;
5702 }
5703
5704 #undef XTOP
5705
5706 //----------------------inline_unsafe_isFlatArray------------------------
5707 // public native boolean Unsafe.isFlatArray(Class<?> arrayClass);
5708 // This intrinsic exploits assumptions made by the native implementation
5709 // (arrayClass is neither null nor primitive) to avoid unnecessary null checks.
5710 bool LibraryCallKit::inline_unsafe_isFlatArray() {
5711 Node* cls = argument(1);
5712 Node* p = basic_plus_adr(cls, java_lang_Class::klass_offset());
5713 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p,
5714 TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
5715 Node* result = flat_array_test(kls);
5716 set_result(result);
5717 return true;
5718 }
5719
5720 //------------------------clone_coping-----------------------------------
5721 // Helper function for inline_native_clone.
5722 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5723 assert(obj_size != nullptr, "");
5724 Node* raw_obj = alloc_obj->in(1);
5725 assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5726
5727 AllocateNode* alloc = nullptr;
5728 if (ReduceBulkZeroing &&
5729 // If we are implementing an array clone without knowing its source type
5730 // (can happen when compiling the array-guarded branch of a reflective
5731 // Object.clone() invocation), initialize the array within the allocation.
5732 // This is needed because some GCs (e.g. ZGC) might fall back in this case
5733 // to a runtime clone call that assumes fully initialized source arrays.
5734 (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5735 // We will be completely responsible for initializing this object -
5736 // mark Initialize node as complete.
5737 alloc = AllocateNode::Ideal_allocation(alloc_obj);
5738 // The object was just allocated - there should be no any stores!
5739 guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5770 // not cloneable or finalizer => slow path to out-of-line Object.clone
5771 //
5772 // The general case has two steps, allocation and copying.
5773 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5774 //
5775 // Copying also has two cases, oop arrays and everything else.
5776 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5777 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5778 //
5779 // These steps fold up nicely if and when the cloned object's klass
5780 // can be sharply typed as an object array, a type array, or an instance.
5781 //
5782 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5783 PhiNode* result_val;
5784
5785 // Set the reexecute bit for the interpreter to reexecute
5786 // the bytecode that invokes Object.clone if deoptimization happens.
5787 { PreserveReexecuteState preexecs(this);
5788 jvms()->set_should_reexecute(true);
5789
5790 Node* obj = argument(0);
5791 obj = null_check_receiver();
5792 if (stopped()) return true;
5793
5794 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5795 if (obj_type->is_inlinetypeptr()) {
5796 // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5797 // no identity.
5798 set_result(obj);
5799 return true;
5800 }
5801
5802 // If we are going to clone an instance, we need its exact type to
5803 // know the number and types of fields to convert the clone to
5804 // loads/stores. Maybe a speculative type can help us.
5805 if (!obj_type->klass_is_exact() &&
5806 obj_type->speculative_type() != nullptr &&
5807 obj_type->speculative_type()->is_instance_klass() &&
5808 !obj_type->speculative_type()->is_inlinetype()) {
5809 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5810 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5811 !spec_ik->has_injected_fields()) {
5812 if (!obj_type->isa_instptr() ||
5813 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5814 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5815 }
5816 }
5817 }
5818
5819 // Conservatively insert a memory barrier on all memory slices.
5820 // Do not let writes into the original float below the clone.
5821 insert_mem_bar(Op_MemBarCPUOrder);
5822
5823 // paths into result_reg:
5824 enum {
5825 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5826 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5827 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5828 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5829 PATH_LIMIT
5830 };
5831 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5832 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5833 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5834 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5835 record_for_igvn(result_reg);
5836
5837 // TODO 8350865 For arrays, this might be folded and then not account for atomic arrays
5838 Node* obj_klass = load_object_klass(obj);
5839 // We only go to the fast case code if we pass a number of guards.
5840 // The paths which do not pass are accumulated in the slow_region.
5841 RegionNode* slow_region = new RegionNode(1);
5842 record_for_igvn(slow_region);
5843
5844 Node* array_obj = obj;
5845 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5846 if (array_ctl != nullptr) {
5847 // It's an array.
5848 PreserveJVMState pjvms(this);
5849 set_control(array_ctl);
5850
5851 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5852 const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5853 if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5854 obj_type->can_be_inline_array() &&
5855 (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5856 // Flat inline type array may have object field that would require a
5857 // write barrier. Conservatively, go to slow path.
5858 generate_fair_guard(flat_array_test(obj_klass), slow_region);
5859 }
5860
5861 if (!stopped()) {
5862 Node* obj_length = load_array_length(array_obj);
5863 Node* array_size = nullptr; // Size of the array without object alignment padding.
5864 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5865
5866 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5867 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5868 // If it is an oop array, it requires very special treatment,
5869 // because gc barriers are required when accessing the array.
5870 Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5871 if (is_obja != nullptr) {
5872 PreserveJVMState pjvms2(this);
5873 set_control(is_obja);
5874 // Generate a direct call to the right arraycopy function(s).
5875 // Clones are always tightly coupled.
5876 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5877 ac->set_clone_oop_array();
5878 Node* n = _gvn.transform(ac);
5879 assert(n == ac, "cannot disappear");
5880 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5881
5882 result_reg->init_req(_objArray_path, control());
5883 result_val->init_req(_objArray_path, alloc_obj);
5884 result_i_o ->set_req(_objArray_path, i_o());
5885 result_mem ->set_req(_objArray_path, reset_memory());
5886 }
5887 }
5888 // Otherwise, there are no barriers to worry about.
5889 // (We can dispense with card marks if we know the allocation
5890 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5891 // causes the non-eden paths to take compensating steps to
5892 // simulate a fresh allocation, so that no further
5893 // card marks are required in compiled code to initialize
5894 // the object.)
5895
5896 if (!stopped()) {
5897 copy_to_clone(obj, alloc_obj, array_size, true);
5898
5899 // Present the results of the copy.
5900 result_reg->init_req(_array_path, control());
5901 result_val->init_req(_array_path, alloc_obj);
5902 result_i_o ->set_req(_array_path, i_o());
5903 result_mem ->set_req(_array_path, reset_memory());
5904 }
5905 }
5906 }
5907
5908 if (!stopped()) {
5909 // It's an instance (we did array above). Make the slow-path tests.
5910 // If this is a virtual call, we generate a funny guard. We grab
5911 // the vtable entry corresponding to clone() from the target object.
5912 // If the target method which we are calling happens to be the
5913 // Object clone() method, we pass the guard. We do not need this
5914 // guard for non-virtual calls; the caller is known to be the native
5915 // Object clone().
5916 if (is_virtual) {
5917 generate_virtual_guard(obj_klass, slow_region);
5918 }
5919
5920 // The object must be easily cloneable and must not have a finalizer.
5921 // Both of these conditions may be checked in a single test.
5922 // We could optimize the test further, but we don't care.
5923 generate_misc_flags_guard(obj_klass,
5924 // Test both conditions:
5925 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5926 // Must be cloneable but not finalizer:
5927 KlassFlags::_misc_is_cloneable_fast,
6019 set_jvms(sfpt->jvms());
6020 _reexecute_sp = jvms()->sp();
6021
6022 return saved_jvms;
6023 }
6024 }
6025 }
6026 return nullptr;
6027 }
6028
6029 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6030 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6031 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6032 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6033 uint size = alloc->req();
6034 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6035 old_jvms->set_map(sfpt);
6036 for (uint i = 0; i < size; i++) {
6037 sfpt->init_req(i, alloc->in(i));
6038 }
6039 int adjustment = 1;
6040 const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6041 if (ary_klass_ptr->is_null_free()) {
6042 // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6043 // also requires the componentType and initVal on stack for re-execution.
6044 // Re-create and push the componentType.
6045 ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6046 ciInstance* instance = klass->component_mirror_instance();
6047 const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6048 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6049 adjustment++;
6050 }
6051 // re-push array length for deoptimization
6052 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6053 if (ary_klass_ptr->is_null_free()) {
6054 // Re-create and push the initVal.
6055 Node* init_val = alloc->in(AllocateNode::InitValue);
6056 if (init_val == nullptr) {
6057 init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6058 } else if (UseCompressedOops) {
6059 init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6060 }
6061 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6062 adjustment++;
6063 }
6064 old_jvms->set_sp(old_jvms->sp() + adjustment);
6065 old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6066 old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6067 old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6068 old_jvms->set_should_reexecute(true);
6069
6070 sfpt->set_i_o(map()->i_o());
6071 sfpt->set_memory(map()->memory());
6072 sfpt->set_control(map()->control());
6073 return sfpt;
6074 }
6075
6076 // In case of a deoptimization, we restart execution at the
6077 // allocation, allocating a new array. We would leave an uninitialized
6078 // array in the heap that GCs wouldn't expect. Move the allocation
6079 // after the traps so we don't allocate the array if we
6080 // deoptimize. This is possible because tightly_coupled_allocation()
6081 // guarantees there's no observer of the allocated array at this point
6082 // and the control flow is simple enough.
6083 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6084 int saved_reexecute_sp, uint new_idx) {
6085 if (saved_jvms_before_guards != nullptr && !stopped()) {
6086 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6087
6088 assert(alloc != nullptr, "only with a tightly coupled allocation");
6089 // restore JVM state to the state at the arraycopy
6090 saved_jvms_before_guards->map()->set_control(map()->control());
6091 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6092 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6093 // If we've improved the types of some nodes (null check) while
6094 // emitting the guards, propagate them to the current state
6095 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6096 set_jvms(saved_jvms_before_guards);
6097 _reexecute_sp = saved_reexecute_sp;
6098
6099 // Remove the allocation from above the guards
6100 CallProjections* callprojs = alloc->extract_projections(true);
6101 InitializeNode* init = alloc->initialization();
6102 Node* alloc_mem = alloc->in(TypeFunc::Memory);
6103 C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6104 C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
6105
6106 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6107 // the allocation (i.e. is only valid if the allocation succeeds):
6108 // 1) replace CastIINode with AllocateArrayNode's length here
6109 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6110 //
6111 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6112 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6113 Node* init_control = init->proj_out(TypeFunc::Control);
6114 Node* alloc_length = alloc->Ideal_length();
6115 #ifdef ASSERT
6116 Node* prev_cast = nullptr;
6117 #endif
6118 for (uint i = 0; i < init_control->outcnt(); i++) {
6119 Node* init_out = init_control->raw_out(i);
6120 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6121 #ifdef ASSERT
6122 if (prev_cast == nullptr) {
6123 prev_cast = init_out;
6125 if (prev_cast->cmp(*init_out) == false) {
6126 prev_cast->dump();
6127 init_out->dump();
6128 assert(false, "not equal CastIINode");
6129 }
6130 }
6131 #endif
6132 C->gvn_replace_by(init_out, alloc_length);
6133 }
6134 }
6135 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6136
6137 // move the allocation here (after the guards)
6138 _gvn.hash_delete(alloc);
6139 alloc->set_req(TypeFunc::Control, control());
6140 alloc->set_req(TypeFunc::I_O, i_o());
6141 Node *mem = reset_memory();
6142 set_all_memory(mem);
6143 alloc->set_req(TypeFunc::Memory, mem);
6144 set_control(init->proj_out_or_null(TypeFunc::Control));
6145 set_i_o(callprojs->fallthrough_ioproj);
6146
6147 // Update memory as done in GraphKit::set_output_for_allocation()
6148 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6149 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6150 if (ary_type->isa_aryptr() && length_type != nullptr) {
6151 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6152 }
6153 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6154 int elemidx = C->get_alias_index(telemref);
6155 set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
6156 set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
6157
6158 Node* allocx = _gvn.transform(alloc);
6159 assert(allocx == alloc, "where has the allocation gone?");
6160 assert(dest->is_CheckCastPP(), "not an allocation result?");
6161
6162 _gvn.hash_delete(dest);
6163 dest->set_req(0, control());
6164 Node* destx = _gvn.transform(dest);
6165 assert(destx == dest, "where has the allocation result gone?");
6463 top_src = src_type->isa_aryptr();
6464 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6465 src_spec = true;
6466 }
6467 if (!has_dest) {
6468 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6469 dest_type = _gvn.type(dest);
6470 top_dest = dest_type->isa_aryptr();
6471 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6472 dest_spec = true;
6473 }
6474 }
6475 }
6476
6477 if (has_src && has_dest && can_emit_guards) {
6478 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6479 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6480 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6481 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6482
6483 if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6484 // If both arrays are object arrays then having the exact types
6485 // for both will remove the need for a subtype check at runtime
6486 // before the call and may make it possible to pick a faster copy
6487 // routine (without a subtype check on every element)
6488 // Do we have the exact type of src?
6489 bool could_have_src = src_spec;
6490 // Do we have the exact type of dest?
6491 bool could_have_dest = dest_spec;
6492 ciKlass* src_k = nullptr;
6493 ciKlass* dest_k = nullptr;
6494 if (!src_spec) {
6495 src_k = src_type->speculative_type_not_null();
6496 if (src_k != nullptr && src_k->is_array_klass()) {
6497 could_have_src = true;
6498 }
6499 }
6500 if (!dest_spec) {
6501 dest_k = dest_type->speculative_type_not_null();
6502 if (dest_k != nullptr && dest_k->is_array_klass()) {
6503 could_have_dest = true;
6504 }
6505 }
6506 if (could_have_src && could_have_dest) {
6507 // If we can have both exact types, emit the missing guards
6508 if (could_have_src && !src_spec) {
6509 src = maybe_cast_profiled_obj(src, src_k, true);
6510 src_type = _gvn.type(src);
6511 top_src = src_type->isa_aryptr();
6512 }
6513 if (could_have_dest && !dest_spec) {
6514 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6515 dest_type = _gvn.type(dest);
6516 top_dest = dest_type->isa_aryptr();
6517 }
6518 }
6519 }
6520 }
6521
6522 ciMethod* trap_method = method();
6523 int trap_bci = bci();
6524 if (saved_jvms_before_guards != nullptr) {
6525 trap_method = alloc->jvms()->method();
6526 trap_bci = alloc->jvms()->bci();
6527 }
6528
6529 bool negative_length_guard_generated = false;
6530
6531 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6532 can_emit_guards && !src->is_top() && !dest->is_top()) {
6533 // validate arguments: enables transformation the ArrayCopyNode
6534 validated = true;
6535
6536 RegionNode* slow_region = new RegionNode(1);
6537 record_for_igvn(slow_region);
6538
6539 // (1) src and dest are arrays.
6540 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6541 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6542
6543 // (2) src and dest arrays must have elements of the same BasicType
6544 // done at macro expansion or at Ideal transformation time
6545
6546 // (4) src_offset must not be negative.
6547 generate_negative_guard(src_offset, slow_region);
6548
6549 // (5) dest_offset must not be negative.
6550 generate_negative_guard(dest_offset, slow_region);
6551
6552 // (7) src_offset + length must not exceed length of src.
6555 slow_region);
6556
6557 // (8) dest_offset + length must not exceed length of dest.
6558 generate_limit_guard(dest_offset, length,
6559 load_array_length(dest),
6560 slow_region);
6561
6562 // (6) length must not be negative.
6563 // This is also checked in generate_arraycopy() during macro expansion, but
6564 // we also have to check it here for the case where the ArrayCopyNode will
6565 // be eliminated by Escape Analysis.
6566 if (EliminateAllocations) {
6567 generate_negative_guard(length, slow_region);
6568 negative_length_guard_generated = true;
6569 }
6570
6571 // (9) each element of an oop array must be assignable
6572 Node* dest_klass = load_object_klass(dest);
6573 if (src != dest) {
6574 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6575 slow_region->add_req(not_subtype_ctrl);
6576 }
6577
6578 // TODO 8350865 Fix below logic. Also handle atomicity.
6579 generate_fair_guard(flat_array_test(src), slow_region);
6580 generate_fair_guard(flat_array_test(dest), slow_region);
6581
6582 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6583 const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6584 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6585 src_type = _gvn.type(src);
6586 top_src = src_type->isa_aryptr();
6587
6588 // Handle flat inline type arrays (null-free arrays are handled by the subtype check above)
6589 if (!stopped() && UseArrayFlattening) {
6590 // If dest is flat, src must be flat as well (guaranteed by src <: dest check). Handle flat src here.
6591 assert(top_dest == nullptr || !top_dest->is_flat() || top_src->is_flat(), "src array must be flat");
6592 if (top_src != nullptr && top_src->is_flat()) {
6593 // Src is flat, check that dest is flat as well
6594 if (top_dest != nullptr && !top_dest->is_flat()) {
6595 generate_fair_guard(flat_array_test(dest_klass, /* flat = */ false), slow_region);
6596 // Since dest is flat and src <: dest, dest must have the same type as src.
6597 top_dest = top_src->cast_to_exactness(false);
6598 assert(top_dest->is_flat(), "dest must be flat");
6599 dest = _gvn.transform(new CheckCastPPNode(control(), dest, top_dest));
6600 }
6601 } else if (top_src == nullptr || !top_src->is_not_flat()) {
6602 // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
6603 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
6604 assert(top_dest == nullptr || !top_dest->is_flat(), "dest array must not be flat");
6605 generate_fair_guard(flat_array_test(src), slow_region);
6606 if (top_src != nullptr) {
6607 top_src = top_src->cast_to_not_flat();
6608 src = _gvn.transform(new CheckCastPPNode(control(), src, top_src));
6609 }
6610 }
6611 }
6612
6613 {
6614 PreserveJVMState pjvms(this);
6615 set_control(_gvn.transform(slow_region));
6616 uncommon_trap(Deoptimization::Reason_intrinsic,
6617 Deoptimization::Action_make_not_entrant);
6618 assert(stopped(), "Should be stopped");
6619 }
6620 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6621 }
6622
6623 if (stopped()) {
6624 return true;
6625 }
6626
6627 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6628 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6629 // so the compiler has a chance to eliminate them: during macro expansion,
6630 // we have to set their control (CastPP nodes are eliminated).
6631 load_object_klass(src), load_object_klass(dest),
6632 load_array_length(src), load_array_length(dest));
6633
6634 ac->set_arraycopy(validated);
6635
6636 Node* n = _gvn.transform(ac);
6637 if (n == ac) {
6638 ac->connect_outputs(this);
6639 } else {
|