6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "asm/macroAssembler.hpp"
26 #include "ci/ciSymbols.hpp"
27 #include "ci/ciUtilities.inline.hpp"
28 #include "classfile/vmIntrinsics.hpp"
29 #include "compiler/compileBroker.hpp"
30 #include "compiler/compileLog.hpp"
31 #include "gc/shared/barrierSet.hpp"
32 #include "jfr/support/jfrIntrinsics.hpp"
33 #include "memory/resourceArea.hpp"
34 #include "oops/klass.inline.hpp"
35 #include "oops/objArrayKlass.hpp"
36 #include "opto/addnode.hpp"
37 #include "opto/arraycopynode.hpp"
38 #include "opto/c2compiler.hpp"
39 #include "opto/castnode.hpp"
40 #include "opto/cfgnode.hpp"
41 #include "opto/convertnode.hpp"
42 #include "opto/countbitsnode.hpp"
43 #include "opto/idealKit.hpp"
44 #include "opto/library_call.hpp"
45 #include "opto/mathexactnode.hpp"
46 #include "opto/mulnode.hpp"
47 #include "opto/narrowptrnode.hpp"
48 #include "opto/opaquenode.hpp"
49 #include "opto/parse.hpp"
50 #include "opto/rootnode.hpp"
51 #include "opto/runtime.hpp"
52 #include "opto/subnode.hpp"
53 #include "opto/vectornode.hpp"
54 #include "prims/jvmtiExport.hpp"
55 #include "prims/jvmtiThreadState.hpp"
56 #include "prims/unsafe.hpp"
57 #include "runtime/jniHandles.inline.hpp"
58 #include "runtime/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.
301 case vmIntrinsics::_indexOfIL: return inline_string_indexOfI(StrIntrinsicNode::LL);
302 case vmIntrinsics::_indexOfIU: return inline_string_indexOfI(StrIntrinsicNode::UU);
303 case vmIntrinsics::_indexOfIUL: return inline_string_indexOfI(StrIntrinsicNode::UL);
304 case vmIntrinsics::_indexOfU_char: return inline_string_indexOfChar(StrIntrinsicNode::U);
305 case vmIntrinsics::_indexOfL_char: return inline_string_indexOfChar(StrIntrinsicNode::L);
306
307 case vmIntrinsics::_equalsL: return inline_string_equals(StrIntrinsicNode::LL);
308
309 case vmIntrinsics::_vectorizedHashCode: return inline_vectorizedHashCode();
310
311 case vmIntrinsics::_toBytesStringU: return inline_string_toBytesU();
312 case vmIntrinsics::_getCharsStringU: return inline_string_getCharsU();
313 case vmIntrinsics::_getCharStringU: return inline_string_char_access(!is_store);
314 case vmIntrinsics::_putCharStringU: return inline_string_char_access( is_store);
315
316 case vmIntrinsics::_compressStringC:
317 case vmIntrinsics::_compressStringB: return inline_string_copy( is_compress);
318 case vmIntrinsics::_inflateStringC:
319 case vmIntrinsics::_inflateStringB: return inline_string_copy(!is_compress);
320
321 case vmIntrinsics::_getReference: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false);
322 case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_store, T_BOOLEAN, Relaxed, false);
323 case vmIntrinsics::_getByte: return inline_unsafe_access(!is_store, T_BYTE, Relaxed, false);
324 case vmIntrinsics::_getShort: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, false);
325 case vmIntrinsics::_getChar: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, false);
326 case vmIntrinsics::_getInt: return inline_unsafe_access(!is_store, T_INT, Relaxed, false);
327 case vmIntrinsics::_getLong: return inline_unsafe_access(!is_store, T_LONG, Relaxed, false);
328 case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_store, T_FLOAT, Relaxed, false);
329 case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_store, T_DOUBLE, Relaxed, false);
330
331 case vmIntrinsics::_putReference: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false);
332 case vmIntrinsics::_putBoolean: return inline_unsafe_access( is_store, T_BOOLEAN, Relaxed, false);
333 case vmIntrinsics::_putByte: return inline_unsafe_access( is_store, T_BYTE, Relaxed, false);
334 case vmIntrinsics::_putShort: return inline_unsafe_access( is_store, T_SHORT, Relaxed, false);
335 case vmIntrinsics::_putChar: return inline_unsafe_access( is_store, T_CHAR, Relaxed, false);
336 case vmIntrinsics::_putInt: return inline_unsafe_access( is_store, T_INT, Relaxed, false);
337 case vmIntrinsics::_putLong: return inline_unsafe_access( is_store, T_LONG, Relaxed, false);
338 case vmIntrinsics::_putFloat: return inline_unsafe_access( is_store, T_FLOAT, Relaxed, false);
339 case vmIntrinsics::_putDouble: return inline_unsafe_access( is_store, T_DOUBLE, Relaxed, false);
340
341 case vmIntrinsics::_getReferenceVolatile: return inline_unsafe_access(!is_store, T_OBJECT, Volatile, false);
342 case vmIntrinsics::_getBooleanVolatile: return inline_unsafe_access(!is_store, T_BOOLEAN, Volatile, false);
343 case vmIntrinsics::_getByteVolatile: return inline_unsafe_access(!is_store, T_BYTE, Volatile, false);
344 case vmIntrinsics::_getShortVolatile: return inline_unsafe_access(!is_store, T_SHORT, Volatile, false);
345 case vmIntrinsics::_getCharVolatile: return inline_unsafe_access(!is_store, T_CHAR, Volatile, false);
346 case vmIntrinsics::_getIntVolatile: return inline_unsafe_access(!is_store, T_INT, Volatile, false);
347 case vmIntrinsics::_getLongVolatile: return inline_unsafe_access(!is_store, T_LONG, Volatile, false);
348 case vmIntrinsics::_getFloatVolatile: return inline_unsafe_access(!is_store, T_FLOAT, Volatile, false);
349 case vmIntrinsics::_getDoubleVolatile: return inline_unsafe_access(!is_store, T_DOUBLE, Volatile, false);
350
351 case vmIntrinsics::_putReferenceVolatile: return inline_unsafe_access( is_store, T_OBJECT, Volatile, false);
352 case vmIntrinsics::_putBooleanVolatile: return inline_unsafe_access( is_store, T_BOOLEAN, Volatile, false);
353 case vmIntrinsics::_putByteVolatile: return inline_unsafe_access( is_store, T_BYTE, Volatile, false);
354 case vmIntrinsics::_putShortVolatile: return inline_unsafe_access( is_store, T_SHORT, Volatile, false);
355 case vmIntrinsics::_putCharVolatile: return inline_unsafe_access( is_store, T_CHAR, Volatile, false);
356 case vmIntrinsics::_putIntVolatile: return inline_unsafe_access( is_store, T_INT, Volatile, false);
357 case vmIntrinsics::_putLongVolatile: return inline_unsafe_access( is_store, T_LONG, Volatile, false);
358 case vmIntrinsics::_putFloatVolatile: return inline_unsafe_access( is_store, T_FLOAT, Volatile, false);
359 case vmIntrinsics::_putDoubleVolatile: return inline_unsafe_access( is_store, T_DOUBLE, Volatile, false);
391 case vmIntrinsics::_getReferenceOpaque: return inline_unsafe_access(!is_store, T_OBJECT, Opaque, false);
392 case vmIntrinsics::_getBooleanOpaque: return inline_unsafe_access(!is_store, T_BOOLEAN, Opaque, false);
393 case vmIntrinsics::_getByteOpaque: return inline_unsafe_access(!is_store, T_BYTE, Opaque, false);
394 case vmIntrinsics::_getShortOpaque: return inline_unsafe_access(!is_store, T_SHORT, Opaque, false);
395 case vmIntrinsics::_getCharOpaque: return inline_unsafe_access(!is_store, T_CHAR, Opaque, false);
396 case vmIntrinsics::_getIntOpaque: return inline_unsafe_access(!is_store, T_INT, Opaque, false);
397 case vmIntrinsics::_getLongOpaque: return inline_unsafe_access(!is_store, T_LONG, Opaque, false);
398 case vmIntrinsics::_getFloatOpaque: return inline_unsafe_access(!is_store, T_FLOAT, Opaque, false);
399 case vmIntrinsics::_getDoubleOpaque: return inline_unsafe_access(!is_store, T_DOUBLE, Opaque, false);
400
401 case vmIntrinsics::_putReferenceOpaque: return inline_unsafe_access( is_store, T_OBJECT, Opaque, false);
402 case vmIntrinsics::_putBooleanOpaque: return inline_unsafe_access( is_store, T_BOOLEAN, Opaque, false);
403 case vmIntrinsics::_putByteOpaque: return inline_unsafe_access( is_store, T_BYTE, Opaque, false);
404 case vmIntrinsics::_putShortOpaque: return inline_unsafe_access( is_store, T_SHORT, Opaque, false);
405 case vmIntrinsics::_putCharOpaque: return inline_unsafe_access( is_store, T_CHAR, Opaque, false);
406 case vmIntrinsics::_putIntOpaque: return inline_unsafe_access( is_store, T_INT, Opaque, false);
407 case vmIntrinsics::_putLongOpaque: return inline_unsafe_access( is_store, T_LONG, Opaque, false);
408 case vmIntrinsics::_putFloatOpaque: return inline_unsafe_access( is_store, T_FLOAT, Opaque, false);
409 case vmIntrinsics::_putDoubleOpaque: return inline_unsafe_access( is_store, T_DOUBLE, Opaque, false);
410
411 case vmIntrinsics::_compareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap, Volatile);
412 case vmIntrinsics::_compareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap, Volatile);
413 case vmIntrinsics::_compareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap, Volatile);
414 case vmIntrinsics::_compareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap, Volatile);
415 case vmIntrinsics::_compareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap, Volatile);
416
417 case vmIntrinsics::_weakCompareAndSetReferencePlain: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
418 case vmIntrinsics::_weakCompareAndSetReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
419 case vmIntrinsics::_weakCompareAndSetReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
420 case vmIntrinsics::_weakCompareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
421 case vmIntrinsics::_weakCompareAndSetBytePlain: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Relaxed);
422 case vmIntrinsics::_weakCompareAndSetByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Acquire);
423 case vmIntrinsics::_weakCompareAndSetByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Release);
424 case vmIntrinsics::_weakCompareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Volatile);
425 case vmIntrinsics::_weakCompareAndSetShortPlain: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Relaxed);
426 case vmIntrinsics::_weakCompareAndSetShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Acquire);
427 case vmIntrinsics::_weakCompareAndSetShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Release);
428 case vmIntrinsics::_weakCompareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Volatile);
429 case vmIntrinsics::_weakCompareAndSetIntPlain: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Relaxed);
430 case vmIntrinsics::_weakCompareAndSetIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Acquire);
498 #endif
499 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
500 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
501 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
502 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
503 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
504 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
505 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
506 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
507 case vmIntrinsics::_getLength: return inline_native_getLength();
508 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
509 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
510 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
511 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
512 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
513 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
514 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
515
516 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
517 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
518
519 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
520
521 case vmIntrinsics::_isInstance:
522 case vmIntrinsics::_isHidden:
523 case vmIntrinsics::_getSuperclass: return inline_native_Class_query(intrinsic_id());
524
525 case vmIntrinsics::_floatToRawIntBits:
526 case vmIntrinsics::_floatToIntBits:
527 case vmIntrinsics::_intBitsToFloat:
528 case vmIntrinsics::_doubleToRawLongBits:
529 case vmIntrinsics::_doubleToLongBits:
530 case vmIntrinsics::_longBitsToDouble:
531 case vmIntrinsics::_floatToFloat16:
532 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
533 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
534 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
535 case vmIntrinsics::_floatIsFinite:
536 case vmIntrinsics::_floatIsInfinite:
537 case vmIntrinsics::_doubleIsFinite:
2315 case vmIntrinsics::_remainderUnsigned_l: {
2316 zero_check_long(argument(2));
2317 // Compile-time detect of null-exception
2318 if (stopped()) {
2319 return true; // keep the graph constructed so far
2320 }
2321 n = new UModLNode(control(), argument(0), argument(2));
2322 break;
2323 }
2324 default: fatal_unexpected_iid(id); break;
2325 }
2326 set_result(_gvn.transform(n));
2327 return true;
2328 }
2329
2330 //----------------------------inline_unsafe_access----------------------------
2331
2332 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2333 // Attempt to infer a sharper value type from the offset and base type.
2334 ciKlass* sharpened_klass = nullptr;
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 }
2341 }
2342
2343 const TypeOopPtr* result = nullptr;
2344 // See if it is a narrow oop array.
2345 if (adr_type->isa_aryptr()) {
2346 if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2347 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2348 if (elem_type != nullptr && elem_type->is_loaded()) {
2349 // Sharpen the value type.
2350 result = elem_type;
2351 }
2352 }
2353 }
2354
2355 // The sharpened class might be unloaded if there is no class loader
2356 // contraint in place.
2357 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2358 // Sharpen the value type.
2359 result = TypeOopPtr::make_from_klass(sharpened_klass);
2360 }
2361 if (result != nullptr) {
2362 #ifndef PRODUCT
2363 if (C->print_intrinsics() || C->print_inlining()) {
2364 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2365 tty->print(" sharpened value: "); result->dump(); tty->cr();
2366 }
2367 #endif
2368 }
2369 return result;
2370 }
2371
2372 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2373 switch (kind) {
2374 case Relaxed:
2375 return MO_UNORDERED;
2376 case Opaque:
2377 return MO_RELAXED;
2378 case Acquire:
2379 return MO_ACQUIRE;
2411 _kit->jvms()->set_sp(_sp);
2412 _map->set_jvms(_kit->jvms());
2413 _kit->set_map(_map);
2414 _kit->set_sp(_sp);
2415 for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2416 Node* out = _kit->control()->fast_out(i);
2417 if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2418 _kit->_gvn.hash_delete(out);
2419 out->set_req(0, _kit->C->top());
2420 _kit->C->record_for_igvn(out);
2421 --i; --imax;
2422 _kit->_gvn.hash_find_insert(out);
2423 }
2424 }
2425 }
2426
2427 void LibraryCallKit::SavedState::discard() {
2428 _discarded = true;
2429 }
2430
2431 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2432 if (callee()->is_static()) return false; // caller must have the capability!
2433 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2434 guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2435 guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2436 assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2437
2438 if (is_reference_type(type)) {
2439 decorators |= ON_UNKNOWN_OOP_REF;
2440 }
2441
2442 if (unaligned) {
2443 decorators |= C2_UNALIGNED;
2444 }
2445
2446 #ifndef PRODUCT
2447 {
2448 ResourceMark rm;
2449 // Check the signatures.
2450 ciSignature* sig = callee()->signature();
2451 #ifdef ASSERT
2452 if (!is_store) {
2453 // Object getReference(Object base, int/long offset), etc.
2454 BasicType rtype = sig->return_type()->basic_type();
2455 assert(rtype == type, "getter must return the expected value");
2456 assert(sig->count() == 2, "oop getter has 2 arguments");
2457 assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2458 assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2459 } else {
2460 // void putReference(Object base, int/long offset, Object x), etc.
2461 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2462 assert(sig->count() == 3, "oop putter has 3 arguments");
2463 assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2464 assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2465 BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2466 assert(vtype == type, "putter must accept the expected value");
2467 }
2468 #endif // ASSERT
2469 }
2470 #endif //PRODUCT
2471
2472 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2473
2474 Node* receiver = argument(0); // type: oop
2475
2476 // Build address expression.
2477 Node* heap_base_oop = top();
2478
2479 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2480 Node* base = argument(1); // type: oop
2481 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2482 Node* offset = argument(2); // type: long
2483 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2484 // to be plain byte offsets, which are also the same as those accepted
2485 // by oopDesc::field_addr.
2486 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2487 "fieldOffset must be byte-scaled");
2488 // 32-bit machines ignore the high half!
2489 offset = ConvL2X(offset);
2490
2491 // Save state and restore on bailout
2492 SavedState old_state(this);
2493
2494 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2495 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2496
2497 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2498 if (type != T_OBJECT) {
2499 decorators |= IN_NATIVE; // off-heap primitive access
2500 } else {
2501 return false; // off-heap oop accesses are not supported
2502 }
2503 } else {
2504 heap_base_oop = base; // on-heap or mixed access
2505 }
2506
2507 // Can base be null? Otherwise, always on-heap access.
2508 bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2509
2510 if (!can_access_non_heap) {
2511 decorators |= IN_HEAP;
2512 }
2513
2514 Node* val = is_store ? argument(4) : nullptr;
2515
2516 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2517 if (adr_type == TypePtr::NULL_PTR) {
2518 return false; // off-heap access with zero address
2519 }
2520
2521 // Try to categorize the address.
2522 Compile::AliasType* alias_type = C->alias_type(adr_type);
2523 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2524
2525 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2526 alias_type->adr_type() == TypeAryPtr::RANGE) {
2527 return false; // not supported
2528 }
2529
2530 bool mismatched = false;
2531 BasicType bt = alias_type->basic_type();
2532 if (bt != T_ILLEGAL) {
2533 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2534 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2535 // Alias type doesn't differentiate between byte[] and boolean[]).
2536 // Use address type to get the element type.
2537 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2538 }
2539 if (is_reference_type(bt, true)) {
2540 // accessing an array field with getReference is not a mismatch
2541 bt = T_OBJECT;
2542 }
2543 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2544 // Don't intrinsify mismatched object accesses
2545 return false;
2546 }
2547 mismatched = (bt != type);
2548 } else if (alias_type->adr_type()->isa_oopptr()) {
2549 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2550 }
2551
2552 old_state.discard();
2553 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2554
2555 if (mismatched) {
2556 decorators |= C2_MISMATCHED;
2557 }
2558
2559 // First guess at the value type.
2560 const Type *value_type = Type::get_const_basic_type(type);
2561
2562 // Figure out the memory ordering.
2563 decorators |= mo_decorator_for_access_kind(kind);
2564
2565 if (!is_store && type == T_OBJECT) {
2566 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2567 if (tjp != nullptr) {
2568 value_type = tjp;
2569 }
2570 }
2571
2572 receiver = null_check(receiver);
2573 if (stopped()) {
2574 return true;
2575 }
2576 // Heap pointers get a null-check from the interpreter,
2577 // as a courtesy. However, this is not guaranteed by Unsafe,
2578 // and it is not possible to fully distinguish unintended nulls
2579 // from intended ones in this API.
2580
2581 if (!is_store) {
2582 Node* p = nullptr;
2583 // Try to constant fold a load from a constant field
2584 ciField* field = alias_type->field();
2585 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !mismatched) {
2586 // final or stable field
2587 p = make_constant_from_field(field, heap_base_oop);
2588 }
2589
2590 if (p == nullptr) { // Could not constant fold the load
2591 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2592 // Normalize the value returned by getBoolean in the following cases
2593 if (type == T_BOOLEAN &&
2594 (mismatched ||
2595 heap_base_oop == top() || // - heap_base_oop is null or
2596 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2597 // and the unsafe access is made to large offset
2598 // (i.e., larger than the maximum offset necessary for any
2599 // field access)
2600 ) {
2601 IdealKit ideal = IdealKit(this);
2602 #define __ ideal.
2603 IdealVariable normalized_result(ideal);
2604 __ declarations_done();
2605 __ set(normalized_result, p);
2606 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2607 __ set(normalized_result, ideal.ConI(1));
2608 ideal.end_if();
2609 final_sync(ideal);
2610 p = __ value(normalized_result);
2611 #undef __
2612 }
2613 }
2614 if (type == T_ADDRESS) {
2615 p = gvn().transform(new CastP2XNode(nullptr, p));
2616 p = ConvX2UL(p);
2617 }
2618 // The load node has the control of the preceding MemBarCPUOrder. All
2619 // following nodes will have the control of the MemBarCPUOrder inserted at
2620 // the end of this method. So, pushing the load onto the stack at a later
2621 // point is fine.
2622 set_result(p);
2623 } else {
2624 if (bt == T_ADDRESS) {
2625 // Repackage the long as a pointer.
2626 val = ConvL2X(val);
2627 val = gvn().transform(new CastX2PNode(val));
2628 }
2629 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2630 }
2631
2632 return true;
2633 }
2634
2635 //----------------------------inline_unsafe_load_store----------------------------
2636 // This method serves a couple of different customers (depending on LoadStoreKind):
2637 //
2638 // LS_cmp_swap:
2639 //
2640 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2641 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2642 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2643 //
2644 // LS_cmp_swap_weak:
2645 //
2646 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2647 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2648 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2649 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2650 //
2651 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2652 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2653 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2654 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
2817 }
2818 case LS_cmp_swap:
2819 case LS_cmp_swap_weak:
2820 case LS_get_add:
2821 break;
2822 default:
2823 ShouldNotReachHere();
2824 }
2825
2826 // Null check receiver.
2827 receiver = null_check(receiver);
2828 if (stopped()) {
2829 return true;
2830 }
2831
2832 int alias_idx = C->get_alias_index(adr_type);
2833
2834 if (is_reference_type(type)) {
2835 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2836
2837 // Transformation of a value which could be null pointer (CastPP #null)
2838 // could be delayed during Parse (for example, in adjust_map_after_if()).
2839 // Execute transformation here to avoid barrier generation in such case.
2840 if (_gvn.type(newval) == TypePtr::NULL_PTR)
2841 newval = _gvn.makecon(TypePtr::NULL_PTR);
2842
2843 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2844 // Refine the value to a null constant, when it is known to be null
2845 oldval = _gvn.makecon(TypePtr::NULL_PTR);
2846 }
2847 }
2848
2849 Node* result = nullptr;
2850 switch (kind) {
2851 case LS_cmp_exchange: {
2852 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2853 oldval, newval, value_type, type, decorators);
2854 break;
2855 }
2856 case LS_cmp_swap_weak:
3003 Deoptimization::Action_make_not_entrant);
3004 }
3005 if (stopped()) {
3006 return true;
3007 }
3008 #endif //INCLUDE_JVMTI
3009
3010 Node* test = nullptr;
3011 if (LibraryCallKit::klass_needs_init_guard(kls)) {
3012 // Note: The argument might still be an illegal value like
3013 // Serializable.class or Object[].class. The runtime will handle it.
3014 // But we must make an explicit check for initialization.
3015 Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3016 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3017 // can generate code to load it as unsigned byte.
3018 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3019 Node* bits = intcon(InstanceKlass::fully_initialized);
3020 test = _gvn.transform(new SubINode(inst, bits));
3021 // The 'test' is non-zero if we need to take a slow path.
3022 }
3023
3024 Node* obj = new_instance(kls, test);
3025 set_result(obj);
3026 return true;
3027 }
3028
3029 //------------------------inline_native_time_funcs--------------
3030 // inline code for System.currentTimeMillis() and System.nanoTime()
3031 // these have the same type and signature
3032 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3033 const TypeFunc* tf = OptoRuntime::void_long_Type();
3034 const TypePtr* no_memory_effects = nullptr;
3035 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3036 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3037 #ifdef ASSERT
3038 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3039 assert(value_top == top(), "second value must be top");
3040 #endif
3041 set_result(value);
3042 return true;
3043 }
3044
3785 Node* thread = _gvn.transform(new ThreadLocalNode());
3786 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
3787 Node* thread_obj_handle
3788 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3789 thread_obj_handle = _gvn.transform(thread_obj_handle);
3790 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3791 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3792
3793 // Change the _monitor_owner_id of the JavaThread
3794 Node* tid = load_field_from_object(arr, "tid", "J");
3795 Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3796 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3797
3798 JFR_ONLY(extend_setCurrentThread(thread, arr);)
3799 return true;
3800 }
3801
3802 const Type* LibraryCallKit::scopedValueCache_type() {
3803 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3804 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3805 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS);
3806
3807 // Because we create the scopedValue cache lazily we have to make the
3808 // type of the result BotPTR.
3809 bool xk = etype->klass_is_exact();
3810 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, 0);
3811 return objects_type;
3812 }
3813
3814 Node* LibraryCallKit::scopedValueCache_helper() {
3815 Node* thread = _gvn.transform(new ThreadLocalNode());
3816 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
3817 // We cannot use immutable_memory() because we might flip onto a
3818 // different carrier thread, at which point we'll need to use that
3819 // carrier thread's cache.
3820 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3821 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3822 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3823 }
3824
3825 //------------------------inline_native_scopedValueCache------------------
3826 bool LibraryCallKit::inline_native_scopedValueCache() {
3827 Node* cache_obj_handle = scopedValueCache_helper();
3828 const Type* objects_type = scopedValueCache_type();
3829 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3830
3914 store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
3915
3916 // Result of top level CFG and Memory.
3917 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3918 record_for_igvn(result_rgn);
3919 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3920 record_for_igvn(result_mem);
3921
3922 result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
3923 result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
3924 result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3925 result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
3926
3927 // Set output state.
3928 set_control(_gvn.transform(result_rgn));
3929 set_all_memory(_gvn.transform(result_mem));
3930
3931 return true;
3932 }
3933
3934 //---------------------------load_mirror_from_klass----------------------------
3935 // Given a klass oop, load its java mirror (a java.lang.Class oop).
3936 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
3937 Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
3938 Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3939 // mirror = ((OopHandle)mirror)->resolve();
3940 return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
3941 }
3942
3943 //-----------------------load_klass_from_mirror_common-------------------------
3944 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
3945 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
3946 // and branch to the given path on the region.
3947 // If never_see_null, take an uncommon trap on null, so we can optimistically
3948 // compile for the non-null case.
3949 // If the region is null, force never_see_null = true.
3950 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
3951 bool never_see_null,
3952 RegionNode* region,
3953 int null_path,
3954 int offset) {
3955 if (region == nullptr) never_see_null = true;
3956 Node* p = basic_plus_adr(mirror, offset);
3957 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
3958 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
3959 Node* null_ctl = top();
3960 kls = null_check_oop(kls, &null_ctl, never_see_null);
3961 if (region != nullptr) {
3962 // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
3966 }
3967 return kls;
3968 }
3969
3970 //--------------------(inline_native_Class_query helpers)---------------------
3971 // Use this for JVM_ACC_INTERFACE.
3972 // Fall through if (mods & mask) == bits, take the guard otherwise.
3973 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
3974 ByteSize offset, const Type* type, BasicType bt) {
3975 // Branch around if the given klass has the given modifier bit set.
3976 // Like generate_guard, adds a new path onto the region.
3977 Node* modp = basic_plus_adr(kls, in_bytes(offset));
3978 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
3979 Node* mask = intcon(modifier_mask);
3980 Node* bits = intcon(modifier_bits);
3981 Node* mbit = _gvn.transform(new AndINode(mods, mask));
3982 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
3983 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3984 return generate_fair_guard(bol, region);
3985 }
3986 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3987 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
3988 Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
3989 }
3990
3991 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
3992 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3993 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
3994 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
3995 }
3996
3997 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
3998 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
3999 }
4000
4001 //-------------------------inline_native_Class_query-------------------
4002 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4003 const Type* return_type = TypeInt::BOOL;
4004 Node* prim_return_value = top(); // what happens if it's a primitive class?
4005 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4115 }
4116 if (!stopped()) {
4117 query_value = load_mirror_from_klass(kls);
4118 }
4119 break;
4120
4121 default:
4122 fatal_unexpected_iid(id);
4123 break;
4124 }
4125
4126 // Fall-through is the normal case of a query to a real class.
4127 phi->init_req(1, query_value);
4128 region->init_req(1, control());
4129
4130 C->set_has_split_ifs(true); // Has chance for split-if optimization
4131 set_result(region, phi);
4132 return true;
4133 }
4134
4135 //-------------------------inline_Class_cast-------------------
4136 bool LibraryCallKit::inline_Class_cast() {
4137 Node* mirror = argument(0); // Class
4138 Node* obj = argument(1);
4139 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4140 if (mirror_con == nullptr) {
4141 return false; // dead path (mirror->is_top()).
4142 }
4143 if (obj == nullptr || obj->is_top()) {
4144 return false; // dead path
4145 }
4146 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4147
4148 // First, see if Class.cast() can be folded statically.
4149 // java_mirror_type() returns non-null for compile-time Class constants.
4150 ciType* tm = mirror_con->java_mirror_type();
4151 if (tm != nullptr && tm->is_klass() &&
4152 tp != nullptr) {
4153 if (!tp->is_loaded()) {
4154 // Don't use intrinsic when class is not loaded.
4155 return false;
4156 } else {
4157 int static_res = C->static_subtype_check(TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces), tp->as_klass_type());
4158 if (static_res == Compile::SSC_always_true) {
4159 // isInstance() is true - fold the code.
4160 set_result(obj);
4161 return true;
4162 } else if (static_res == Compile::SSC_always_false) {
4163 // Don't use intrinsic, have to throw ClassCastException.
4164 // If the reference is null, the non-intrinsic bytecode will
4165 // be optimized appropriately.
4166 return false;
4167 }
4168 }
4169 }
4170
4171 // Bailout intrinsic and do normal inlining if exception path is frequent.
4172 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4173 return false;
4174 }
4175
4176 // Generate dynamic checks.
4177 // Class.cast() is java implementation of _checkcast bytecode.
4178 // Do checkcast (Parse::do_checkcast()) optimizations here.
4179
4180 mirror = null_check(mirror);
4181 // If mirror is dead, only null-path is taken.
4182 if (stopped()) {
4183 return true;
4184 }
4185
4186 // Not-subtype or the mirror's klass ptr is null (in case it is a primitive).
4187 enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
4188 RegionNode* region = new RegionNode(PATH_LIMIT);
4189 record_for_igvn(region);
4190
4191 // Now load the mirror's klass metaobject, and null-check it.
4192 // If kls is null, we have a primitive mirror and
4193 // nothing is an instance of a primitive type.
4194 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4195
4196 Node* res = top();
4197 if (!stopped()) {
4198 Node* bad_type_ctrl = top();
4199 // Do checkcast optimizations.
4200 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4201 region->init_req(_bad_type_path, bad_type_ctrl);
4202 }
4203 if (region->in(_prim_path) != top() ||
4204 region->in(_bad_type_path) != top()) {
4205 // Let Interpreter throw ClassCastException.
4206 PreserveJVMState pjvms(this);
4207 set_control(_gvn.transform(region));
4208 uncommon_trap(Deoptimization::Reason_intrinsic,
4209 Deoptimization::Action_maybe_recompile);
4210 }
4211 if (!stopped()) {
4212 set_result(res);
4213 }
4214 return true;
4215 }
4216
4217
4218 //--------------------------inline_native_subtype_check------------------------
4219 // This intrinsic takes the JNI calls out of the heart of
4220 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4221 bool LibraryCallKit::inline_native_subtype_check() {
4222 // Pull both arguments off the stack.
4223 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4224 args[0] = argument(0);
4225 args[1] = argument(1);
4226 Node* klasses[2]; // corresponding Klasses: superk, subk
4227 klasses[0] = klasses[1] = top();
4228
4229 enum {
4230 // A full decision tree on {superc is prim, subc is prim}:
4231 _prim_0_path = 1, // {P,N} => false
4232 // {P,P} & superc!=subc => false
4233 _prim_same_path, // {P,P} & superc==subc => true
4234 _prim_1_path, // {N,P} => false
4235 _ref_subtype_path, // {N,N} & subtype check wins => true
4236 _both_ref_path, // {N,N} & subtype check loses => false
4237 PATH_LIMIT
4238 };
4239
4240 RegionNode* region = new RegionNode(PATH_LIMIT);
4241 Node* phi = new PhiNode(region, TypeInt::BOOL);
4242 record_for_igvn(region);
4243
4244 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4245 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4246 int class_klass_offset = java_lang_Class::klass_offset();
4247
4248 // First null-check both mirrors and load each mirror's klass metaobject.
4249 int which_arg;
4250 for (which_arg = 0; which_arg <= 1; which_arg++) {
4251 Node* arg = args[which_arg];
4252 arg = null_check(arg);
4253 if (stopped()) break;
4254 args[which_arg] = arg;
4255
4256 Node* p = basic_plus_adr(arg, class_klass_offset);
4257 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4258 klasses[which_arg] = _gvn.transform(kls);
4259 }
4260
4261 // Having loaded both klasses, test each for null.
4262 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4263 for (which_arg = 0; which_arg <= 1; which_arg++) {
4264 Node* kls = klasses[which_arg];
4265 Node* null_ctl = top();
4266 kls = null_check_oop(kls, &null_ctl, never_see_null);
4267 int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
4268 region->init_req(prim_path, null_ctl);
4269 if (stopped()) break;
4270 klasses[which_arg] = kls;
4271 }
4272
4273 if (!stopped()) {
4274 // now we have two reference types, in klasses[0..1]
4275 Node* subk = klasses[1]; // the argument to isAssignableFrom
4276 Node* superk = klasses[0]; // the receiver
4277 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4278 // now we have a successful reference subtype check
4279 region->set_req(_ref_subtype_path, control());
4280 }
4281
4282 // If both operands are primitive (both klasses null), then
4283 // we must return true when they are identical primitives.
4284 // It is convenient to test this after the first null klass check.
4285 set_control(region->in(_prim_0_path)); // go back to first null check
4286 if (!stopped()) {
4287 // Since superc is primitive, make a guard for the superc==subc case.
4288 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4289 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4290 generate_guard(bol_eq, region, PROB_FAIR);
4291 if (region->req() == PATH_LIMIT+1) {
4292 // A guard was added. If the added guard is taken, superc==subc.
4293 region->swap_edges(PATH_LIMIT, _prim_same_path);
4294 region->del_req(PATH_LIMIT);
4295 }
4296 region->set_req(_prim_0_path, control()); // Not equal after all.
4297 }
4298
4299 // these are the only paths that produce 'true':
4300 phi->set_req(_prim_same_path, intcon(1));
4301 phi->set_req(_ref_subtype_path, intcon(1));
4302
4303 // pull together the cases:
4304 assert(region->req() == PATH_LIMIT, "sane region");
4305 for (uint i = 1; i < region->req(); i++) {
4306 Node* ctl = region->in(i);
4307 if (ctl == nullptr || ctl == top()) {
4308 region->set_req(i, top());
4309 phi ->set_req(i, top());
4310 } else if (phi->in(i) == nullptr) {
4311 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4312 }
4313 }
4314
4315 set_control(_gvn.transform(region));
4316 set_result(_gvn.transform(phi));
4317 return true;
4318 }
4319
4320 //---------------------generate_array_guard_common------------------------
4321 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
4322 bool obj_array, bool not_array, Node** obj) {
4323
4324 if (stopped()) {
4325 return nullptr;
4326 }
4327
4328 // If obj_array/non_array==false/false:
4329 // Branch around if the given klass is in fact an array (either obj or prim).
4330 // If obj_array/non_array==false/true:
4331 // Branch around if the given klass is not an array klass of any kind.
4332 // If obj_array/non_array==true/true:
4333 // Branch around if the kls is not an oop array (kls is int[], String, etc.)
4334 // If obj_array/non_array==true/false:
4335 // Branch around if the kls is an oop array (Object[] or subtype)
4336 //
4337 // Like generate_guard, adds a new path onto the region.
4338 jint layout_con = 0;
4339 Node* layout_val = get_layout_helper(kls, layout_con);
4340 if (layout_val == nullptr) {
4341 bool query = (obj_array
4342 ? Klass::layout_helper_is_objArray(layout_con)
4343 : Klass::layout_helper_is_array(layout_con));
4344 if (query == not_array) {
4345 return nullptr; // never a branch
4346 } else { // always a branch
4347 Node* always_branch = control();
4348 if (region != nullptr)
4349 region->add_req(always_branch);
4350 set_control(top());
4351 return always_branch;
4352 }
4353 }
4354 // Now test the correct condition.
4355 jint nval = (obj_array
4356 ? (jint)(Klass::_lh_array_tag_type_value
4357 << Klass::_lh_array_tag_shift)
4358 : Klass::_lh_neutral_value);
4359 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4360 BoolTest::mask btest = BoolTest::lt; // correct for testing is_[obj]array
4361 // invert the test if we are looking for a non-array
4362 if (not_array) btest = BoolTest(btest).negate();
4363 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4364 Node* ctrl = generate_fair_guard(bol, region);
4365 Node* is_array_ctrl = not_array ? control() : ctrl;
4366 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4367 // Keep track of the fact that 'obj' is an array to prevent
4368 // array specific accesses from floating above the guard.
4369 *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4370 }
4371 return ctrl;
4372 }
4373
4374
4375 //-----------------------inline_native_newArray--------------------------
4376 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
4377 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4378 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4379 Node* mirror;
4380 Node* count_val;
4381 if (uninitialized) {
4382 null_check_receiver();
4383 mirror = argument(1);
4384 count_val = argument(2);
4385 } else {
4386 mirror = argument(0);
4387 count_val = argument(1);
4388 }
4389
4390 mirror = null_check(mirror);
4391 // If mirror or obj is dead, only null-path is taken.
4392 if (stopped()) return true;
4393
4394 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4395 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4396 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4414 CallJavaNode* slow_call = nullptr;
4415 if (uninitialized) {
4416 // Generate optimized virtual call (holder class 'Unsafe' is final)
4417 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4418 } else {
4419 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4420 }
4421 Node* slow_result = set_results_for_java_call(slow_call);
4422 // this->control() comes from set_results_for_java_call
4423 result_reg->set_req(_slow_path, control());
4424 result_val->set_req(_slow_path, slow_result);
4425 result_io ->set_req(_slow_path, i_o());
4426 result_mem->set_req(_slow_path, reset_memory());
4427 }
4428
4429 set_control(normal_ctl);
4430 if (!stopped()) {
4431 // Normal case: The array type has been cached in the java.lang.Class.
4432 // The following call works fine even if the array type is polymorphic.
4433 // It could be a dynamic mix of int[], boolean[], Object[], etc.
4434 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
4435 result_reg->init_req(_normal_path, control());
4436 result_val->init_req(_normal_path, obj);
4437 result_io ->init_req(_normal_path, i_o());
4438 result_mem->init_req(_normal_path, reset_memory());
4439
4440 if (uninitialized) {
4441 // Mark the allocation so that zeroing is skipped
4442 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4443 alloc->maybe_set_complete(&_gvn);
4444 }
4445 }
4446
4447 // Return the combined state.
4448 set_i_o( _gvn.transform(result_io) );
4449 set_all_memory( _gvn.transform(result_mem));
4450
4451 C->set_has_split_ifs(true); // Has chance for split-if optimization
4452 set_result(result_reg, result_val);
4453 return true;
4502 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4503 { PreserveReexecuteState preexecs(this);
4504 jvms()->set_should_reexecute(true);
4505
4506 array_type_mirror = null_check(array_type_mirror);
4507 original = null_check(original);
4508
4509 // Check if a null path was taken unconditionally.
4510 if (stopped()) return true;
4511
4512 Node* orig_length = load_array_length(original);
4513
4514 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4515 klass_node = null_check(klass_node);
4516
4517 RegionNode* bailout = new RegionNode(1);
4518 record_for_igvn(bailout);
4519
4520 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4521 // Bail out if that is so.
4522 Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
4523 if (not_objArray != nullptr) {
4524 // Improve the klass node's type from the new optimistic assumption:
4525 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4526 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
4527 Node* cast = new CastPPNode(control(), klass_node, akls);
4528 klass_node = _gvn.transform(cast);
4529 }
4530
4531 // Bail out if either start or end is negative.
4532 generate_negative_guard(start, bailout, &start);
4533 generate_negative_guard(end, bailout, &end);
4534
4535 Node* length = end;
4536 if (_gvn.type(start) != TypeInt::ZERO) {
4537 length = _gvn.transform(new SubINode(end, start));
4538 }
4539
4540 // Bail out if length is negative (i.e., if start > end).
4541 // Without this the new_array would throw
4542 // NegativeArraySizeException but IllegalArgumentException is what
4543 // should be thrown
4544 generate_negative_guard(length, bailout, &length);
4545
4546 // Bail out if start is larger than the original length
4547 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4548 generate_negative_guard(orig_tail, bailout, &orig_tail);
4549
4550 if (bailout->req() > 1) {
4551 PreserveJVMState pjvms(this);
4552 set_control(_gvn.transform(bailout));
4553 uncommon_trap(Deoptimization::Reason_intrinsic,
4554 Deoptimization::Action_maybe_recompile);
4555 }
4556
4557 if (!stopped()) {
4558 // How many elements will we copy from the original?
4559 // The answer is MinI(orig_tail, length).
4560 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4561
4562 // Generate a direct call to the right arraycopy function(s).
4563 // We know the copy is disjoint but we might not know if the
4564 // oop stores need checking.
4565 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
4571 // to the copyOf to be validated, including that the copy to the
4572 // new array won't trigger an ArrayStoreException. That subtype
4573 // check can be optimized if we know something on the type of
4574 // the input array from type speculation.
4575 if (_gvn.type(klass_node)->singleton()) {
4576 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
4577 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
4578
4579 int test = C->static_subtype_check(superk, subk);
4580 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4581 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4582 if (t_original->speculative_type() != nullptr) {
4583 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4584 }
4585 }
4586 }
4587
4588 bool validated = false;
4589 // Reason_class_check rather than Reason_intrinsic because we
4590 // want to intrinsify even if this traps.
4591 if (!too_many_traps(Deoptimization::Reason_class_check)) {
4592 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4593
4594 if (not_subtype_ctrl != top()) {
4595 PreserveJVMState pjvms(this);
4596 set_control(not_subtype_ctrl);
4597 uncommon_trap(Deoptimization::Reason_class_check,
4598 Deoptimization::Action_make_not_entrant);
4599 assert(stopped(), "Should be stopped");
4600 }
4601 validated = true;
4602 }
4603
4604 if (!stopped()) {
4605 newcopy = new_array(klass_node, length, 0); // no arguments to push
4606
4607 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4608 load_object_klass(original), klass_node);
4609 if (!is_copyOfRange) {
4610 ac->set_copyof(validated);
4611 } else {
4657
4658 //-----------------------generate_method_call----------------------------
4659 // Use generate_method_call to make a slow-call to the real
4660 // method if the fast path fails. An alternative would be to
4661 // use a stub like OptoRuntime::slow_arraycopy_Java.
4662 // This only works for expanding the current library call,
4663 // not another intrinsic. (E.g., don't use this for making an
4664 // arraycopy call inside of the copyOf intrinsic.)
4665 CallJavaNode*
4666 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4667 // When compiling the intrinsic method itself, do not use this technique.
4668 guarantee(callee() != C->method(), "cannot make slow-call to self");
4669
4670 ciMethod* method = callee();
4671 // ensure the JVMS we have will be correct for this call
4672 guarantee(method_id == method->intrinsic_id(), "must match");
4673
4674 const TypeFunc* tf = TypeFunc::make(method);
4675 if (res_not_null) {
4676 assert(tf->return_type() == T_OBJECT, "");
4677 const TypeTuple* range = tf->range();
4678 const Type** fields = TypeTuple::fields(range->cnt());
4679 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4680 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4681 tf = TypeFunc::make(tf->domain(), new_range);
4682 }
4683 CallJavaNode* slow_call;
4684 if (is_static) {
4685 assert(!is_virtual, "");
4686 slow_call = new CallStaticJavaNode(C, tf,
4687 SharedRuntime::get_resolve_static_call_stub(), method);
4688 } else if (is_virtual) {
4689 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4690 int vtable_index = Method::invalid_vtable_index;
4691 if (UseInlineCaches) {
4692 // Suppress the vtable call
4693 } else {
4694 // hashCode and clone are not a miranda methods,
4695 // so the vtable index is fixed.
4696 // No need to use the linkResolver to get it.
4697 vtable_index = method->vtable_index();
4698 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4699 "bad index %d", vtable_index);
4700 }
4701 slow_call = new CallDynamicJavaNode(tf,
4718 set_edges_for_java_call(slow_call);
4719 return slow_call;
4720 }
4721
4722
4723 /**
4724 * Build special case code for calls to hashCode on an object. This call may
4725 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4726 * slightly different code.
4727 */
4728 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4729 assert(is_static == callee()->is_static(), "correct intrinsic selection");
4730 assert(!(is_virtual && is_static), "either virtual, special, or static");
4731
4732 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4733
4734 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4735 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
4736 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
4737 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4738 Node* obj = nullptr;
4739 if (!is_static) {
4740 // Check for hashing null object
4741 obj = null_check_receiver();
4742 if (stopped()) return true; // unconditionally null
4743 result_reg->init_req(_null_path, top());
4744 result_val->init_req(_null_path, top());
4745 } else {
4746 // Do a null check, and return zero if null.
4747 // System.identityHashCode(null) == 0
4748 obj = argument(0);
4749 Node* null_ctl = top();
4750 obj = null_check_oop(obj, &null_ctl);
4751 result_reg->init_req(_null_path, null_ctl);
4752 result_val->init_req(_null_path, _gvn.intcon(0));
4753 }
4754
4755 // Unconditionally null? Then return right away.
4756 if (stopped()) {
4757 set_control( result_reg->in(_null_path));
4758 if (!stopped())
4759 set_result(result_val->in(_null_path));
4760 return true;
4761 }
4762
4763 // We only go to the fast case code if we pass a number of guards. The
4764 // paths which do not pass are accumulated in the slow_region.
4765 RegionNode* slow_region = new RegionNode(1);
4766 record_for_igvn(slow_region);
4767
4768 // If this is a virtual call, we generate a funny guard. We pull out
4769 // the vtable entry corresponding to hashCode() from the target object.
4770 // If the target method which we are calling happens to be the native
4771 // Object hashCode() method, we pass the guard. We do not need this
4772 // guard for non-virtual calls -- the caller is known to be the native
4773 // Object hashCode().
4774 if (is_virtual) {
4775 // After null check, get the object's klass.
4776 Node* obj_klass = load_object_klass(obj);
4777 generate_virtual_guard(obj_klass, slow_region);
4778 }
4779
4780 // Get the header out of the object, use LoadMarkNode when available
4781 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4782 // The control of the load must be null. Otherwise, the load can move before
4783 // the null check after castPP removal.
4784 Node* no_ctrl = nullptr;
4785 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4786
4787 if (!UseObjectMonitorTable) {
4788 // Test the header to see if it is safe to read w.r.t. locking.
4789 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
4790 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4791 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
4792 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
4793 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
4794
4795 generate_slow_guard(test_monitor, slow_region);
4796 }
4797
4798 // Get the hash value and check to see that it has been properly assigned.
4799 // We depend on hash_mask being at most 32 bits and avoid the use of
4800 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4801 // vm: see markWord.hpp.
4802 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
4803 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
4804 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4805 // This hack lets the hash bits live anywhere in the mark object now, as long
4806 // as the shift drops the relevant bits into the low 32 bits. Note that
4807 // Java spec says that HashCode is an int so there's no point in capturing
4808 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4836 // this->control() comes from set_results_for_java_call
4837 result_reg->init_req(_slow_path, control());
4838 result_val->init_req(_slow_path, slow_result);
4839 result_io ->set_req(_slow_path, i_o());
4840 result_mem ->set_req(_slow_path, reset_memory());
4841 }
4842
4843 // Return the combined state.
4844 set_i_o( _gvn.transform(result_io) );
4845 set_all_memory( _gvn.transform(result_mem));
4846
4847 set_result(result_reg, result_val);
4848 return true;
4849 }
4850
4851 //---------------------------inline_native_getClass----------------------------
4852 // public final native Class<?> java.lang.Object.getClass();
4853 //
4854 // Build special case code for calls to getClass on an object.
4855 bool LibraryCallKit::inline_native_getClass() {
4856 Node* obj = null_check_receiver();
4857 if (stopped()) return true;
4858 set_result(load_mirror_from_klass(load_object_klass(obj)));
4859 return true;
4860 }
4861
4862 //-----------------inline_native_Reflection_getCallerClass---------------------
4863 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4864 //
4865 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4866 //
4867 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4868 // in that it must skip particular security frames and checks for
4869 // caller sensitive methods.
4870 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4871 #ifndef PRODUCT
4872 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4873 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4874 }
4875 #endif
4876
5258 // not cloneable or finalizer => slow path to out-of-line Object.clone
5259 //
5260 // The general case has two steps, allocation and copying.
5261 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5262 //
5263 // Copying also has two cases, oop arrays and everything else.
5264 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5265 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5266 //
5267 // These steps fold up nicely if and when the cloned object's klass
5268 // can be sharply typed as an object array, a type array, or an instance.
5269 //
5270 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5271 PhiNode* result_val;
5272
5273 // Set the reexecute bit for the interpreter to reexecute
5274 // the bytecode that invokes Object.clone if deoptimization happens.
5275 { PreserveReexecuteState preexecs(this);
5276 jvms()->set_should_reexecute(true);
5277
5278 Node* obj = null_check_receiver();
5279 if (stopped()) return true;
5280
5281 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5282
5283 // If we are going to clone an instance, we need its exact type to
5284 // know the number and types of fields to convert the clone to
5285 // loads/stores. Maybe a speculative type can help us.
5286 if (!obj_type->klass_is_exact() &&
5287 obj_type->speculative_type() != nullptr &&
5288 obj_type->speculative_type()->is_instance_klass()) {
5289 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5290 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5291 !spec_ik->has_injected_fields()) {
5292 if (!obj_type->isa_instptr() ||
5293 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5294 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5295 }
5296 }
5297 }
5298
5299 // Conservatively insert a memory barrier on all memory slices.
5300 // Do not let writes into the original float below the clone.
5301 insert_mem_bar(Op_MemBarCPUOrder);
5302
5303 // paths into result_reg:
5304 enum {
5305 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5306 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5307 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5308 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5309 PATH_LIMIT
5310 };
5311 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5312 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5313 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5314 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5315 record_for_igvn(result_reg);
5316
5317 Node* obj_klass = load_object_klass(obj);
5318 Node* array_obj = obj;
5319 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5320 if (array_ctl != nullptr) {
5321 // It's an array.
5322 PreserveJVMState pjvms(this);
5323 set_control(array_ctl);
5324 Node* obj_length = load_array_length(array_obj);
5325 Node* array_size = nullptr; // Size of the array without object alignment padding.
5326 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5327
5328 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5329 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5330 // If it is an oop array, it requires very special treatment,
5331 // because gc barriers are required when accessing the array.
5332 Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5333 if (is_obja != nullptr) {
5334 PreserveJVMState pjvms2(this);
5335 set_control(is_obja);
5336 // Generate a direct call to the right arraycopy function(s).
5337 // Clones are always tightly coupled.
5338 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5339 ac->set_clone_oop_array();
5340 Node* n = _gvn.transform(ac);
5341 assert(n == ac, "cannot disappear");
5342 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5343
5344 result_reg->init_req(_objArray_path, control());
5345 result_val->init_req(_objArray_path, alloc_obj);
5346 result_i_o ->set_req(_objArray_path, i_o());
5347 result_mem ->set_req(_objArray_path, reset_memory());
5348 }
5349 }
5350 // Otherwise, there are no barriers to worry about.
5351 // (We can dispense with card marks if we know the allocation
5352 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5353 // causes the non-eden paths to take compensating steps to
5354 // simulate a fresh allocation, so that no further
5355 // card marks are required in compiled code to initialize
5356 // the object.)
5357
5358 if (!stopped()) {
5359 copy_to_clone(array_obj, alloc_obj, array_size, true);
5360
5361 // Present the results of the copy.
5362 result_reg->init_req(_array_path, control());
5363 result_val->init_req(_array_path, alloc_obj);
5364 result_i_o ->set_req(_array_path, i_o());
5365 result_mem ->set_req(_array_path, reset_memory());
5366 }
5367 }
5368
5369 // We only go to the instance fast case code if we pass a number of guards.
5370 // The paths which do not pass are accumulated in the slow_region.
5371 RegionNode* slow_region = new RegionNode(1);
5372 record_for_igvn(slow_region);
5373 if (!stopped()) {
5374 // It's an instance (we did array above). Make the slow-path tests.
5375 // If this is a virtual call, we generate a funny guard. We grab
5376 // the vtable entry corresponding to clone() from the target object.
5377 // If the target method which we are calling happens to be the
5378 // Object clone() method, we pass the guard. We do not need this
5379 // guard for non-virtual calls; the caller is known to be the native
5380 // Object clone().
5381 if (is_virtual) {
5382 generate_virtual_guard(obj_klass, slow_region);
5383 }
5384
5385 // The object must be easily cloneable and must not have a finalizer.
5386 // Both of these conditions may be checked in a single test.
5387 // We could optimize the test further, but we don't care.
5388 generate_misc_flags_guard(obj_klass,
5389 // Test both conditions:
5390 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5391 // Must be cloneable but not finalizer:
5392 KlassFlags::_misc_is_cloneable_fast,
5484 set_jvms(sfpt->jvms());
5485 _reexecute_sp = jvms()->sp();
5486
5487 return saved_jvms;
5488 }
5489 }
5490 }
5491 return nullptr;
5492 }
5493
5494 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5495 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5496 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5497 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5498 uint size = alloc->req();
5499 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5500 old_jvms->set_map(sfpt);
5501 for (uint i = 0; i < size; i++) {
5502 sfpt->init_req(i, alloc->in(i));
5503 }
5504 // re-push array length for deoptimization
5505 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
5506 old_jvms->set_sp(old_jvms->sp()+1);
5507 old_jvms->set_monoff(old_jvms->monoff()+1);
5508 old_jvms->set_scloff(old_jvms->scloff()+1);
5509 old_jvms->set_endoff(old_jvms->endoff()+1);
5510 old_jvms->set_should_reexecute(true);
5511
5512 sfpt->set_i_o(map()->i_o());
5513 sfpt->set_memory(map()->memory());
5514 sfpt->set_control(map()->control());
5515 return sfpt;
5516 }
5517
5518 // In case of a deoptimization, we restart execution at the
5519 // allocation, allocating a new array. We would leave an uninitialized
5520 // array in the heap that GCs wouldn't expect. Move the allocation
5521 // after the traps so we don't allocate the array if we
5522 // deoptimize. This is possible because tightly_coupled_allocation()
5523 // guarantees there's no observer of the allocated array at this point
5524 // and the control flow is simple enough.
5525 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5526 int saved_reexecute_sp, uint new_idx) {
5527 if (saved_jvms_before_guards != nullptr && !stopped()) {
5528 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5529
5530 assert(alloc != nullptr, "only with a tightly coupled allocation");
5531 // restore JVM state to the state at the arraycopy
5532 saved_jvms_before_guards->map()->set_control(map()->control());
5533 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5534 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5535 // If we've improved the types of some nodes (null check) while
5536 // emitting the guards, propagate them to the current state
5537 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5538 set_jvms(saved_jvms_before_guards);
5539 _reexecute_sp = saved_reexecute_sp;
5540
5541 // Remove the allocation from above the guards
5542 CallProjections callprojs;
5543 alloc->extract_projections(&callprojs, true);
5544 InitializeNode* init = alloc->initialization();
5545 Node* alloc_mem = alloc->in(TypeFunc::Memory);
5546 C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5547 C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
5548
5549 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5550 // the allocation (i.e. is only valid if the allocation succeeds):
5551 // 1) replace CastIINode with AllocateArrayNode's length here
5552 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5553 //
5554 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5555 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5556 Node* init_control = init->proj_out(TypeFunc::Control);
5557 Node* alloc_length = alloc->Ideal_length();
5558 #ifdef ASSERT
5559 Node* prev_cast = nullptr;
5560 #endif
5561 for (uint i = 0; i < init_control->outcnt(); i++) {
5562 Node* init_out = init_control->raw_out(i);
5563 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5564 #ifdef ASSERT
5565 if (prev_cast == nullptr) {
5566 prev_cast = init_out;
5568 if (prev_cast->cmp(*init_out) == false) {
5569 prev_cast->dump();
5570 init_out->dump();
5571 assert(false, "not equal CastIINode");
5572 }
5573 }
5574 #endif
5575 C->gvn_replace_by(init_out, alloc_length);
5576 }
5577 }
5578 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5579
5580 // move the allocation here (after the guards)
5581 _gvn.hash_delete(alloc);
5582 alloc->set_req(TypeFunc::Control, control());
5583 alloc->set_req(TypeFunc::I_O, i_o());
5584 Node *mem = reset_memory();
5585 set_all_memory(mem);
5586 alloc->set_req(TypeFunc::Memory, mem);
5587 set_control(init->proj_out_or_null(TypeFunc::Control));
5588 set_i_o(callprojs.fallthrough_ioproj);
5589
5590 // Update memory as done in GraphKit::set_output_for_allocation()
5591 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5592 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5593 if (ary_type->isa_aryptr() && length_type != nullptr) {
5594 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5595 }
5596 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5597 int elemidx = C->get_alias_index(telemref);
5598 set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
5599 set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
5600
5601 Node* allocx = _gvn.transform(alloc);
5602 assert(allocx == alloc, "where has the allocation gone?");
5603 assert(dest->is_CheckCastPP(), "not an allocation result?");
5604
5605 _gvn.hash_delete(dest);
5606 dest->set_req(0, control());
5607 Node* destx = _gvn.transform(dest);
5608 assert(destx == dest, "where has the allocation result gone?");
5906 top_src = src_type->isa_aryptr();
5907 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5908 src_spec = true;
5909 }
5910 if (!has_dest) {
5911 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5912 dest_type = _gvn.type(dest);
5913 top_dest = dest_type->isa_aryptr();
5914 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5915 dest_spec = true;
5916 }
5917 }
5918 }
5919
5920 if (has_src && has_dest && can_emit_guards) {
5921 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
5922 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
5923 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
5924 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
5925
5926 if (src_elem == dest_elem && src_elem == T_OBJECT) {
5927 // If both arrays are object arrays then having the exact types
5928 // for both will remove the need for a subtype check at runtime
5929 // before the call and may make it possible to pick a faster copy
5930 // routine (without a subtype check on every element)
5931 // Do we have the exact type of src?
5932 bool could_have_src = src_spec;
5933 // Do we have the exact type of dest?
5934 bool could_have_dest = dest_spec;
5935 ciKlass* src_k = nullptr;
5936 ciKlass* dest_k = nullptr;
5937 if (!src_spec) {
5938 src_k = src_type->speculative_type_not_null();
5939 if (src_k != nullptr && src_k->is_array_klass()) {
5940 could_have_src = true;
5941 }
5942 }
5943 if (!dest_spec) {
5944 dest_k = dest_type->speculative_type_not_null();
5945 if (dest_k != nullptr && dest_k->is_array_klass()) {
5946 could_have_dest = true;
5947 }
5948 }
5949 if (could_have_src && could_have_dest) {
5950 // If we can have both exact types, emit the missing guards
5951 if (could_have_src && !src_spec) {
5952 src = maybe_cast_profiled_obj(src, src_k, true);
5953 }
5954 if (could_have_dest && !dest_spec) {
5955 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5956 }
5957 }
5958 }
5959 }
5960
5961 ciMethod* trap_method = method();
5962 int trap_bci = bci();
5963 if (saved_jvms_before_guards != nullptr) {
5964 trap_method = alloc->jvms()->method();
5965 trap_bci = alloc->jvms()->bci();
5966 }
5967
5968 bool negative_length_guard_generated = false;
5969
5970 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5971 can_emit_guards &&
5972 !src->is_top() && !dest->is_top()) {
5973 // validate arguments: enables transformation the ArrayCopyNode
5974 validated = true;
5975
5976 RegionNode* slow_region = new RegionNode(1);
5977 record_for_igvn(slow_region);
5978
5979 // (1) src and dest are arrays.
5980 generate_non_array_guard(load_object_klass(src), slow_region, &src);
5981 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
5982
5983 // (2) src and dest arrays must have elements of the same BasicType
5984 // done at macro expansion or at Ideal transformation time
5985
5986 // (4) src_offset must not be negative.
5987 generate_negative_guard(src_offset, slow_region);
5988
5989 // (5) dest_offset must not be negative.
5990 generate_negative_guard(dest_offset, slow_region);
5991
5992 // (7) src_offset + length must not exceed length of src.
5995 slow_region);
5996
5997 // (8) dest_offset + length must not exceed length of dest.
5998 generate_limit_guard(dest_offset, length,
5999 load_array_length(dest),
6000 slow_region);
6001
6002 // (6) length must not be negative.
6003 // This is also checked in generate_arraycopy() during macro expansion, but
6004 // we also have to check it here for the case where the ArrayCopyNode will
6005 // be eliminated by Escape Analysis.
6006 if (EliminateAllocations) {
6007 generate_negative_guard(length, slow_region);
6008 negative_length_guard_generated = true;
6009 }
6010
6011 // (9) each element of an oop array must be assignable
6012 Node* dest_klass = load_object_klass(dest);
6013 if (src != dest) {
6014 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6015
6016 if (not_subtype_ctrl != top()) {
6017 PreserveJVMState pjvms(this);
6018 set_control(not_subtype_ctrl);
6019 uncommon_trap(Deoptimization::Reason_intrinsic,
6020 Deoptimization::Action_make_not_entrant);
6021 assert(stopped(), "Should be stopped");
6022 }
6023 }
6024 {
6025 PreserveJVMState pjvms(this);
6026 set_control(_gvn.transform(slow_region));
6027 uncommon_trap(Deoptimization::Reason_intrinsic,
6028 Deoptimization::Action_make_not_entrant);
6029 assert(stopped(), "Should be stopped");
6030 }
6031
6032 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6033 const Type *toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6034 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6035 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6036 }
6037
6038 if (stopped()) {
6039 return true;
6040 }
6041
6042 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6043 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6044 // so the compiler has a chance to eliminate them: during macro expansion,
6045 // we have to set their control (CastPP nodes are eliminated).
6046 load_object_klass(src), load_object_klass(dest),
6047 load_array_length(src), load_array_length(dest));
6048
6049 ac->set_arraycopy(validated);
6050
6051 Node* n = _gvn.transform(ac);
6052 if (n == ac) {
6053 ac->connect_outputs(this);
6054 } 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/ciSymbols.hpp"
30 #include "ci/ciUtilities.inline.hpp"
31 #include "classfile/vmIntrinsics.hpp"
32 #include "compiler/compileBroker.hpp"
33 #include "compiler/compileLog.hpp"
34 #include "gc/shared/barrierSet.hpp"
35 #include "gc/shared/c2/barrierSetC2.hpp"
36 #include "jfr/support/jfrIntrinsics.hpp"
37 #include "memory/resourceArea.hpp"
38 #include "oops/accessDecorators.hpp"
39 #include "oops/klass.inline.hpp"
40 #include "oops/layoutKind.hpp"
41 #include "oops/objArrayKlass.hpp"
42 #include "opto/addnode.hpp"
43 #include "opto/arraycopynode.hpp"
44 #include "opto/c2compiler.hpp"
45 #include "opto/castnode.hpp"
46 #include "opto/cfgnode.hpp"
47 #include "opto/convertnode.hpp"
48 #include "opto/countbitsnode.hpp"
49 #include "opto/graphKit.hpp"
50 #include "opto/idealKit.hpp"
51 #include "opto/inlinetypenode.hpp"
52 #include "opto/library_call.hpp"
53 #include "opto/mathexactnode.hpp"
54 #include "opto/mulnode.hpp"
55 #include "opto/narrowptrnode.hpp"
56 #include "opto/opaquenode.hpp"
57 #include "opto/opcodes.hpp"
58 #include "opto/parse.hpp"
59 #include "opto/rootnode.hpp"
60 #include "opto/runtime.hpp"
61 #include "opto/subnode.hpp"
62 #include "opto/type.hpp"
63 #include "opto/vectornode.hpp"
64 #include "prims/jvmtiExport.hpp"
65 #include "prims/jvmtiThreadState.hpp"
66 #include "prims/unsafe.hpp"
67 #include "runtime/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.
312 case vmIntrinsics::_indexOfIL: return inline_string_indexOfI(StrIntrinsicNode::LL);
313 case vmIntrinsics::_indexOfIU: return inline_string_indexOfI(StrIntrinsicNode::UU);
314 case vmIntrinsics::_indexOfIUL: return inline_string_indexOfI(StrIntrinsicNode::UL);
315 case vmIntrinsics::_indexOfU_char: return inline_string_indexOfChar(StrIntrinsicNode::U);
316 case vmIntrinsics::_indexOfL_char: return inline_string_indexOfChar(StrIntrinsicNode::L);
317
318 case vmIntrinsics::_equalsL: return inline_string_equals(StrIntrinsicNode::LL);
319
320 case vmIntrinsics::_vectorizedHashCode: return inline_vectorizedHashCode();
321
322 case vmIntrinsics::_toBytesStringU: return inline_string_toBytesU();
323 case vmIntrinsics::_getCharsStringU: return inline_string_getCharsU();
324 case vmIntrinsics::_getCharStringU: return inline_string_char_access(!is_store);
325 case vmIntrinsics::_putCharStringU: return inline_string_char_access( is_store);
326
327 case vmIntrinsics::_compressStringC:
328 case vmIntrinsics::_compressStringB: return inline_string_copy( is_compress);
329 case vmIntrinsics::_inflateStringC:
330 case vmIntrinsics::_inflateStringB: return inline_string_copy(!is_compress);
331
332 case vmIntrinsics::_makePrivateBuffer: return inline_unsafe_make_private_buffer();
333 case vmIntrinsics::_finishPrivateBuffer: return inline_unsafe_finish_private_buffer();
334 case vmIntrinsics::_getReference: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false);
335 case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_store, T_BOOLEAN, Relaxed, false);
336 case vmIntrinsics::_getByte: return inline_unsafe_access(!is_store, T_BYTE, Relaxed, false);
337 case vmIntrinsics::_getShort: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, false);
338 case vmIntrinsics::_getChar: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, false);
339 case vmIntrinsics::_getInt: return inline_unsafe_access(!is_store, T_INT, Relaxed, false);
340 case vmIntrinsics::_getLong: return inline_unsafe_access(!is_store, T_LONG, Relaxed, false);
341 case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_store, T_FLOAT, Relaxed, false);
342 case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_store, T_DOUBLE, Relaxed, false);
343 case vmIntrinsics::_getValue: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false, true);
344
345 case vmIntrinsics::_putReference: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false);
346 case vmIntrinsics::_putBoolean: return inline_unsafe_access( is_store, T_BOOLEAN, Relaxed, false);
347 case vmIntrinsics::_putByte: return inline_unsafe_access( is_store, T_BYTE, Relaxed, false);
348 case vmIntrinsics::_putShort: return inline_unsafe_access( is_store, T_SHORT, Relaxed, false);
349 case vmIntrinsics::_putChar: return inline_unsafe_access( is_store, T_CHAR, Relaxed, false);
350 case vmIntrinsics::_putInt: return inline_unsafe_access( is_store, T_INT, Relaxed, false);
351 case vmIntrinsics::_putLong: return inline_unsafe_access( is_store, T_LONG, Relaxed, false);
352 case vmIntrinsics::_putFloat: return inline_unsafe_access( is_store, T_FLOAT, Relaxed, false);
353 case vmIntrinsics::_putDouble: return inline_unsafe_access( is_store, T_DOUBLE, Relaxed, false);
354 case vmIntrinsics::_putValue: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false, true);
355
356 case vmIntrinsics::_getReferenceVolatile: return inline_unsafe_access(!is_store, T_OBJECT, Volatile, false);
357 case vmIntrinsics::_getBooleanVolatile: return inline_unsafe_access(!is_store, T_BOOLEAN, Volatile, false);
358 case vmIntrinsics::_getByteVolatile: return inline_unsafe_access(!is_store, T_BYTE, Volatile, false);
359 case vmIntrinsics::_getShortVolatile: return inline_unsafe_access(!is_store, T_SHORT, Volatile, false);
360 case vmIntrinsics::_getCharVolatile: return inline_unsafe_access(!is_store, T_CHAR, Volatile, false);
361 case vmIntrinsics::_getIntVolatile: return inline_unsafe_access(!is_store, T_INT, Volatile, false);
362 case vmIntrinsics::_getLongVolatile: return inline_unsafe_access(!is_store, T_LONG, Volatile, false);
363 case vmIntrinsics::_getFloatVolatile: return inline_unsafe_access(!is_store, T_FLOAT, Volatile, false);
364 case vmIntrinsics::_getDoubleVolatile: return inline_unsafe_access(!is_store, T_DOUBLE, Volatile, false);
365
366 case vmIntrinsics::_putReferenceVolatile: return inline_unsafe_access( is_store, T_OBJECT, Volatile, false);
367 case vmIntrinsics::_putBooleanVolatile: return inline_unsafe_access( is_store, T_BOOLEAN, Volatile, false);
368 case vmIntrinsics::_putByteVolatile: return inline_unsafe_access( is_store, T_BYTE, Volatile, false);
369 case vmIntrinsics::_putShortVolatile: return inline_unsafe_access( is_store, T_SHORT, Volatile, false);
370 case vmIntrinsics::_putCharVolatile: return inline_unsafe_access( is_store, T_CHAR, Volatile, false);
371 case vmIntrinsics::_putIntVolatile: return inline_unsafe_access( is_store, T_INT, Volatile, false);
372 case vmIntrinsics::_putLongVolatile: return inline_unsafe_access( is_store, T_LONG, Volatile, false);
373 case vmIntrinsics::_putFloatVolatile: return inline_unsafe_access( is_store, T_FLOAT, Volatile, false);
374 case vmIntrinsics::_putDoubleVolatile: return inline_unsafe_access( is_store, T_DOUBLE, Volatile, false);
406 case vmIntrinsics::_getReferenceOpaque: return inline_unsafe_access(!is_store, T_OBJECT, Opaque, false);
407 case vmIntrinsics::_getBooleanOpaque: return inline_unsafe_access(!is_store, T_BOOLEAN, Opaque, false);
408 case vmIntrinsics::_getByteOpaque: return inline_unsafe_access(!is_store, T_BYTE, Opaque, false);
409 case vmIntrinsics::_getShortOpaque: return inline_unsafe_access(!is_store, T_SHORT, Opaque, false);
410 case vmIntrinsics::_getCharOpaque: return inline_unsafe_access(!is_store, T_CHAR, Opaque, false);
411 case vmIntrinsics::_getIntOpaque: return inline_unsafe_access(!is_store, T_INT, Opaque, false);
412 case vmIntrinsics::_getLongOpaque: return inline_unsafe_access(!is_store, T_LONG, Opaque, false);
413 case vmIntrinsics::_getFloatOpaque: return inline_unsafe_access(!is_store, T_FLOAT, Opaque, false);
414 case vmIntrinsics::_getDoubleOpaque: return inline_unsafe_access(!is_store, T_DOUBLE, Opaque, false);
415
416 case vmIntrinsics::_putReferenceOpaque: return inline_unsafe_access( is_store, T_OBJECT, Opaque, false);
417 case vmIntrinsics::_putBooleanOpaque: return inline_unsafe_access( is_store, T_BOOLEAN, Opaque, false);
418 case vmIntrinsics::_putByteOpaque: return inline_unsafe_access( is_store, T_BYTE, Opaque, false);
419 case vmIntrinsics::_putShortOpaque: return inline_unsafe_access( is_store, T_SHORT, Opaque, false);
420 case vmIntrinsics::_putCharOpaque: return inline_unsafe_access( is_store, T_CHAR, Opaque, false);
421 case vmIntrinsics::_putIntOpaque: return inline_unsafe_access( is_store, T_INT, Opaque, false);
422 case vmIntrinsics::_putLongOpaque: return inline_unsafe_access( is_store, T_LONG, Opaque, false);
423 case vmIntrinsics::_putFloatOpaque: return inline_unsafe_access( is_store, T_FLOAT, Opaque, false);
424 case vmIntrinsics::_putDoubleOpaque: return inline_unsafe_access( is_store, T_DOUBLE, Opaque, false);
425
426 case vmIntrinsics::_getFlatValue: return inline_unsafe_flat_access(!is_store, Relaxed);
427 case vmIntrinsics::_putFlatValue: return inline_unsafe_flat_access( is_store, Relaxed);
428
429 case vmIntrinsics::_compareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap, Volatile);
430 case vmIntrinsics::_compareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap, Volatile);
431 case vmIntrinsics::_compareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap, Volatile);
432 case vmIntrinsics::_compareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap, Volatile);
433 case vmIntrinsics::_compareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap, Volatile);
434
435 case vmIntrinsics::_weakCompareAndSetReferencePlain: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
436 case vmIntrinsics::_weakCompareAndSetReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
437 case vmIntrinsics::_weakCompareAndSetReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
438 case vmIntrinsics::_weakCompareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
439 case vmIntrinsics::_weakCompareAndSetBytePlain: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Relaxed);
440 case vmIntrinsics::_weakCompareAndSetByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Acquire);
441 case vmIntrinsics::_weakCompareAndSetByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Release);
442 case vmIntrinsics::_weakCompareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Volatile);
443 case vmIntrinsics::_weakCompareAndSetShortPlain: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Relaxed);
444 case vmIntrinsics::_weakCompareAndSetShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Acquire);
445 case vmIntrinsics::_weakCompareAndSetShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Release);
446 case vmIntrinsics::_weakCompareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Volatile);
447 case vmIntrinsics::_weakCompareAndSetIntPlain: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Relaxed);
448 case vmIntrinsics::_weakCompareAndSetIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Acquire);
516 #endif
517 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
518 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
519 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
520 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
521 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
522 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
523 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
524 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
525 case vmIntrinsics::_getLength: return inline_native_getLength();
526 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
527 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
528 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
529 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
530 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
531 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
532 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
533
534 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
535 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
536 case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
537 case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
538 case vmIntrinsics::_newNullableAtomicArray: return inline_newArray(/* null_free */ false, /* atomic */ true);
539 case vmIntrinsics::_isFlatArray: return inline_getArrayProperties(IsFlat);
540 case vmIntrinsics::_isNullRestrictedArray: return inline_getArrayProperties(IsNullRestricted);
541 case vmIntrinsics::_isAtomicArray: return inline_getArrayProperties(IsAtomic);
542
543 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
544
545 case vmIntrinsics::_isInstance:
546 case vmIntrinsics::_isHidden:
547 case vmIntrinsics::_getSuperclass: return inline_native_Class_query(intrinsic_id());
548
549 case vmIntrinsics::_floatToRawIntBits:
550 case vmIntrinsics::_floatToIntBits:
551 case vmIntrinsics::_intBitsToFloat:
552 case vmIntrinsics::_doubleToRawLongBits:
553 case vmIntrinsics::_doubleToLongBits:
554 case vmIntrinsics::_longBitsToDouble:
555 case vmIntrinsics::_floatToFloat16:
556 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
557 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
558 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
559 case vmIntrinsics::_floatIsFinite:
560 case vmIntrinsics::_floatIsInfinite:
561 case vmIntrinsics::_doubleIsFinite:
2339 case vmIntrinsics::_remainderUnsigned_l: {
2340 zero_check_long(argument(2));
2341 // Compile-time detect of null-exception
2342 if (stopped()) {
2343 return true; // keep the graph constructed so far
2344 }
2345 n = new UModLNode(control(), argument(0), argument(2));
2346 break;
2347 }
2348 default: fatal_unexpected_iid(id); break;
2349 }
2350 set_result(_gvn.transform(n));
2351 return true;
2352 }
2353
2354 //----------------------------inline_unsafe_access----------------------------
2355
2356 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2357 // Attempt to infer a sharper value type from the offset and base type.
2358 ciKlass* sharpened_klass = nullptr;
2359 bool null_free = false;
2360
2361 // See if it is an instance field, with an object type.
2362 if (alias_type->field() != nullptr) {
2363 if (alias_type->field()->type()->is_klass()) {
2364 sharpened_klass = alias_type->field()->type()->as_klass();
2365 null_free = alias_type->field()->is_null_free();
2366 }
2367 }
2368
2369 const TypeOopPtr* result = nullptr;
2370 // See if it is a narrow oop array.
2371 if (adr_type->isa_aryptr()) {
2372 if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2373 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2374 null_free = adr_type->is_aryptr()->is_null_free();
2375 if (elem_type != nullptr && elem_type->is_loaded()) {
2376 // Sharpen the value type.
2377 result = elem_type;
2378 }
2379 }
2380 }
2381
2382 // The sharpened class might be unloaded if there is no class loader
2383 // contraint in place.
2384 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2385 // Sharpen the value type.
2386 result = TypeOopPtr::make_from_klass(sharpened_klass);
2387 if (null_free) {
2388 result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2389 }
2390 }
2391 if (result != nullptr) {
2392 #ifndef PRODUCT
2393 if (C->print_intrinsics() || C->print_inlining()) {
2394 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2395 tty->print(" sharpened value: "); result->dump(); tty->cr();
2396 }
2397 #endif
2398 }
2399 return result;
2400 }
2401
2402 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2403 switch (kind) {
2404 case Relaxed:
2405 return MO_UNORDERED;
2406 case Opaque:
2407 return MO_RELAXED;
2408 case Acquire:
2409 return MO_ACQUIRE;
2441 _kit->jvms()->set_sp(_sp);
2442 _map->set_jvms(_kit->jvms());
2443 _kit->set_map(_map);
2444 _kit->set_sp(_sp);
2445 for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2446 Node* out = _kit->control()->fast_out(i);
2447 if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2448 _kit->_gvn.hash_delete(out);
2449 out->set_req(0, _kit->C->top());
2450 _kit->C->record_for_igvn(out);
2451 --i; --imax;
2452 _kit->_gvn.hash_find_insert(out);
2453 }
2454 }
2455 }
2456
2457 void LibraryCallKit::SavedState::discard() {
2458 _discarded = true;
2459 }
2460
2461 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned, const bool is_flat) {
2462 if (callee()->is_static()) return false; // caller must have the capability!
2463 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2464 guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2465 guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2466 assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2467
2468 if (is_reference_type(type)) {
2469 decorators |= ON_UNKNOWN_OOP_REF;
2470 }
2471
2472 if (unaligned) {
2473 decorators |= C2_UNALIGNED;
2474 }
2475
2476 #ifndef PRODUCT
2477 {
2478 ResourceMark rm;
2479 // Check the signatures.
2480 ciSignature* sig = callee()->signature();
2481 #ifdef ASSERT
2482 if (!is_store) {
2483 // Object getReference(Object base, int/long offset), etc.
2484 BasicType rtype = sig->return_type()->basic_type();
2485 assert(rtype == type, "getter must return the expected value");
2486 assert(sig->count() == 2 || (is_flat && sig->count() == 3), "oop getter has 2 or 3 arguments");
2487 assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2488 assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2489 } else {
2490 // void putReference(Object base, int/long offset, Object x), etc.
2491 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2492 assert(sig->count() == 3 || (is_flat && sig->count() == 4), "oop putter has 3 arguments");
2493 assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2494 assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2495 BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2496 assert(vtype == type, "putter must accept the expected value");
2497 }
2498 #endif // ASSERT
2499 }
2500 #endif //PRODUCT
2501
2502 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2503
2504 Node* receiver = argument(0); // type: oop
2505
2506 // Build address expression.
2507 Node* heap_base_oop = top();
2508
2509 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2510 Node* base = argument(1); // type: oop
2511 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2512 Node* offset = argument(2); // type: long
2513 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2514 // to be plain byte offsets, which are also the same as those accepted
2515 // by oopDesc::field_addr.
2516 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2517 "fieldOffset must be byte-scaled");
2518
2519 ciInlineKlass* inline_klass = nullptr;
2520 if (is_flat) {
2521 const TypeInstPtr* cls = _gvn.type(argument(4))->isa_instptr();
2522 if (cls == nullptr || cls->const_oop() == nullptr) {
2523 return false;
2524 }
2525 ciType* mirror_type = cls->const_oop()->as_instance()->java_mirror_type();
2526 if (!mirror_type->is_inlinetype()) {
2527 return false;
2528 }
2529 inline_klass = mirror_type->as_inline_klass();
2530 }
2531
2532 if (base->is_InlineType()) {
2533 assert(!is_store, "InlineTypeNodes are non-larval value objects");
2534 InlineTypeNode* vt = base->as_InlineType();
2535 if (offset->is_Con()) {
2536 long off = find_long_con(offset, 0);
2537 ciInlineKlass* vk = vt->type()->inline_klass();
2538 if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2539 return false;
2540 }
2541
2542 ciField* field = vk->get_non_flat_field_by_offset(off);
2543 if (field != nullptr) {
2544 BasicType bt = type2field[field->type()->basic_type()];
2545 if (bt == T_ARRAY || bt == T_NARROWOOP) {
2546 bt = T_OBJECT;
2547 }
2548 if (bt == type && (!field->is_flat() || field->type() == inline_klass)) {
2549 Node* value = vt->field_value_by_offset(off, false);
2550 if (value->is_InlineType()) {
2551 value = value->as_InlineType()->adjust_scalarization_depth(this);
2552 }
2553 set_result(value);
2554 return true;
2555 }
2556 }
2557 }
2558 {
2559 // Re-execute the unsafe access if allocation triggers deoptimization.
2560 PreserveReexecuteState preexecs(this);
2561 jvms()->set_should_reexecute(true);
2562 vt = vt->buffer(this);
2563 }
2564 base = vt->get_oop();
2565 }
2566
2567 // 32-bit machines ignore the high half!
2568 offset = ConvL2X(offset);
2569
2570 // Save state and restore on bailout
2571 SavedState old_state(this);
2572
2573 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2574 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2575
2576 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2577 if (type != T_OBJECT && (inline_klass == nullptr || !inline_klass->has_object_fields())) {
2578 decorators |= IN_NATIVE; // off-heap primitive access
2579 } else {
2580 return false; // off-heap oop accesses are not supported
2581 }
2582 } else {
2583 heap_base_oop = base; // on-heap or mixed access
2584 }
2585
2586 // Can base be null? Otherwise, always on-heap access.
2587 bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2588
2589 if (!can_access_non_heap) {
2590 decorators |= IN_HEAP;
2591 }
2592
2593 Node* val = is_store ? argument(4 + (is_flat ? 1 : 0)) : nullptr;
2594
2595 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2596 if (adr_type == TypePtr::NULL_PTR) {
2597 return false; // off-heap access with zero address
2598 }
2599
2600 // Try to categorize the address.
2601 Compile::AliasType* alias_type = C->alias_type(adr_type);
2602 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2603
2604 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2605 alias_type->adr_type() == TypeAryPtr::RANGE) {
2606 return false; // not supported
2607 }
2608
2609 bool mismatched = false;
2610 BasicType bt = T_ILLEGAL;
2611 ciField* field = nullptr;
2612 if (adr_type->isa_instptr()) {
2613 const TypeInstPtr* instptr = adr_type->is_instptr();
2614 ciInstanceKlass* k = instptr->instance_klass();
2615 int off = instptr->offset();
2616 if (instptr->const_oop() != nullptr &&
2617 k == ciEnv::current()->Class_klass() &&
2618 instptr->offset() >= (k->size_helper() * wordSize)) {
2619 k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2620 field = k->get_field_by_offset(off, true);
2621 } else {
2622 field = k->get_non_flat_field_by_offset(off);
2623 }
2624 if (field != nullptr) {
2625 bt = type2field[field->type()->basic_type()];
2626 }
2627 if (bt != alias_type->basic_type()) {
2628 // Type mismatch. Is it an access to a nested flat field?
2629 field = k->get_field_by_offset(off, false);
2630 if (field != nullptr) {
2631 bt = type2field[field->type()->basic_type()];
2632 }
2633 }
2634 assert(bt == alias_type->basic_type() || is_flat, "should match");
2635 } else {
2636 bt = alias_type->basic_type();
2637 }
2638
2639 if (bt != T_ILLEGAL) {
2640 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2641 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2642 // Alias type doesn't differentiate between byte[] and boolean[]).
2643 // Use address type to get the element type.
2644 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2645 }
2646 if (is_reference_type(bt, true)) {
2647 // accessing an array field with getReference is not a mismatch
2648 bt = T_OBJECT;
2649 }
2650 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2651 // Don't intrinsify mismatched object accesses
2652 return false;
2653 }
2654 mismatched = (bt != type);
2655 } else if (alias_type->adr_type()->isa_oopptr()) {
2656 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2657 }
2658
2659 if (is_flat) {
2660 if (adr_type->isa_instptr()) {
2661 if (field == nullptr || field->type() != inline_klass) {
2662 mismatched = true;
2663 }
2664 } else if (adr_type->isa_aryptr()) {
2665 const Type* elem = adr_type->is_aryptr()->elem();
2666 if (!adr_type->is_flat() || elem->inline_klass() != inline_klass) {
2667 mismatched = true;
2668 }
2669 } else {
2670 mismatched = true;
2671 }
2672 if (is_store) {
2673 const Type* val_t = _gvn.type(val);
2674 if (!val_t->is_inlinetypeptr() || val_t->inline_klass() != inline_klass) {
2675 return false;
2676 }
2677 }
2678 }
2679
2680 old_state.discard();
2681 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2682
2683 if (mismatched) {
2684 decorators |= C2_MISMATCHED;
2685 }
2686
2687 // First guess at the value type.
2688 const Type *value_type = Type::get_const_basic_type(type);
2689
2690 // Figure out the memory ordering.
2691 decorators |= mo_decorator_for_access_kind(kind);
2692
2693 if (!is_store) {
2694 if (type == T_OBJECT && !is_flat) {
2695 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2696 if (tjp != nullptr) {
2697 value_type = tjp;
2698 }
2699 }
2700 }
2701
2702 receiver = null_check(receiver);
2703 if (stopped()) {
2704 return true;
2705 }
2706 // Heap pointers get a null-check from the interpreter,
2707 // as a courtesy. However, this is not guaranteed by Unsafe,
2708 // and it is not possible to fully distinguish unintended nulls
2709 // from intended ones in this API.
2710
2711 if (!is_store) {
2712 Node* p = nullptr;
2713 // Try to constant fold a load from a constant field
2714
2715 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2716 // final or stable field
2717 p = make_constant_from_field(field, heap_base_oop);
2718 }
2719
2720 if (p == nullptr) { // Could not constant fold the load
2721 if (is_flat) {
2722 p = InlineTypeNode::make_from_flat(this, inline_klass, base, adr, adr_type, false, false, true);
2723 } else {
2724 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2725 const TypeOopPtr* ptr = value_type->make_oopptr();
2726 if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2727 // Load a non-flattened inline type from memory
2728 p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2729 }
2730 }
2731 // Normalize the value returned by getBoolean in the following cases
2732 if (type == T_BOOLEAN &&
2733 (mismatched ||
2734 heap_base_oop == top() || // - heap_base_oop is null or
2735 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2736 // and the unsafe access is made to large offset
2737 // (i.e., larger than the maximum offset necessary for any
2738 // field access)
2739 ) {
2740 IdealKit ideal = IdealKit(this);
2741 #define __ ideal.
2742 IdealVariable normalized_result(ideal);
2743 __ declarations_done();
2744 __ set(normalized_result, p);
2745 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2746 __ set(normalized_result, ideal.ConI(1));
2747 ideal.end_if();
2748 final_sync(ideal);
2749 p = __ value(normalized_result);
2750 #undef __
2751 }
2752 }
2753 if (type == T_ADDRESS) {
2754 p = gvn().transform(new CastP2XNode(nullptr, p));
2755 p = ConvX2UL(p);
2756 }
2757 // The load node has the control of the preceding MemBarCPUOrder. All
2758 // following nodes will have the control of the MemBarCPUOrder inserted at
2759 // the end of this method. So, pushing the load onto the stack at a later
2760 // point is fine.
2761 set_result(p);
2762 } else {
2763 if (bt == T_ADDRESS) {
2764 // Repackage the long as a pointer.
2765 val = ConvL2X(val);
2766 val = gvn().transform(new CastX2PNode(val));
2767 }
2768 if (is_flat) {
2769 val->as_InlineType()->store_flat(this, base, adr, false, false, true, decorators);
2770 } else {
2771 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2772 }
2773 }
2774
2775 return true;
2776 }
2777
2778 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2779 #ifdef ASSERT
2780 {
2781 ResourceMark rm;
2782 // Check the signatures.
2783 ciSignature* sig = callee()->signature();
2784 assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2785 assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2786 assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2787 assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2788 if (is_store) {
2789 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2790 assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2791 assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2792 } else {
2793 assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2794 assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2795 }
2796 }
2797 #endif // ASSERT
2798
2799 assert(kind == Relaxed, "Only plain accesses for now");
2800 if (callee()->is_static()) {
2801 // caller must have the capability!
2802 return false;
2803 }
2804 C->set_has_unsafe_access(true);
2805
2806 const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2807 if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2808 // parameter valueType is not a constant
2809 return false;
2810 }
2811 ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2812 if (!mirror_type->is_inlinetype()) {
2813 // Dead code
2814 return false;
2815 }
2816 ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2817
2818 const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2819 if (layout_type == nullptr || !layout_type->is_con()) {
2820 // parameter layoutKind is not a constant
2821 return false;
2822 }
2823 assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2824 layout_type->get_con() <= static_cast<int>(LayoutKind::UNKNOWN),
2825 "invalid layoutKind %d", layout_type->get_con());
2826 LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2827 assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NON_ATOMIC_FLAT ||
2828 layout == LayoutKind::ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2829 "unexpected layoutKind %d", layout_type->get_con());
2830
2831 null_check(argument(0));
2832 if (stopped()) {
2833 return true;
2834 }
2835
2836 Node* base = must_be_not_null(argument(1), true);
2837 Node* offset = argument(2);
2838 const Type* base_type = _gvn.type(base);
2839
2840 Node* ptr;
2841 bool immutable_memory = false;
2842 DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2843 if (base_type->isa_instptr()) {
2844 const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2845 if (offset_type == nullptr || !offset_type->is_con()) {
2846 // Offset into a non-array should be a constant
2847 decorators |= C2_MISMATCHED;
2848 } else {
2849 int offset_con = checked_cast<int>(offset_type->get_con());
2850 ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2851 ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2852 if (field == nullptr) {
2853 assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2854 decorators |= C2_MISMATCHED;
2855 } else {
2856 assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2857 offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2858 immutable_memory = field->is_strict() && field->is_final();
2859
2860 if (base->is_InlineType()) {
2861 assert(!is_store, "Cannot store into a non-larval value object");
2862 set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2863 return true;
2864 }
2865 }
2866 }
2867
2868 if (base->is_InlineType()) {
2869 assert(!is_store, "Cannot store into a non-larval value object");
2870 base = base->as_InlineType()->buffer(this, true);
2871 }
2872 ptr = basic_plus_adr(base, ConvL2X(offset));
2873 } else if (base_type->isa_aryptr()) {
2874 decorators |= IS_ARRAY;
2875 if (layout == LayoutKind::REFERENCE) {
2876 if (!base_type->is_aryptr()->is_not_flat()) {
2877 const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2878 Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::StrongDependency));
2879 replace_in_map(base, new_base);
2880 base = new_base;
2881 }
2882 ptr = basic_plus_adr(base, ConvL2X(offset));
2883 } else {
2884 if (UseArrayFlattening) {
2885 // Flat array must have an exact type
2886 bool is_null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2887 bool is_atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2888 Node* new_base = cast_to_flat_array(base, value_klass, is_null_free, !is_null_free, is_atomic);
2889 replace_in_map(base, new_base);
2890 base = new_base;
2891 ptr = basic_plus_adr(base, ConvL2X(offset));
2892 const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2893 if (ptr_type->field_offset().get() != 0) {
2894 ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::StrongDependency));
2895 }
2896 } else {
2897 uncommon_trap(Deoptimization::Reason_intrinsic,
2898 Deoptimization::Action_none);
2899 return true;
2900 }
2901 }
2902 } else {
2903 decorators |= C2_MISMATCHED;
2904 ptr = basic_plus_adr(base, ConvL2X(offset));
2905 }
2906
2907 if (is_store) {
2908 Node* value = argument(6);
2909 const Type* value_type = _gvn.type(value);
2910 if (!value_type->is_inlinetypeptr()) {
2911 value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2912 Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::StrongDependency));
2913 new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2914 replace_in_map(value, new_value);
2915 value = new_value;
2916 }
2917
2918 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());
2919 if (layout == LayoutKind::REFERENCE) {
2920 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2921 access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2922 } else {
2923 bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2924 bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2925 value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2926 }
2927
2928 return true;
2929 } else {
2930 decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2931 InlineTypeNode* result;
2932 if (layout == LayoutKind::REFERENCE) {
2933 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2934 Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2935 result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2936 } else {
2937 bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2938 bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2939 result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2940 }
2941
2942 set_result(result);
2943 return true;
2944 }
2945 }
2946
2947 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2948 Node* receiver = argument(0);
2949 Node* value = argument(1);
2950
2951 const Type* type = gvn().type(value);
2952 if (!type->is_inlinetypeptr()) {
2953 C->record_method_not_compilable("value passed to Unsafe::makePrivateBuffer is not of a constant value type");
2954 return false;
2955 }
2956
2957 null_check(receiver);
2958 if (stopped()) {
2959 return true;
2960 }
2961
2962 value = null_check(value);
2963 if (stopped()) {
2964 return true;
2965 }
2966
2967 ciInlineKlass* vk = type->inline_klass();
2968 Node* klass = makecon(TypeKlassPtr::make(vk));
2969 Node* obj = new_instance(klass);
2970 AllocateNode::Ideal_allocation(obj)->_larval = true;
2971
2972 assert(value->is_InlineType(), "must be an InlineTypeNode");
2973 Node* payload_ptr = basic_plus_adr(obj, vk->payload_offset());
2974 value->as_InlineType()->store_flat(this, obj, payload_ptr, false, true, true, IN_HEAP | MO_UNORDERED);
2975
2976 set_result(obj);
2977 return true;
2978 }
2979
2980 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2981 Node* receiver = argument(0);
2982 Node* buffer = argument(1);
2983
2984 const Type* type = gvn().type(buffer);
2985 if (!type->is_inlinetypeptr()) {
2986 C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer is not of a constant value type");
2987 return false;
2988 }
2989
2990 AllocateNode* alloc = AllocateNode::Ideal_allocation(buffer);
2991 if (alloc == nullptr) {
2992 C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer must be allocated by Unsafe::makePrivateBuffer");
2993 return false;
2994 }
2995
2996 null_check(receiver);
2997 if (stopped()) {
2998 return true;
2999 }
3000
3001 // Unset the larval bit in the object header
3002 Node* old_header = make_load(control(), buffer, TypeX_X, TypeX_X->basic_type(), MemNode::unordered, LoadNode::Pinned);
3003 Node* new_header = gvn().transform(new AndXNode(old_header, MakeConX(~markWord::larval_bit_in_place)));
3004 access_store_at(buffer, buffer, type->is_ptr(), new_header, TypeX_X, TypeX_X->basic_type(), MO_UNORDERED | IN_HEAP);
3005
3006 // We must ensure that the buffer is properly published
3007 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
3008 assert(!type->maybe_null(), "result of an allocation should not be null");
3009 set_result(InlineTypeNode::make_from_oop(this, buffer, type->inline_klass()));
3010 return true;
3011 }
3012
3013 //----------------------------inline_unsafe_load_store----------------------------
3014 // This method serves a couple of different customers (depending on LoadStoreKind):
3015 //
3016 // LS_cmp_swap:
3017 //
3018 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
3019 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
3020 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
3021 //
3022 // LS_cmp_swap_weak:
3023 //
3024 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
3025 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
3026 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
3027 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
3028 //
3029 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
3030 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
3031 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
3032 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
3195 }
3196 case LS_cmp_swap:
3197 case LS_cmp_swap_weak:
3198 case LS_get_add:
3199 break;
3200 default:
3201 ShouldNotReachHere();
3202 }
3203
3204 // Null check receiver.
3205 receiver = null_check(receiver);
3206 if (stopped()) {
3207 return true;
3208 }
3209
3210 int alias_idx = C->get_alias_index(adr_type);
3211
3212 if (is_reference_type(type)) {
3213 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3214
3215 if (oldval != nullptr && oldval->is_InlineType()) {
3216 // Re-execute the unsafe access if allocation triggers deoptimization.
3217 PreserveReexecuteState preexecs(this);
3218 jvms()->set_should_reexecute(true);
3219 oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3220 }
3221 if (newval != nullptr && newval->is_InlineType()) {
3222 // Re-execute the unsafe access if allocation triggers deoptimization.
3223 PreserveReexecuteState preexecs(this);
3224 jvms()->set_should_reexecute(true);
3225 newval = newval->as_InlineType()->buffer(this)->get_oop();
3226 }
3227
3228 // Transformation of a value which could be null pointer (CastPP #null)
3229 // could be delayed during Parse (for example, in adjust_map_after_if()).
3230 // Execute transformation here to avoid barrier generation in such case.
3231 if (_gvn.type(newval) == TypePtr::NULL_PTR)
3232 newval = _gvn.makecon(TypePtr::NULL_PTR);
3233
3234 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3235 // Refine the value to a null constant, when it is known to be null
3236 oldval = _gvn.makecon(TypePtr::NULL_PTR);
3237 }
3238 }
3239
3240 Node* result = nullptr;
3241 switch (kind) {
3242 case LS_cmp_exchange: {
3243 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3244 oldval, newval, value_type, type, decorators);
3245 break;
3246 }
3247 case LS_cmp_swap_weak:
3394 Deoptimization::Action_make_not_entrant);
3395 }
3396 if (stopped()) {
3397 return true;
3398 }
3399 #endif //INCLUDE_JVMTI
3400
3401 Node* test = nullptr;
3402 if (LibraryCallKit::klass_needs_init_guard(kls)) {
3403 // Note: The argument might still be an illegal value like
3404 // Serializable.class or Object[].class. The runtime will handle it.
3405 // But we must make an explicit check for initialization.
3406 Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3407 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3408 // can generate code to load it as unsigned byte.
3409 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3410 Node* bits = intcon(InstanceKlass::fully_initialized);
3411 test = _gvn.transform(new SubINode(inst, bits));
3412 // The 'test' is non-zero if we need to take a slow path.
3413 }
3414 Node* obj = nullptr;
3415 const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3416 if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3417 obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3418 } else {
3419 obj = new_instance(kls, test);
3420 }
3421 set_result(obj);
3422 return true;
3423 }
3424
3425 //------------------------inline_native_time_funcs--------------
3426 // inline code for System.currentTimeMillis() and System.nanoTime()
3427 // these have the same type and signature
3428 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3429 const TypeFunc* tf = OptoRuntime::void_long_Type();
3430 const TypePtr* no_memory_effects = nullptr;
3431 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3432 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3433 #ifdef ASSERT
3434 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3435 assert(value_top == top(), "second value must be top");
3436 #endif
3437 set_result(value);
3438 return true;
3439 }
3440
4181 Node* thread = _gvn.transform(new ThreadLocalNode());
4182 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4183 Node* thread_obj_handle
4184 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4185 thread_obj_handle = _gvn.transform(thread_obj_handle);
4186 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4187 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4188
4189 // Change the _monitor_owner_id of the JavaThread
4190 Node* tid = load_field_from_object(arr, "tid", "J");
4191 Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4192 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4193
4194 JFR_ONLY(extend_setCurrentThread(thread, arr);)
4195 return true;
4196 }
4197
4198 const Type* LibraryCallKit::scopedValueCache_type() {
4199 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4200 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4201 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true);
4202
4203 // Because we create the scopedValue cache lazily we have to make the
4204 // type of the result BotPTR.
4205 bool xk = etype->klass_is_exact();
4206 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4207 return objects_type;
4208 }
4209
4210 Node* LibraryCallKit::scopedValueCache_helper() {
4211 Node* thread = _gvn.transform(new ThreadLocalNode());
4212 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4213 // We cannot use immutable_memory() because we might flip onto a
4214 // different carrier thread, at which point we'll need to use that
4215 // carrier thread's cache.
4216 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4217 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4218 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4219 }
4220
4221 //------------------------inline_native_scopedValueCache------------------
4222 bool LibraryCallKit::inline_native_scopedValueCache() {
4223 Node* cache_obj_handle = scopedValueCache_helper();
4224 const Type* objects_type = scopedValueCache_type();
4225 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4226
4310 store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4311
4312 // Result of top level CFG and Memory.
4313 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4314 record_for_igvn(result_rgn);
4315 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4316 record_for_igvn(result_mem);
4317
4318 result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4319 result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4320 result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4321 result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4322
4323 // Set output state.
4324 set_control(_gvn.transform(result_rgn));
4325 set_all_memory(_gvn.transform(result_mem));
4326
4327 return true;
4328 }
4329
4330 //-----------------------load_klass_from_mirror_common-------------------------
4331 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4332 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4333 // and branch to the given path on the region.
4334 // If never_see_null, take an uncommon trap on null, so we can optimistically
4335 // compile for the non-null case.
4336 // If the region is null, force never_see_null = true.
4337 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4338 bool never_see_null,
4339 RegionNode* region,
4340 int null_path,
4341 int offset) {
4342 if (region == nullptr) never_see_null = true;
4343 Node* p = basic_plus_adr(mirror, offset);
4344 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4345 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4346 Node* null_ctl = top();
4347 kls = null_check_oop(kls, &null_ctl, never_see_null);
4348 if (region != nullptr) {
4349 // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4353 }
4354 return kls;
4355 }
4356
4357 //--------------------(inline_native_Class_query helpers)---------------------
4358 // Use this for JVM_ACC_INTERFACE.
4359 // Fall through if (mods & mask) == bits, take the guard otherwise.
4360 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4361 ByteSize offset, const Type* type, BasicType bt) {
4362 // Branch around if the given klass has the given modifier bit set.
4363 // Like generate_guard, adds a new path onto the region.
4364 Node* modp = basic_plus_adr(kls, in_bytes(offset));
4365 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4366 Node* mask = intcon(modifier_mask);
4367 Node* bits = intcon(modifier_bits);
4368 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4369 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4370 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4371 return generate_fair_guard(bol, region);
4372 }
4373
4374 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4375 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4376 Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4377 }
4378
4379 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4380 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4381 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4382 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4383 }
4384
4385 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4386 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4387 }
4388
4389 //-------------------------inline_native_Class_query-------------------
4390 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4391 const Type* return_type = TypeInt::BOOL;
4392 Node* prim_return_value = top(); // what happens if it's a primitive class?
4393 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4503 }
4504 if (!stopped()) {
4505 query_value = load_mirror_from_klass(kls);
4506 }
4507 break;
4508
4509 default:
4510 fatal_unexpected_iid(id);
4511 break;
4512 }
4513
4514 // Fall-through is the normal case of a query to a real class.
4515 phi->init_req(1, query_value);
4516 region->init_req(1, control());
4517
4518 C->set_has_split_ifs(true); // Has chance for split-if optimization
4519 set_result(region, phi);
4520 return true;
4521 }
4522
4523
4524 //-------------------------inline_Class_cast-------------------
4525 bool LibraryCallKit::inline_Class_cast() {
4526 Node* mirror = argument(0); // Class
4527 Node* obj = argument(1);
4528 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4529 if (mirror_con == nullptr) {
4530 return false; // dead path (mirror->is_top()).
4531 }
4532 if (obj == nullptr || obj->is_top()) {
4533 return false; // dead path
4534 }
4535 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4536
4537 // First, see if Class.cast() can be folded statically.
4538 // java_mirror_type() returns non-null for compile-time Class constants.
4539 ciType* tm = mirror_con->java_mirror_type();
4540 if (tm != nullptr && tm->is_klass() &&
4541 tp != nullptr) {
4542 if (!tp->is_loaded()) {
4543 // Don't use intrinsic when class is not loaded.
4544 return false;
4545 } else {
4546 const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4547 int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4548 if (static_res == Compile::SSC_always_true) {
4549 // isInstance() is true - fold the code.
4550 set_result(obj);
4551 return true;
4552 } else if (static_res == Compile::SSC_always_false) {
4553 // Don't use intrinsic, have to throw ClassCastException.
4554 // If the reference is null, the non-intrinsic bytecode will
4555 // be optimized appropriately.
4556 return false;
4557 }
4558 }
4559 }
4560
4561 // Bailout intrinsic and do normal inlining if exception path is frequent.
4562 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4563 return false;
4564 }
4565
4566 // Generate dynamic checks.
4567 // Class.cast() is java implementation of _checkcast bytecode.
4568 // Do checkcast (Parse::do_checkcast()) optimizations here.
4569
4570 mirror = null_check(mirror);
4571 // If mirror is dead, only null-path is taken.
4572 if (stopped()) {
4573 return true;
4574 }
4575
4576 // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4577 enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4578 RegionNode* region = new RegionNode(PATH_LIMIT);
4579 record_for_igvn(region);
4580
4581 // Now load the mirror's klass metaobject, and null-check it.
4582 // If kls is null, we have a primitive mirror and
4583 // nothing is an instance of a primitive type.
4584 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4585
4586 Node* res = top();
4587 Node* io = i_o();
4588 Node* mem = merged_memory();
4589 if (!stopped()) {
4590
4591 Node* bad_type_ctrl = top();
4592 // Do checkcast optimizations.
4593 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4594 region->init_req(_bad_type_path, bad_type_ctrl);
4595 }
4596 if (region->in(_prim_path) != top() ||
4597 region->in(_bad_type_path) != top() ||
4598 region->in(_npe_path) != top()) {
4599 // Let Interpreter throw ClassCastException.
4600 PreserveJVMState pjvms(this);
4601 set_control(_gvn.transform(region));
4602 // Set IO and memory because gen_checkcast may override them when buffering inline types
4603 set_i_o(io);
4604 set_all_memory(mem);
4605 uncommon_trap(Deoptimization::Reason_intrinsic,
4606 Deoptimization::Action_maybe_recompile);
4607 }
4608 if (!stopped()) {
4609 set_result(res);
4610 }
4611 return true;
4612 }
4613
4614
4615 //--------------------------inline_native_subtype_check------------------------
4616 // This intrinsic takes the JNI calls out of the heart of
4617 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4618 bool LibraryCallKit::inline_native_subtype_check() {
4619 // Pull both arguments off the stack.
4620 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4621 args[0] = argument(0);
4622 args[1] = argument(1);
4623 Node* klasses[2]; // corresponding Klasses: superk, subk
4624 klasses[0] = klasses[1] = top();
4625
4626 enum {
4627 // A full decision tree on {superc is prim, subc is prim}:
4628 _prim_0_path = 1, // {P,N} => false
4629 // {P,P} & superc!=subc => false
4630 _prim_same_path, // {P,P} & superc==subc => true
4631 _prim_1_path, // {N,P} => false
4632 _ref_subtype_path, // {N,N} & subtype check wins => true
4633 _both_ref_path, // {N,N} & subtype check loses => false
4634 PATH_LIMIT
4635 };
4636
4637 RegionNode* region = new RegionNode(PATH_LIMIT);
4638 RegionNode* prim_region = new RegionNode(2);
4639 Node* phi = new PhiNode(region, TypeInt::BOOL);
4640 record_for_igvn(region);
4641 record_for_igvn(prim_region);
4642
4643 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4644 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4645 int class_klass_offset = java_lang_Class::klass_offset();
4646
4647 // First null-check both mirrors and load each mirror's klass metaobject.
4648 int which_arg;
4649 for (which_arg = 0; which_arg <= 1; which_arg++) {
4650 Node* arg = args[which_arg];
4651 arg = null_check(arg);
4652 if (stopped()) break;
4653 args[which_arg] = arg;
4654
4655 Node* p = basic_plus_adr(arg, class_klass_offset);
4656 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4657 klasses[which_arg] = _gvn.transform(kls);
4658 }
4659
4660 // Having loaded both klasses, test each for null.
4661 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4662 for (which_arg = 0; which_arg <= 1; which_arg++) {
4663 Node* kls = klasses[which_arg];
4664 Node* null_ctl = top();
4665 kls = null_check_oop(kls, &null_ctl, never_see_null);
4666 if (which_arg == 0) {
4667 prim_region->init_req(1, null_ctl);
4668 } else {
4669 region->init_req(_prim_1_path, null_ctl);
4670 }
4671 if (stopped()) break;
4672 klasses[which_arg] = kls;
4673 }
4674
4675 if (!stopped()) {
4676 // now we have two reference types, in klasses[0..1]
4677 Node* subk = klasses[1]; // the argument to isAssignableFrom
4678 Node* superk = klasses[0]; // the receiver
4679 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4680 region->set_req(_ref_subtype_path, control());
4681 }
4682
4683 // If both operands are primitive (both klasses null), then
4684 // we must return true when they are identical primitives.
4685 // It is convenient to test this after the first null klass check.
4686 // This path is also used if superc is a value mirror.
4687 set_control(_gvn.transform(prim_region));
4688 if (!stopped()) {
4689 // Since superc is primitive, make a guard for the superc==subc case.
4690 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4691 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4692 generate_fair_guard(bol_eq, region);
4693 if (region->req() == PATH_LIMIT+1) {
4694 // A guard was added. If the added guard is taken, superc==subc.
4695 region->swap_edges(PATH_LIMIT, _prim_same_path);
4696 region->del_req(PATH_LIMIT);
4697 }
4698 region->set_req(_prim_0_path, control()); // Not equal after all.
4699 }
4700
4701 // these are the only paths that produce 'true':
4702 phi->set_req(_prim_same_path, intcon(1));
4703 phi->set_req(_ref_subtype_path, intcon(1));
4704
4705 // pull together the cases:
4706 assert(region->req() == PATH_LIMIT, "sane region");
4707 for (uint i = 1; i < region->req(); i++) {
4708 Node* ctl = region->in(i);
4709 if (ctl == nullptr || ctl == top()) {
4710 region->set_req(i, top());
4711 phi ->set_req(i, top());
4712 } else if (phi->in(i) == nullptr) {
4713 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4714 }
4715 }
4716
4717 set_control(_gvn.transform(region));
4718 set_result(_gvn.transform(phi));
4719 return true;
4720 }
4721
4722 //---------------------generate_array_guard_common------------------------
4723 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4724
4725 if (stopped()) {
4726 return nullptr;
4727 }
4728
4729 // Like generate_guard, adds a new path onto the region.
4730 jint layout_con = 0;
4731 Node* layout_val = get_layout_helper(kls, layout_con);
4732 if (layout_val == nullptr) {
4733 bool query = 0;
4734 switch(kind) {
4735 case RefArray: query = Klass::layout_helper_is_refArray(layout_con); break;
4736 case NonRefArray: query = !Klass::layout_helper_is_refArray(layout_con); break;
4737 case TypeArray: query = Klass::layout_helper_is_typeArray(layout_con); break;
4738 case AnyArray: query = Klass::layout_helper_is_array(layout_con); break;
4739 case NonArray: query = !Klass::layout_helper_is_array(layout_con); break;
4740 default:
4741 ShouldNotReachHere();
4742 }
4743 if (!query) {
4744 return nullptr; // never a branch
4745 } else { // always a branch
4746 Node* always_branch = control();
4747 if (region != nullptr)
4748 region->add_req(always_branch);
4749 set_control(top());
4750 return always_branch;
4751 }
4752 }
4753 unsigned int value = 0;
4754 BoolTest::mask btest = BoolTest::illegal;
4755 switch(kind) {
4756 case RefArray:
4757 case NonRefArray: {
4758 value = Klass::_lh_array_tag_ref_value;
4759 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4760 btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4761 break;
4762 }
4763 case TypeArray: {
4764 value = Klass::_lh_array_tag_type_value;
4765 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4766 btest = BoolTest::eq;
4767 break;
4768 }
4769 case AnyArray: value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4770 case NonArray: value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4771 default:
4772 ShouldNotReachHere();
4773 }
4774 // Now test the correct condition.
4775 jint nval = (jint)value;
4776 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4777 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4778 Node* ctrl = generate_fair_guard(bol, region);
4779 Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4780 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4781 // Keep track of the fact that 'obj' is an array to prevent
4782 // array specific accesses from floating above the guard.
4783 *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4784 }
4785 return ctrl;
4786 }
4787
4788 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4789 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4790 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4791 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4792 assert(null_free || atomic, "nullable implies atomic");
4793 Node* componentType = argument(0);
4794 Node* length = argument(1);
4795 Node* init_val = null_free ? argument(2) : nullptr;
4796
4797 const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4798 if (tp != nullptr) {
4799 ciInstanceKlass* ik = tp->instance_klass();
4800 if (ik == C->env()->Class_klass()) {
4801 ciType* t = tp->java_mirror_type();
4802 if (t != nullptr && t->is_inlinetype()) {
4803
4804 ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4805 assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4806 assert(array_klass->is_elem_atomic() == atomic, "inconsistency");
4807
4808 // TOOD 8350865 ZGC needs card marks on initializing oop stores
4809 if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4810 return false;
4811 }
4812
4813 if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4814 const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces, true);
4815 if (null_free) {
4816 if (init_val->is_InlineType()) {
4817 if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4818 // Zeroing is enough because the init value is the all-zero value
4819 init_val = nullptr;
4820 } else {
4821 init_val = init_val->as_InlineType()->buffer(this);
4822 }
4823 }
4824 // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4825 }
4826 Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4827 const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4828 assert(arytype->is_null_free() == null_free, "inconsistency");
4829 assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4830 assert(arytype->is_atomic() == atomic, "inconsistency");
4831 set_result(obj);
4832 return true;
4833 }
4834 }
4835 }
4836 }
4837 return false;
4838 }
4839
4840 // public static native boolean ValueClass::isFlatArray(Object array);
4841 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4842 // public static native boolean ValueClass::isAtomicArray(Object array);
4843 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4844 Node* array = argument(0);
4845
4846 Node* bol;
4847 switch(check) {
4848 case IsFlat:
4849 // TODO 8350865 Use the object version here instead of loading the klass
4850 // The problem is that PhaseMacroExpand::expand_flatarraycheck_node can only handle some IR shapes and will fail, for example, if the bol is directly wired to a ReturnNode
4851 bol = flat_array_test(load_object_klass(array));
4852 break;
4853 case IsNullRestricted:
4854 bol = null_free_array_test(array);
4855 break;
4856 case IsAtomic:
4857 // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4858 // Enable TestIntrinsics::test87/88 once this is implemented
4859 // bol = null_free_atomic_array_test
4860 return false;
4861 default:
4862 ShouldNotReachHere();
4863 }
4864
4865 Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4866 set_result(res);
4867 return true;
4868 }
4869
4870 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4871 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4872 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4873 RegionNode* region = new RegionNode(2);
4874 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4875
4876 if (type_array_guard) {
4877 generate_typeArray_guard(klass_node, region);
4878 if (region->req() == 3) {
4879 phi->add_req(klass_node);
4880 }
4881 }
4882 Node* adr_refined_klass = basic_plus_adr(klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4883 Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4884
4885 // Can be null if not initialized yet, just deopt
4886 Node* null_ctl = top();
4887 refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4888
4889 region->init_req(1, control());
4890 phi->init_req(1, refined_klass);
4891
4892 set_control(_gvn.transform(region));
4893 return _gvn.transform(phi);
4894 }
4895
4896 //-----------------------inline_native_newArray--------------------------
4897 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4898 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4899 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4900 Node* mirror;
4901 Node* count_val;
4902 if (uninitialized) {
4903 null_check_receiver();
4904 mirror = argument(1);
4905 count_val = argument(2);
4906 } else {
4907 mirror = argument(0);
4908 count_val = argument(1);
4909 }
4910
4911 mirror = null_check(mirror);
4912 // If mirror or obj is dead, only null-path is taken.
4913 if (stopped()) return true;
4914
4915 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4916 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4917 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4935 CallJavaNode* slow_call = nullptr;
4936 if (uninitialized) {
4937 // Generate optimized virtual call (holder class 'Unsafe' is final)
4938 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4939 } else {
4940 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4941 }
4942 Node* slow_result = set_results_for_java_call(slow_call);
4943 // this->control() comes from set_results_for_java_call
4944 result_reg->set_req(_slow_path, control());
4945 result_val->set_req(_slow_path, slow_result);
4946 result_io ->set_req(_slow_path, i_o());
4947 result_mem->set_req(_slow_path, reset_memory());
4948 }
4949
4950 set_control(normal_ctl);
4951 if (!stopped()) {
4952 // Normal case: The array type has been cached in the java.lang.Class.
4953 // The following call works fine even if the array type is polymorphic.
4954 // It could be a dynamic mix of int[], boolean[], Object[], etc.
4955
4956 klass_node = load_default_refined_array_klass(klass_node);
4957
4958 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
4959 result_reg->init_req(_normal_path, control());
4960 result_val->init_req(_normal_path, obj);
4961 result_io ->init_req(_normal_path, i_o());
4962 result_mem->init_req(_normal_path, reset_memory());
4963
4964 if (uninitialized) {
4965 // Mark the allocation so that zeroing is skipped
4966 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4967 alloc->maybe_set_complete(&_gvn);
4968 }
4969 }
4970
4971 // Return the combined state.
4972 set_i_o( _gvn.transform(result_io) );
4973 set_all_memory( _gvn.transform(result_mem));
4974
4975 C->set_has_split_ifs(true); // Has chance for split-if optimization
4976 set_result(result_reg, result_val);
4977 return true;
5026 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5027 { PreserveReexecuteState preexecs(this);
5028 jvms()->set_should_reexecute(true);
5029
5030 array_type_mirror = null_check(array_type_mirror);
5031 original = null_check(original);
5032
5033 // Check if a null path was taken unconditionally.
5034 if (stopped()) return true;
5035
5036 Node* orig_length = load_array_length(original);
5037
5038 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5039 klass_node = null_check(klass_node);
5040
5041 RegionNode* bailout = new RegionNode(1);
5042 record_for_igvn(bailout);
5043
5044 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5045 // Bail out if that is so.
5046 // Inline type array may have object field that would require a
5047 // write barrier. Conservatively, go to slow path.
5048 // TODO 8251971: Optimize for the case when flat src/dst are later found
5049 // to not contain oops (i.e., move this check to the macro expansion phase).
5050 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5051 const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5052 const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5053 bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5054 // Can src array be flat and contain oops?
5055 (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5056 // Can dest array be flat and contain oops?
5057 tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5058 Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5059
5060 klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5061
5062 if (not_objArray != nullptr) {
5063 // Improve the klass node's type from the new optimistic assumption:
5064 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5065 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0));
5066 Node* cast = new CastPPNode(control(), klass_node, akls);
5067 klass_node = _gvn.transform(cast);
5068 }
5069
5070 // Bail out if either start or end is negative.
5071 generate_negative_guard(start, bailout, &start);
5072 generate_negative_guard(end, bailout, &end);
5073
5074 Node* length = end;
5075 if (_gvn.type(start) != TypeInt::ZERO) {
5076 length = _gvn.transform(new SubINode(end, start));
5077 }
5078
5079 // Bail out if length is negative (i.e., if start > end).
5080 // Without this the new_array would throw
5081 // NegativeArraySizeException but IllegalArgumentException is what
5082 // should be thrown
5083 generate_negative_guard(length, bailout, &length);
5084
5085 // Handle inline type arrays
5086 bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5087 if (!stopped()) {
5088 // TODO JDK-8329224
5089 if (!orig_t->is_null_free()) {
5090 // Not statically known to be null free, add a check
5091 generate_fair_guard(null_free_array_test(original), bailout);
5092 }
5093 orig_t = _gvn.type(original)->isa_aryptr();
5094 if (orig_t != nullptr && orig_t->is_flat()) {
5095 // Src is flat, check that dest is flat as well
5096 if (exclude_flat) {
5097 // Dest can't be flat, bail out
5098 bailout->add_req(control());
5099 set_control(top());
5100 } else {
5101 generate_fair_guard(flat_array_test(klass_node, /* flat = */ false), bailout);
5102 }
5103 // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5104 } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5105 // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5106 ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5107 // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5108 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5109 generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5110 if (orig_t != nullptr) {
5111 orig_t = orig_t->cast_to_not_flat();
5112 original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5113 }
5114 }
5115 if (!can_validate) {
5116 // No validation. The subtype check emitted at macro expansion time will not go to the slow
5117 // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5118 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5119 generate_fair_guard(flat_array_test(klass_node), bailout);
5120 generate_fair_guard(null_free_array_test(original), bailout);
5121 }
5122 }
5123
5124 // Bail out if start is larger than the original length
5125 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5126 generate_negative_guard(orig_tail, bailout, &orig_tail);
5127
5128 if (bailout->req() > 1) {
5129 PreserveJVMState pjvms(this);
5130 set_control(_gvn.transform(bailout));
5131 uncommon_trap(Deoptimization::Reason_intrinsic,
5132 Deoptimization::Action_maybe_recompile);
5133 }
5134
5135 if (!stopped()) {
5136 // How many elements will we copy from the original?
5137 // The answer is MinI(orig_tail, length).
5138 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5139
5140 // Generate a direct call to the right arraycopy function(s).
5141 // We know the copy is disjoint but we might not know if the
5142 // oop stores need checking.
5143 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
5149 // to the copyOf to be validated, including that the copy to the
5150 // new array won't trigger an ArrayStoreException. That subtype
5151 // check can be optimized if we know something on the type of
5152 // the input array from type speculation.
5153 if (_gvn.type(klass_node)->singleton()) {
5154 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5155 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5156
5157 int test = C->static_subtype_check(superk, subk);
5158 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5159 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5160 if (t_original->speculative_type() != nullptr) {
5161 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5162 }
5163 }
5164 }
5165
5166 bool validated = false;
5167 // Reason_class_check rather than Reason_intrinsic because we
5168 // want to intrinsify even if this traps.
5169 if (can_validate) {
5170 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5171
5172 if (not_subtype_ctrl != top()) {
5173 PreserveJVMState pjvms(this);
5174 set_control(not_subtype_ctrl);
5175 uncommon_trap(Deoptimization::Reason_class_check,
5176 Deoptimization::Action_make_not_entrant);
5177 assert(stopped(), "Should be stopped");
5178 }
5179 validated = true;
5180 }
5181
5182 if (!stopped()) {
5183 newcopy = new_array(klass_node, length, 0); // no arguments to push
5184
5185 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5186 load_object_klass(original), klass_node);
5187 if (!is_copyOfRange) {
5188 ac->set_copyof(validated);
5189 } else {
5235
5236 //-----------------------generate_method_call----------------------------
5237 // Use generate_method_call to make a slow-call to the real
5238 // method if the fast path fails. An alternative would be to
5239 // use a stub like OptoRuntime::slow_arraycopy_Java.
5240 // This only works for expanding the current library call,
5241 // not another intrinsic. (E.g., don't use this for making an
5242 // arraycopy call inside of the copyOf intrinsic.)
5243 CallJavaNode*
5244 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5245 // When compiling the intrinsic method itself, do not use this technique.
5246 guarantee(callee() != C->method(), "cannot make slow-call to self");
5247
5248 ciMethod* method = callee();
5249 // ensure the JVMS we have will be correct for this call
5250 guarantee(method_id == method->intrinsic_id(), "must match");
5251
5252 const TypeFunc* tf = TypeFunc::make(method);
5253 if (res_not_null) {
5254 assert(tf->return_type() == T_OBJECT, "");
5255 const TypeTuple* range = tf->range_cc();
5256 const Type** fields = TypeTuple::fields(range->cnt());
5257 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5258 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5259 tf = TypeFunc::make(tf->domain_cc(), new_range);
5260 }
5261 CallJavaNode* slow_call;
5262 if (is_static) {
5263 assert(!is_virtual, "");
5264 slow_call = new CallStaticJavaNode(C, tf,
5265 SharedRuntime::get_resolve_static_call_stub(), method);
5266 } else if (is_virtual) {
5267 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5268 int vtable_index = Method::invalid_vtable_index;
5269 if (UseInlineCaches) {
5270 // Suppress the vtable call
5271 } else {
5272 // hashCode and clone are not a miranda methods,
5273 // so the vtable index is fixed.
5274 // No need to use the linkResolver to get it.
5275 vtable_index = method->vtable_index();
5276 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5277 "bad index %d", vtable_index);
5278 }
5279 slow_call = new CallDynamicJavaNode(tf,
5296 set_edges_for_java_call(slow_call);
5297 return slow_call;
5298 }
5299
5300
5301 /**
5302 * Build special case code for calls to hashCode on an object. This call may
5303 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5304 * slightly different code.
5305 */
5306 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5307 assert(is_static == callee()->is_static(), "correct intrinsic selection");
5308 assert(!(is_virtual && is_static), "either virtual, special, or static");
5309
5310 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5311
5312 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5313 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
5314 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
5315 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5316 Node* obj = argument(0);
5317
5318 // Don't intrinsify hashcode on inline types for now.
5319 // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5320 if (gvn().type(obj)->is_inlinetypeptr()) {
5321 return false;
5322 }
5323
5324 if (!is_static) {
5325 // Check for hashing null object
5326 obj = null_check_receiver();
5327 if (stopped()) return true; // unconditionally null
5328 result_reg->init_req(_null_path, top());
5329 result_val->init_req(_null_path, top());
5330 } else {
5331 // Do a null check, and return zero if null.
5332 // System.identityHashCode(null) == 0
5333 Node* null_ctl = top();
5334 obj = null_check_oop(obj, &null_ctl);
5335 result_reg->init_req(_null_path, null_ctl);
5336 result_val->init_req(_null_path, _gvn.intcon(0));
5337 }
5338
5339 // Unconditionally null? Then return right away.
5340 if (stopped()) {
5341 set_control( result_reg->in(_null_path));
5342 if (!stopped())
5343 set_result(result_val->in(_null_path));
5344 return true;
5345 }
5346
5347 // We only go to the fast case code if we pass a number of guards. The
5348 // paths which do not pass are accumulated in the slow_region.
5349 RegionNode* slow_region = new RegionNode(1);
5350 record_for_igvn(slow_region);
5351
5352 // If this is a virtual call, we generate a funny guard. We pull out
5353 // the vtable entry corresponding to hashCode() from the target object.
5354 // If the target method which we are calling happens to be the native
5355 // Object hashCode() method, we pass the guard. We do not need this
5356 // guard for non-virtual calls -- the caller is known to be the native
5357 // Object hashCode().
5358 if (is_virtual) {
5359 // After null check, get the object's klass.
5360 Node* obj_klass = load_object_klass(obj);
5361 generate_virtual_guard(obj_klass, slow_region);
5362 }
5363
5364 // Get the header out of the object, use LoadMarkNode when available
5365 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5366 // The control of the load must be null. Otherwise, the load can move before
5367 // the null check after castPP removal.
5368 Node* no_ctrl = nullptr;
5369 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5370
5371 if (!UseObjectMonitorTable) {
5372 // Test the header to see if it is safe to read w.r.t. locking.
5373 // We cannot use the inline type mask as this may check bits that are overriden
5374 // by an object monitor's pointer when inflating locking.
5375 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
5376 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5377 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
5378 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5379 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5380
5381 generate_slow_guard(test_monitor, slow_region);
5382 }
5383
5384 // Get the hash value and check to see that it has been properly assigned.
5385 // We depend on hash_mask being at most 32 bits and avoid the use of
5386 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5387 // vm: see markWord.hpp.
5388 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
5389 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
5390 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5391 // This hack lets the hash bits live anywhere in the mark object now, as long
5392 // as the shift drops the relevant bits into the low 32 bits. Note that
5393 // Java spec says that HashCode is an int so there's no point in capturing
5394 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5422 // this->control() comes from set_results_for_java_call
5423 result_reg->init_req(_slow_path, control());
5424 result_val->init_req(_slow_path, slow_result);
5425 result_io ->set_req(_slow_path, i_o());
5426 result_mem ->set_req(_slow_path, reset_memory());
5427 }
5428
5429 // Return the combined state.
5430 set_i_o( _gvn.transform(result_io) );
5431 set_all_memory( _gvn.transform(result_mem));
5432
5433 set_result(result_reg, result_val);
5434 return true;
5435 }
5436
5437 //---------------------------inline_native_getClass----------------------------
5438 // public final native Class<?> java.lang.Object.getClass();
5439 //
5440 // Build special case code for calls to getClass on an object.
5441 bool LibraryCallKit::inline_native_getClass() {
5442 Node* obj = argument(0);
5443 if (obj->is_InlineType()) {
5444 const Type* t = _gvn.type(obj);
5445 if (t->maybe_null()) {
5446 null_check(obj);
5447 }
5448 set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5449 return true;
5450 }
5451 obj = null_check_receiver();
5452 if (stopped()) return true;
5453 set_result(load_mirror_from_klass(load_object_klass(obj)));
5454 return true;
5455 }
5456
5457 //-----------------inline_native_Reflection_getCallerClass---------------------
5458 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5459 //
5460 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5461 //
5462 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5463 // in that it must skip particular security frames and checks for
5464 // caller sensitive methods.
5465 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5466 #ifndef PRODUCT
5467 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5468 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5469 }
5470 #endif
5471
5853 // not cloneable or finalizer => slow path to out-of-line Object.clone
5854 //
5855 // The general case has two steps, allocation and copying.
5856 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5857 //
5858 // Copying also has two cases, oop arrays and everything else.
5859 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5860 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5861 //
5862 // These steps fold up nicely if and when the cloned object's klass
5863 // can be sharply typed as an object array, a type array, or an instance.
5864 //
5865 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5866 PhiNode* result_val;
5867
5868 // Set the reexecute bit for the interpreter to reexecute
5869 // the bytecode that invokes Object.clone if deoptimization happens.
5870 { PreserveReexecuteState preexecs(this);
5871 jvms()->set_should_reexecute(true);
5872
5873 Node* obj = argument(0);
5874 obj = null_check_receiver();
5875 if (stopped()) return true;
5876
5877 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5878 if (obj_type->is_inlinetypeptr()) {
5879 // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5880 // no identity.
5881 set_result(obj);
5882 return true;
5883 }
5884
5885 // If we are going to clone an instance, we need its exact type to
5886 // know the number and types of fields to convert the clone to
5887 // loads/stores. Maybe a speculative type can help us.
5888 if (!obj_type->klass_is_exact() &&
5889 obj_type->speculative_type() != nullptr &&
5890 obj_type->speculative_type()->is_instance_klass() &&
5891 !obj_type->speculative_type()->is_inlinetype()) {
5892 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5893 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5894 !spec_ik->has_injected_fields()) {
5895 if (!obj_type->isa_instptr() ||
5896 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5897 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5898 }
5899 }
5900 }
5901
5902 // Conservatively insert a memory barrier on all memory slices.
5903 // Do not let writes into the original float below the clone.
5904 insert_mem_bar(Op_MemBarCPUOrder);
5905
5906 // paths into result_reg:
5907 enum {
5908 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5909 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5910 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5911 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5912 PATH_LIMIT
5913 };
5914 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5915 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5916 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5917 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5918 record_for_igvn(result_reg);
5919
5920 Node* obj_klass = load_object_klass(obj);
5921 // We only go to the fast case code if we pass a number of guards.
5922 // The paths which do not pass are accumulated in the slow_region.
5923 RegionNode* slow_region = new RegionNode(1);
5924 record_for_igvn(slow_region);
5925
5926 Node* array_obj = obj;
5927 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5928 if (array_ctl != nullptr) {
5929 // It's an array.
5930 PreserveJVMState pjvms(this);
5931 set_control(array_ctl);
5932
5933 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5934 const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5935 if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5936 obj_type->can_be_inline_array() &&
5937 (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5938 // Flat inline type array may have object field that would require a
5939 // write barrier. Conservatively, go to slow path.
5940 generate_fair_guard(flat_array_test(obj_klass), slow_region);
5941 }
5942
5943 if (!stopped()) {
5944 Node* obj_length = load_array_length(array_obj);
5945 Node* array_size = nullptr; // Size of the array without object alignment padding.
5946 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5947
5948 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5949 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5950 // If it is an oop array, it requires very special treatment,
5951 // because gc barriers are required when accessing the array.
5952 Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
5953 if (is_obja != nullptr) {
5954 PreserveJVMState pjvms2(this);
5955 set_control(is_obja);
5956 // Generate a direct call to the right arraycopy function(s).
5957 // Clones are always tightly coupled.
5958 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5959 ac->set_clone_oop_array();
5960 Node* n = _gvn.transform(ac);
5961 assert(n == ac, "cannot disappear");
5962 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5963
5964 result_reg->init_req(_objArray_path, control());
5965 result_val->init_req(_objArray_path, alloc_obj);
5966 result_i_o ->set_req(_objArray_path, i_o());
5967 result_mem ->set_req(_objArray_path, reset_memory());
5968 }
5969 }
5970 // Otherwise, there are no barriers to worry about.
5971 // (We can dispense with card marks if we know the allocation
5972 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5973 // causes the non-eden paths to take compensating steps to
5974 // simulate a fresh allocation, so that no further
5975 // card marks are required in compiled code to initialize
5976 // the object.)
5977
5978 if (!stopped()) {
5979 copy_to_clone(obj, alloc_obj, array_size, true);
5980
5981 // Present the results of the copy.
5982 result_reg->init_req(_array_path, control());
5983 result_val->init_req(_array_path, alloc_obj);
5984 result_i_o ->set_req(_array_path, i_o());
5985 result_mem ->set_req(_array_path, reset_memory());
5986 }
5987 }
5988 }
5989
5990 if (!stopped()) {
5991 // It's an instance (we did array above). Make the slow-path tests.
5992 // If this is a virtual call, we generate a funny guard. We grab
5993 // the vtable entry corresponding to clone() from the target object.
5994 // If the target method which we are calling happens to be the
5995 // Object clone() method, we pass the guard. We do not need this
5996 // guard for non-virtual calls; the caller is known to be the native
5997 // Object clone().
5998 if (is_virtual) {
5999 generate_virtual_guard(obj_klass, slow_region);
6000 }
6001
6002 // The object must be easily cloneable and must not have a finalizer.
6003 // Both of these conditions may be checked in a single test.
6004 // We could optimize the test further, but we don't care.
6005 generate_misc_flags_guard(obj_klass,
6006 // Test both conditions:
6007 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6008 // Must be cloneable but not finalizer:
6009 KlassFlags::_misc_is_cloneable_fast,
6101 set_jvms(sfpt->jvms());
6102 _reexecute_sp = jvms()->sp();
6103
6104 return saved_jvms;
6105 }
6106 }
6107 }
6108 return nullptr;
6109 }
6110
6111 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6112 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6113 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6114 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6115 uint size = alloc->req();
6116 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6117 old_jvms->set_map(sfpt);
6118 for (uint i = 0; i < size; i++) {
6119 sfpt->init_req(i, alloc->in(i));
6120 }
6121 int adjustment = 1;
6122 const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6123 if (ary_klass_ptr->is_null_free()) {
6124 // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6125 // also requires the componentType and initVal on stack for re-execution.
6126 // Re-create and push the componentType.
6127 ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6128 ciInstance* instance = klass->component_mirror_instance();
6129 const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6130 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6131 adjustment++;
6132 }
6133 // re-push array length for deoptimization
6134 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6135 if (ary_klass_ptr->is_null_free()) {
6136 // Re-create and push the initVal.
6137 Node* init_val = alloc->in(AllocateNode::InitValue);
6138 if (init_val == nullptr) {
6139 init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6140 } else if (UseCompressedOops) {
6141 init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6142 }
6143 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6144 adjustment++;
6145 }
6146 old_jvms->set_sp(old_jvms->sp() + adjustment);
6147 old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6148 old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6149 old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6150 old_jvms->set_should_reexecute(true);
6151
6152 sfpt->set_i_o(map()->i_o());
6153 sfpt->set_memory(map()->memory());
6154 sfpt->set_control(map()->control());
6155 return sfpt;
6156 }
6157
6158 // In case of a deoptimization, we restart execution at the
6159 // allocation, allocating a new array. We would leave an uninitialized
6160 // array in the heap that GCs wouldn't expect. Move the allocation
6161 // after the traps so we don't allocate the array if we
6162 // deoptimize. This is possible because tightly_coupled_allocation()
6163 // guarantees there's no observer of the allocated array at this point
6164 // and the control flow is simple enough.
6165 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6166 int saved_reexecute_sp, uint new_idx) {
6167 if (saved_jvms_before_guards != nullptr && !stopped()) {
6168 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6169
6170 assert(alloc != nullptr, "only with a tightly coupled allocation");
6171 // restore JVM state to the state at the arraycopy
6172 saved_jvms_before_guards->map()->set_control(map()->control());
6173 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6174 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6175 // If we've improved the types of some nodes (null check) while
6176 // emitting the guards, propagate them to the current state
6177 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6178 set_jvms(saved_jvms_before_guards);
6179 _reexecute_sp = saved_reexecute_sp;
6180
6181 // Remove the allocation from above the guards
6182 CallProjections* callprojs = alloc->extract_projections(true);
6183 InitializeNode* init = alloc->initialization();
6184 Node* alloc_mem = alloc->in(TypeFunc::Memory);
6185 C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6186 C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
6187
6188 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6189 // the allocation (i.e. is only valid if the allocation succeeds):
6190 // 1) replace CastIINode with AllocateArrayNode's length here
6191 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6192 //
6193 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6194 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6195 Node* init_control = init->proj_out(TypeFunc::Control);
6196 Node* alloc_length = alloc->Ideal_length();
6197 #ifdef ASSERT
6198 Node* prev_cast = nullptr;
6199 #endif
6200 for (uint i = 0; i < init_control->outcnt(); i++) {
6201 Node* init_out = init_control->raw_out(i);
6202 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6203 #ifdef ASSERT
6204 if (prev_cast == nullptr) {
6205 prev_cast = init_out;
6207 if (prev_cast->cmp(*init_out) == false) {
6208 prev_cast->dump();
6209 init_out->dump();
6210 assert(false, "not equal CastIINode");
6211 }
6212 }
6213 #endif
6214 C->gvn_replace_by(init_out, alloc_length);
6215 }
6216 }
6217 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6218
6219 // move the allocation here (after the guards)
6220 _gvn.hash_delete(alloc);
6221 alloc->set_req(TypeFunc::Control, control());
6222 alloc->set_req(TypeFunc::I_O, i_o());
6223 Node *mem = reset_memory();
6224 set_all_memory(mem);
6225 alloc->set_req(TypeFunc::Memory, mem);
6226 set_control(init->proj_out_or_null(TypeFunc::Control));
6227 set_i_o(callprojs->fallthrough_ioproj);
6228
6229 // Update memory as done in GraphKit::set_output_for_allocation()
6230 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6231 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6232 if (ary_type->isa_aryptr() && length_type != nullptr) {
6233 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6234 }
6235 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6236 int elemidx = C->get_alias_index(telemref);
6237 set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
6238 set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
6239
6240 Node* allocx = _gvn.transform(alloc);
6241 assert(allocx == alloc, "where has the allocation gone?");
6242 assert(dest->is_CheckCastPP(), "not an allocation result?");
6243
6244 _gvn.hash_delete(dest);
6245 dest->set_req(0, control());
6246 Node* destx = _gvn.transform(dest);
6247 assert(destx == dest, "where has the allocation result gone?");
6545 top_src = src_type->isa_aryptr();
6546 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6547 src_spec = true;
6548 }
6549 if (!has_dest) {
6550 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6551 dest_type = _gvn.type(dest);
6552 top_dest = dest_type->isa_aryptr();
6553 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6554 dest_spec = true;
6555 }
6556 }
6557 }
6558
6559 if (has_src && has_dest && can_emit_guards) {
6560 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6561 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6562 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6563 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6564
6565 if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6566 // If both arrays are object arrays then having the exact types
6567 // for both will remove the need for a subtype check at runtime
6568 // before the call and may make it possible to pick a faster copy
6569 // routine (without a subtype check on every element)
6570 // Do we have the exact type of src?
6571 bool could_have_src = src_spec;
6572 // Do we have the exact type of dest?
6573 bool could_have_dest = dest_spec;
6574 ciKlass* src_k = nullptr;
6575 ciKlass* dest_k = nullptr;
6576 if (!src_spec) {
6577 src_k = src_type->speculative_type_not_null();
6578 if (src_k != nullptr && src_k->is_array_klass()) {
6579 could_have_src = true;
6580 }
6581 }
6582 if (!dest_spec) {
6583 dest_k = dest_type->speculative_type_not_null();
6584 if (dest_k != nullptr && dest_k->is_array_klass()) {
6585 could_have_dest = true;
6586 }
6587 }
6588 if (could_have_src && could_have_dest) {
6589 // If we can have both exact types, emit the missing guards
6590 if (could_have_src && !src_spec) {
6591 src = maybe_cast_profiled_obj(src, src_k, true);
6592 src_type = _gvn.type(src);
6593 top_src = src_type->isa_aryptr();
6594 }
6595 if (could_have_dest && !dest_spec) {
6596 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6597 dest_type = _gvn.type(dest);
6598 top_dest = dest_type->isa_aryptr();
6599 }
6600 }
6601 }
6602 }
6603
6604 ciMethod* trap_method = method();
6605 int trap_bci = bci();
6606 if (saved_jvms_before_guards != nullptr) {
6607 trap_method = alloc->jvms()->method();
6608 trap_bci = alloc->jvms()->bci();
6609 }
6610
6611 bool negative_length_guard_generated = false;
6612
6613 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6614 can_emit_guards && !src->is_top() && !dest->is_top()) {
6615 // validate arguments: enables transformation the ArrayCopyNode
6616 validated = true;
6617
6618 RegionNode* slow_region = new RegionNode(1);
6619 record_for_igvn(slow_region);
6620
6621 // (1) src and dest are arrays.
6622 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6623 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6624
6625 // (2) src and dest arrays must have elements of the same BasicType
6626 // done at macro expansion or at Ideal transformation time
6627
6628 // (4) src_offset must not be negative.
6629 generate_negative_guard(src_offset, slow_region);
6630
6631 // (5) dest_offset must not be negative.
6632 generate_negative_guard(dest_offset, slow_region);
6633
6634 // (7) src_offset + length must not exceed length of src.
6637 slow_region);
6638
6639 // (8) dest_offset + length must not exceed length of dest.
6640 generate_limit_guard(dest_offset, length,
6641 load_array_length(dest),
6642 slow_region);
6643
6644 // (6) length must not be negative.
6645 // This is also checked in generate_arraycopy() during macro expansion, but
6646 // we also have to check it here for the case where the ArrayCopyNode will
6647 // be eliminated by Escape Analysis.
6648 if (EliminateAllocations) {
6649 generate_negative_guard(length, slow_region);
6650 negative_length_guard_generated = true;
6651 }
6652
6653 // (9) each element of an oop array must be assignable
6654 Node* dest_klass = load_object_klass(dest);
6655 if (src != dest) {
6656 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6657 slow_region->add_req(not_subtype_ctrl);
6658 }
6659
6660 // TODO 8350865 Fix below logic. Also handle atomicity.
6661 generate_fair_guard(flat_array_test(src), slow_region);
6662 generate_fair_guard(flat_array_test(dest), slow_region);
6663
6664 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6665 const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6666 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6667 src_type = _gvn.type(src);
6668 top_src = src_type->isa_aryptr();
6669
6670 // Handle flat inline type arrays (null-free arrays are handled by the subtype check above)
6671 if (!stopped() && UseArrayFlattening) {
6672 // If dest is flat, src must be flat as well (guaranteed by src <: dest check). Handle flat src here.
6673 assert(top_dest == nullptr || !top_dest->is_flat() || top_src->is_flat(), "src array must be flat");
6674 if (top_src != nullptr && top_src->is_flat()) {
6675 // Src is flat, check that dest is flat as well
6676 if (top_dest != nullptr && !top_dest->is_flat()) {
6677 generate_fair_guard(flat_array_test(dest_klass, /* flat = */ false), slow_region);
6678 // Since dest is flat and src <: dest, dest must have the same type as src.
6679 top_dest = top_src->cast_to_exactness(false);
6680 assert(top_dest->is_flat(), "dest must be flat");
6681 dest = _gvn.transform(new CheckCastPPNode(control(), dest, top_dest));
6682 }
6683 } else if (top_src == nullptr || !top_src->is_not_flat()) {
6684 // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
6685 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
6686 assert(top_dest == nullptr || !top_dest->is_flat(), "dest array must not be flat");
6687 generate_fair_guard(flat_array_test(src), slow_region);
6688 if (top_src != nullptr) {
6689 top_src = top_src->cast_to_not_flat();
6690 src = _gvn.transform(new CheckCastPPNode(control(), src, top_src));
6691 }
6692 }
6693 }
6694
6695 {
6696 PreserveJVMState pjvms(this);
6697 set_control(_gvn.transform(slow_region));
6698 uncommon_trap(Deoptimization::Reason_intrinsic,
6699 Deoptimization::Action_make_not_entrant);
6700 assert(stopped(), "Should be stopped");
6701 }
6702 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6703 }
6704
6705 if (stopped()) {
6706 return true;
6707 }
6708
6709 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6710 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6711 // so the compiler has a chance to eliminate them: during macro expansion,
6712 // we have to set their control (CastPP nodes are eliminated).
6713 load_object_klass(src), load_object_klass(dest),
6714 load_array_length(src), load_array_length(dest));
6715
6716 ac->set_arraycopy(validated);
6717
6718 Node* n = _gvn.transform(ac);
6719 if (n == ac) {
6720 ac->connect_outputs(this);
6721 } else {
|