33 #include "code/scopeDesc.hpp"
34 #include "compiler/compilationPolicy.hpp"
35 #include "compiler/compilerDefinitions.inline.hpp"
36 #include "gc/shared/collectedHeap.hpp"
37 #include "gc/shared/memAllocator.hpp"
38 #include "interpreter/bytecode.hpp"
39 #include "interpreter/bytecode.inline.hpp"
40 #include "interpreter/bytecodeStream.hpp"
41 #include "interpreter/interpreter.hpp"
42 #include "interpreter/oopMapCache.hpp"
43 #include "jvm.h"
44 #include "logging/log.hpp"
45 #include "logging/logLevel.hpp"
46 #include "logging/logMessage.hpp"
47 #include "logging/logStream.hpp"
48 #include "memory/allocation.inline.hpp"
49 #include "memory/oopFactory.hpp"
50 #include "memory/resourceArea.hpp"
51 #include "memory/universe.hpp"
52 #include "oops/constantPool.hpp"
53 #include "oops/fieldStreams.inline.hpp"
54 #include "oops/method.hpp"
55 #include "oops/objArrayKlass.hpp"
56 #include "oops/objArrayOop.inline.hpp"
57 #include "oops/oop.inline.hpp"
58 #include "oops/typeArrayOop.inline.hpp"
59 #include "oops/verifyOopClosure.hpp"
60 #include "prims/jvmtiDeferredUpdates.hpp"
61 #include "prims/jvmtiExport.hpp"
62 #include "prims/jvmtiThreadState.hpp"
63 #include "prims/methodHandles.hpp"
64 #include "prims/vectorSupport.hpp"
65 #include "runtime/atomic.hpp"
66 #include "runtime/basicLock.inline.hpp"
67 #include "runtime/continuation.hpp"
68 #include "runtime/continuationEntry.inline.hpp"
69 #include "runtime/deoptimization.hpp"
70 #include "runtime/escapeBarrier.hpp"
71 #include "runtime/fieldDescriptor.hpp"
72 #include "runtime/fieldDescriptor.inline.hpp"
73 #include "runtime/frame.inline.hpp"
74 #include "runtime/handles.inline.hpp"
75 #include "runtime/interfaceSupport.inline.hpp"
76 #include "runtime/javaThread.hpp"
77 #include "runtime/jniHandles.inline.hpp"
283 // The actual reallocation of previously eliminated objects occurs in realloc_objects,
284 // which is called from the method fetch_unroll_info_helper below.
285 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* current, int exec_mode))
286 // fetch_unroll_info() is called at the beginning of the deoptimization
287 // handler. Note this fact before we start generating temporary frames
288 // that can confuse an asynchronous stack walker. This counter is
289 // decremented at the end of unpack_frames().
290 current->inc_in_deopt_handler();
291
292 if (exec_mode == Unpack_exception) {
293 // When we get here, a callee has thrown an exception into a deoptimized
294 // frame. That throw might have deferred stack watermark checking until
295 // after unwinding. So we deal with such deferred requests here.
296 StackWatermarkSet::after_unwind(current);
297 }
298
299 return fetch_unroll_info_helper(current, exec_mode);
300 JRT_END
301
302 #if COMPILER2_OR_JVMCI
303 // print information about reallocated objects
304 static void print_objects(JavaThread* deoptee_thread,
305 GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
306 ResourceMark rm;
307 stringStream st; // change to logStream with logging
308 st.print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(deoptee_thread));
309 fieldDescriptor fd;
310
311 for (int i = 0; i < objects->length(); i++) {
312 ObjectValue* sv = (ObjectValue*) objects->at(i);
313 Handle obj = sv->value();
314
315 if (obj.is_null()) {
316 st.print_cr(" nullptr");
317 continue;
318 }
319
320 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
321
322 st.print(" object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));
323 k->print_value_on(&st);
324 st.print_cr(" allocated (%zu bytes)", obj->size() * HeapWordSize);
325
326 if (Verbose && k != nullptr) {
327 k->oop_print_on(obj(), &st);
328 }
329 }
330 tty->print_raw(st.freeze());
331 }
332
333 static bool rematerialize_objects(JavaThread* thread, int exec_mode, nmethod* compiled_method,
334 frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk,
335 bool& deoptimized_objects) {
336 bool realloc_failures = false;
337 assert (chunk->at(0)->scope() != nullptr,"expect only compiled java frames");
338
339 JavaThread* deoptee_thread = chunk->at(0)->thread();
340 assert(exec_mode == Deoptimization::Unpack_none || (deoptee_thread == thread),
341 "a frame can only be deoptimized by the owner thread");
342
343 GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects_to_rematerialize(deoptee, map);
344
345 // The flag return_oop() indicates call sites which return oop
346 // in compiled code. Such sites include java method calls,
347 // runtime calls (for example, used to allocate new objects/arrays
348 // on slow code path) and any other calls generated in compiled code.
349 // It is not guaranteed that we can get such information here only
350 // by analyzing bytecode in deoptimized frames. This is why this flag
351 // is set during method compilation (see Compile::Process_OopMap_Node()).
352 // If the previous frame was popped or if we are dispatching an exception,
353 // we don't have an oop result.
354 bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt);
355 Handle return_value;
356 if (save_oop_result) {
357 // Reallocation may trigger GC. If deoptimization happened on return from
358 // call which returns oop we need to save it since it is not in oopmap.
359 oop result = deoptee.saved_oop_result(&map);
360 assert(oopDesc::is_oop_or_null(result), "must be oop");
361 return_value = Handle(thread, result);
362 assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
363 if (TraceDeoptimization) {
364 tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread));
365 tty->cr();
366 }
367 }
368 if (objects != nullptr) {
369 if (exec_mode == Deoptimization::Unpack_none) {
370 assert(thread->thread_state() == _thread_in_vm, "assumption");
371 JavaThread* THREAD = thread; // For exception macros.
372 // Clear pending OOM if reallocation fails and return true indicating allocation failure
373 realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, CHECK_AND_CLEAR_(true));
374 deoptimized_objects = true;
375 } else {
376 JavaThread* current = thread; // For JRT_BLOCK
377 JRT_BLOCK
378 realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD);
379 JRT_END
380 }
381 guarantee(compiled_method != nullptr, "deopt must be associated with an nmethod");
382 bool is_jvmci = compiled_method->is_compiled_by_jvmci();
383 Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, is_jvmci);
384 if (TraceDeoptimization) {
385 print_objects(deoptee_thread, objects, realloc_failures);
386 }
387 }
388 if (save_oop_result) {
389 // Restore result.
390 deoptee.set_saved_oop_result(&map, return_value());
391 }
392 return realloc_failures;
393 }
394
395 static void restore_eliminated_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures,
396 frame& deoptee, int exec_mode, bool& deoptimized_objects) {
397 JavaThread* deoptee_thread = chunk->at(0)->thread();
398 assert(!EscapeBarrier::objs_are_deoptimized(deoptee_thread, deoptee.id()), "must relock just once");
399 assert(thread == Thread::current(), "should be");
400 HandleMark hm(thread);
401 #ifndef PRODUCT
402 bool first = true;
403 #endif // !PRODUCT
404 // Start locking from outermost/oldest frame
405 for (int i = (chunk->length() - 1); i >= 0; i--) {
406 compiledVFrame* cvf = chunk->at(i);
407 assert (cvf->scope() != nullptr,"expect only compiled java frames");
408 GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
409 if (monitors->is_nonempty()) {
410 bool relocked = Deoptimization::relock_objects(thread, monitors, deoptee_thread, deoptee,
705 // its caller's stack by. If the caller is a compiled frame then
706 // we pretend that the callee has no parameters so that the
707 // extension counts for the full amount of locals and not just
708 // locals-parms. This is because without a c2i adapter the parm
709 // area as created by the compiled frame will not be usable by
710 // the interpreter. (Depending on the calling convention there
711 // may not even be enough space).
712
713 // QQQ I'd rather see this pushed down into last_frame_adjust
714 // and have it take the sender (aka caller).
715
716 if (!deopt_sender.is_interpreted_frame() || caller_was_method_handle) {
717 caller_adjustment = last_frame_adjust(0, callee_locals);
718 } else if (callee_locals > callee_parameters) {
719 // The caller frame may need extending to accommodate
720 // non-parameter locals of the first unpacked interpreted frame.
721 // Compute that adjustment.
722 caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
723 }
724
725 // If the sender is deoptimized the we must retrieve the address of the handler
726 // since the frame will "magically" show the original pc before the deopt
727 // and we'd undo the deopt.
728
729 frame_pcs[0] = Continuation::is_cont_barrier_frame(deoptee) ? StubRoutines::cont_returnBarrier() : deopt_sender.raw_pc();
730 if (Continuation::is_continuation_enterSpecial(deopt_sender)) {
731 ContinuationEntry::from_frame(deopt_sender)->set_argsize(0);
732 }
733
734 assert(CodeCache::find_blob(frame_pcs[0]) != nullptr, "bad pc");
735
736 #if INCLUDE_JVMCI
737 if (exceptionObject() != nullptr) {
738 current->set_exception_oop(exceptionObject());
739 exec_mode = Unpack_exception;
740 }
741 #endif
742
743 if (current->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) {
744 assert(current->has_pending_exception(), "should have thrown OOME");
745 current->set_exception_oop(current->pending_exception());
1221 case T_LONG: return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1222 default:;
1223 }
1224 }
1225 return nullptr;
1226 }
1227 #endif // INCLUDE_JVMCI
1228
1229 #if COMPILER2_OR_JVMCI
1230 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {
1231 Handle pending_exception(THREAD, thread->pending_exception());
1232 const char* exception_file = thread->exception_file();
1233 int exception_line = thread->exception_line();
1234 thread->clear_pending_exception();
1235
1236 bool failures = false;
1237
1238 for (int i = 0; i < objects->length(); i++) {
1239 assert(objects->at(i)->is_object(), "invalid debug information");
1240 ObjectValue* sv = (ObjectValue*) objects->at(i);
1241
1242 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1243 oop obj = nullptr;
1244
1245 bool cache_init_error = false;
1246 if (k->is_instance_klass()) {
1247 #if INCLUDE_JVMCI
1248 nmethod* nm = fr->cb()->as_nmethod_or_null();
1249 if (nm->is_compiled_by_jvmci() && sv->is_auto_box()) {
1250 AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv;
1251 obj = get_cached_box(abv, fr, reg_map, cache_init_error, THREAD);
1252 if (obj != nullptr) {
1253 // Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it.
1254 abv->set_cached(true);
1255 } else if (cache_init_error) {
1256 // Results in an OOME which is valid (as opposed to a class initialization error)
1257 // and is fine for the rare case a cache initialization failing.
1258 failures = true;
1259 }
1260 }
1261 #endif // INCLUDE_JVMCI
1262
1263 InstanceKlass* ik = InstanceKlass::cast(k);
1264 if (obj == nullptr && !cache_init_error) {
1265 InternalOOMEMark iom(THREAD);
1266 if (EnableVectorSupport && VectorSupport::is_vector(ik)) {
1267 obj = VectorSupport::allocate_vector(ik, fr, reg_map, sv, THREAD);
1268 } else {
1269 obj = ik->allocate_instance(THREAD);
1270 }
1271 }
1272 } else if (k->is_typeArray_klass()) {
1273 TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1274 assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
1275 int len = sv->field_size() / type2size[ak->element_type()];
1276 InternalOOMEMark iom(THREAD);
1277 obj = ak->allocate_instance(len, THREAD);
1278 } else if (k->is_objArray_klass()) {
1279 ObjArrayKlass* ak = ObjArrayKlass::cast(k);
1280 InternalOOMEMark iom(THREAD);
1281 obj = ak->allocate_instance(sv->field_size(), THREAD);
1282 }
1283
1284 if (obj == nullptr) {
1285 failures = true;
1286 }
1287
1288 assert(sv->value().is_null(), "redundant reallocation");
1289 assert(obj != nullptr || HAS_PENDING_EXCEPTION || cache_init_error, "allocation should succeed or we should get an exception");
1290 CLEAR_PENDING_EXCEPTION;
1291 sv->set_value(obj);
1292 }
1293
1294 if (failures) {
1295 THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
1296 } else if (pending_exception.not_null()) {
1297 thread->set_pending_exception(pending_exception(), exception_file, exception_line);
1298 }
1299
1300 return failures;
1301 }
1302
1303 #if INCLUDE_JVMCI
1304 /**
1305 * For primitive types whose kind gets "erased" at runtime (shorts become stack ints),
1306 * we need to somehow be able to recover the actual kind to be able to write the correct
1307 * amount of bytes.
1308 * For that purpose, this method assumes that, for an entry spanning n bytes at index i,
1309 * the entries at index n + 1 to n + i are 'markers'.
1310 * For example, if we were writing a short at index 4 of a byte array of size 8, the
1311 * expected form of the array would be:
1312 *
1313 * {b0, b1, b2, b3, INT, marker, b6, b7}
1314 *
1315 * Thus, in order to get back the size of the entry, we simply need to count the number
1316 * of marked entries
1317 *
1318 * @param virtualArray the virtualized byte array
1319 * @param i index of the virtual entry we are recovering
1320 * @return The number of bytes the entry spans
1321 */
1322 static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) {
1448 default:
1449 ShouldNotReachHere();
1450 }
1451 index++;
1452 }
1453 }
1454
1455 // restore fields of an eliminated object array
1456 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
1457 for (int i = 0; i < sv->field_size(); i++) {
1458 StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1459 assert(value->type() == T_OBJECT, "object element expected");
1460 obj->obj_at_put(i, value->get_obj()());
1461 }
1462 }
1463
1464 class ReassignedField {
1465 public:
1466 int _offset;
1467 BasicType _type;
1468 public:
1469 ReassignedField() {
1470 _offset = 0;
1471 _type = T_ILLEGAL;
1472 }
1473 };
1474
1475 // Gets the fields of `klass` that are eliminated by escape analysis and need to be reassigned
1476 static GrowableArray<ReassignedField>* get_reassigned_fields(InstanceKlass* klass, GrowableArray<ReassignedField>* fields, bool is_jvmci) {
1477 InstanceKlass* super = klass->superklass();
1478 if (super != nullptr) {
1479 get_reassigned_fields(super, fields, is_jvmci);
1480 }
1481 for (AllFieldStream fs(klass); !fs.done(); fs.next()) {
1482 if (!fs.access_flags().is_static() && (is_jvmci || !fs.field_flags().is_injected())) {
1483 ReassignedField field;
1484 field._offset = fs.offset();
1485 field._type = Signature::basic_type(fs.signature());
1486 fields->append(field);
1487 }
1488 }
1489 return fields;
1490 }
1491
1492 // Restore fields of an eliminated instance object employing the same field order used by the compiler.
1493 static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool is_jvmci) {
1494 GrowableArray<ReassignedField>* fields = get_reassigned_fields(klass, new GrowableArray<ReassignedField>(), is_jvmci);
1495 for (int i = 0; i < fields->length(); i++) {
1496 ScopeValue* scope_field = sv->field_at(svIndex);
1497 StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1498 int offset = fields->at(i)._offset;
1499 BasicType type = fields->at(i)._type;
1500 switch (type) {
1501 case T_OBJECT: case T_ARRAY:
1502 assert(value->type() == T_OBJECT, "Agreement.");
1503 obj->obj_field_put(offset, value->get_obj()());
1504 break;
1505
1506 case T_INT: case T_FLOAT: { // 4 bytes.
1507 assert(value->type() == T_INT, "Agreement.");
1508 bool big_value = false;
1509 if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {
1510 if (scope_field->is_location()) {
1511 Location::Type type = ((LocationValue*) scope_field)->location().type();
1512 if (type == Location::dbl || type == Location::lng) {
1513 big_value = true;
1514 }
1515 }
1516 if (scope_field->is_constant_int()) {
1517 ScopeValue* next_scope_field = sv->field_at(svIndex + 1);
1518 if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1519 big_value = true;
1520 }
1521 }
1552 case T_CHAR:
1553 assert(value->type() == T_INT, "Agreement.");
1554 obj->char_field_put(offset, (jchar)value->get_jint());
1555 break;
1556
1557 case T_BYTE:
1558 assert(value->type() == T_INT, "Agreement.");
1559 obj->byte_field_put(offset, (jbyte)value->get_jint());
1560 break;
1561
1562 case T_BOOLEAN:
1563 assert(value->type() == T_INT, "Agreement.");
1564 obj->bool_field_put(offset, (jboolean)value->get_jint());
1565 break;
1566
1567 default:
1568 ShouldNotReachHere();
1569 }
1570 svIndex++;
1571 }
1572 return svIndex;
1573 }
1574
1575 // restore fields of all eliminated objects and arrays
1576 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool is_jvmci) {
1577 for (int i = 0; i < objects->length(); i++) {
1578 assert(objects->at(i)->is_object(), "invalid debug information");
1579 ObjectValue* sv = (ObjectValue*) objects->at(i);
1580 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1581 Handle obj = sv->value();
1582 assert(obj.not_null() || realloc_failures, "reallocation was missed");
1583 #ifndef PRODUCT
1584 if (PrintDeoptimizationDetails) {
1585 tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());
1586 }
1587 #endif // !PRODUCT
1588
1589 if (obj.is_null()) {
1590 continue;
1591 }
1592
1593 #if INCLUDE_JVMCI
1594 // Don't reassign fields of boxes that came from a cache. Caches may be in CDS.
1595 if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) {
1596 continue;
1597 }
1598 #endif // INCLUDE_JVMCI
1599 if (EnableVectorSupport && VectorSupport::is_vector(k)) {
1600 assert(sv->field_size() == 1, "%s not a vector", k->name()->as_C_string());
1601 ScopeValue* payload = sv->field_at(0);
1602 if (payload->is_location() &&
1603 payload->as_LocationValue()->location().type() == Location::vector) {
1604 #ifndef PRODUCT
1605 if (PrintDeoptimizationDetails) {
1606 tty->print_cr("skip field reassignment for this vector - it should be assigned already");
1607 if (Verbose) {
1608 Handle obj = sv->value();
1609 k->oop_print_on(obj(), tty);
1610 }
1611 }
1612 #endif // !PRODUCT
1613 continue; // Such vector's value was already restored in VectorSupport::allocate_vector().
1614 }
1615 // Else fall-through to do assignment for scalar-replaced boxed vector representation
1616 // which could be restored after vector object allocation.
1617 }
1618 if (k->is_instance_klass()) {
1619 InstanceKlass* ik = InstanceKlass::cast(k);
1620 reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), is_jvmci);
1621 } else if (k->is_typeArray_klass()) {
1622 TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1623 reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
1624 } else if (k->is_objArray_klass()) {
1625 reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
1626 }
1627 }
1628 // These objects may escape when we return to Interpreter after deoptimization.
1629 // We need barrier so that stores that initialize these objects can't be reordered
1630 // with subsequent stores that make these objects accessible by other threads.
1631 OrderAccess::storestore();
1632 }
1633
1634
1635 // relock objects for which synchronization was eliminated
1636 bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors,
1637 JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) {
1638 bool relocked_objects = false;
1639 for (int i = 0; i < monitors->length(); i++) {
1640 MonitorInfo* mon_info = monitors->at(i);
1641 if (mon_info->eliminated()) {
1642 assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
1643 relocked_objects = true;
1644 if (!mon_info->owner_is_scalar_replaced()) {
1796 xtty->begin_head("deoptimized thread='%zu' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1797 nm->log_identity(xtty);
1798 xtty->end_head();
1799 for (ScopeDesc* sd = nm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1800 xtty->begin_elem("jvms bci='%d'", sd->bci());
1801 xtty->method(sd->method());
1802 xtty->end_elem();
1803 if (sd->is_top()) break;
1804 }
1805 xtty->tail("deoptimized");
1806 }
1807
1808 Continuation::notify_deopt(thread, fr.sp());
1809
1810 // Patch the compiled method so that when execution returns to it we will
1811 // deopt the execution state and return to the interpreter.
1812 fr.deoptimize(thread);
1813 }
1814
1815 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {
1816 // Deoptimize only if the frame comes from compile code.
1817 // Do not deoptimize the frame which is already patched
1818 // during the execution of the loops below.
1819 if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1820 return;
1821 }
1822 ResourceMark rm;
1823 deoptimize_single_frame(thread, fr, reason);
1824 }
1825
1826 #if INCLUDE_JVMCI
1827 address Deoptimization::deoptimize_for_missing_exception_handler(nmethod* nm) {
1828 // there is no exception handler for this pc => deoptimize
1829 nm->make_not_entrant(nmethod::InvalidationReason::MISSING_EXCEPTION_HANDLER);
1830
1831 // Use Deoptimization::deoptimize for all of its side-effects:
1832 // gathering traps statistics, logging...
1833 // it also patches the return pc but we do not care about that
1834 // since we return a continuation to the deopt_blob below.
1835 JavaThread* thread = JavaThread::current();
1836 RegisterMap reg_map(thread,
|
33 #include "code/scopeDesc.hpp"
34 #include "compiler/compilationPolicy.hpp"
35 #include "compiler/compilerDefinitions.inline.hpp"
36 #include "gc/shared/collectedHeap.hpp"
37 #include "gc/shared/memAllocator.hpp"
38 #include "interpreter/bytecode.hpp"
39 #include "interpreter/bytecode.inline.hpp"
40 #include "interpreter/bytecodeStream.hpp"
41 #include "interpreter/interpreter.hpp"
42 #include "interpreter/oopMapCache.hpp"
43 #include "jvm.h"
44 #include "logging/log.hpp"
45 #include "logging/logLevel.hpp"
46 #include "logging/logMessage.hpp"
47 #include "logging/logStream.hpp"
48 #include "memory/allocation.inline.hpp"
49 #include "memory/oopFactory.hpp"
50 #include "memory/resourceArea.hpp"
51 #include "memory/universe.hpp"
52 #include "oops/constantPool.hpp"
53 #include "oops/flatArrayKlass.hpp"
54 #include "oops/flatArrayOop.hpp"
55 #include "oops/fieldStreams.inline.hpp"
56 #include "oops/method.hpp"
57 #include "oops/objArrayKlass.hpp"
58 #include "oops/objArrayOop.inline.hpp"
59 #include "oops/oop.inline.hpp"
60 #include "oops/inlineKlass.inline.hpp"
61 #include "oops/typeArrayOop.inline.hpp"
62 #include "oops/verifyOopClosure.hpp"
63 #include "prims/jvmtiDeferredUpdates.hpp"
64 #include "prims/jvmtiExport.hpp"
65 #include "prims/jvmtiThreadState.hpp"
66 #include "prims/methodHandles.hpp"
67 #include "prims/vectorSupport.hpp"
68 #include "runtime/atomic.hpp"
69 #include "runtime/basicLock.inline.hpp"
70 #include "runtime/continuation.hpp"
71 #include "runtime/continuationEntry.inline.hpp"
72 #include "runtime/deoptimization.hpp"
73 #include "runtime/escapeBarrier.hpp"
74 #include "runtime/fieldDescriptor.hpp"
75 #include "runtime/fieldDescriptor.inline.hpp"
76 #include "runtime/frame.inline.hpp"
77 #include "runtime/handles.inline.hpp"
78 #include "runtime/interfaceSupport.inline.hpp"
79 #include "runtime/javaThread.hpp"
80 #include "runtime/jniHandles.inline.hpp"
286 // The actual reallocation of previously eliminated objects occurs in realloc_objects,
287 // which is called from the method fetch_unroll_info_helper below.
288 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* current, int exec_mode))
289 // fetch_unroll_info() is called at the beginning of the deoptimization
290 // handler. Note this fact before we start generating temporary frames
291 // that can confuse an asynchronous stack walker. This counter is
292 // decremented at the end of unpack_frames().
293 current->inc_in_deopt_handler();
294
295 if (exec_mode == Unpack_exception) {
296 // When we get here, a callee has thrown an exception into a deoptimized
297 // frame. That throw might have deferred stack watermark checking until
298 // after unwinding. So we deal with such deferred requests here.
299 StackWatermarkSet::after_unwind(current);
300 }
301
302 return fetch_unroll_info_helper(current, exec_mode);
303 JRT_END
304
305 #if COMPILER2_OR_JVMCI
306
307 static Klass* get_refined_array_klass(Klass* k, frame* fr, RegisterMap* map, ObjectValue* sv, TRAPS) {
308 // If it's an array, get the properties
309 if (k->is_array_klass() && !k->is_typeArray_klass()) {
310 assert(!k->is_refArray_klass() && !k->is_flatArray_klass(), "Unexpected refined klass");
311 nmethod* nm = fr->cb()->as_nmethod_or_null();
312 if (nm->is_compiled_by_c2()) {
313 assert(sv->has_properties(), "Property information is missing");
314 ArrayKlass::ArrayProperties props = static_cast<ArrayKlass::ArrayProperties>(StackValue::create_stack_value(fr, map, sv->properties())->get_jint());
315 k = ObjArrayKlass::cast(k)->klass_with_properties(props, THREAD);
316 } else {
317 // TODO Graal needs to be fixed. Just go with the default properties for now
318 k = ObjArrayKlass::cast(k)->klass_with_properties(ArrayKlass::ArrayProperties::DEFAULT, THREAD);
319 }
320 }
321 return k;
322 }
323
324 // print information about reallocated objects
325 static void print_objects(JavaThread* deoptee_thread, frame* deoptee, RegisterMap* map,
326 GrowableArray<ScopeValue*>* objects, bool realloc_failures, TRAPS) {
327 ResourceMark rm;
328 stringStream st; // change to logStream with logging
329 st.print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(deoptee_thread));
330 fieldDescriptor fd;
331
332 for (int i = 0; i < objects->length(); i++) {
333 ObjectValue* sv = (ObjectValue*) objects->at(i);
334 Handle obj = sv->value();
335
336 if (obj.is_null()) {
337 st.print_cr(" nullptr");
338 continue;
339 }
340
341 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
342 k = get_refined_array_klass(k, deoptee, map, sv, THREAD);
343
344 st.print(" object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));
345 k->print_value_on(&st);
346 st.print_cr(" allocated (%zu bytes)", obj->size() * HeapWordSize);
347
348 if (Verbose && k != nullptr) {
349 k->oop_print_on(obj(), &st);
350 }
351 }
352 tty->print_raw(st.freeze());
353 }
354
355 static bool rematerialize_objects(JavaThread* thread, int exec_mode, nmethod* compiled_method,
356 frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk,
357 bool& deoptimized_objects) {
358 bool realloc_failures = false;
359 assert (chunk->at(0)->scope() != nullptr,"expect only compiled java frames");
360
361 JavaThread* deoptee_thread = chunk->at(0)->thread();
362 assert(exec_mode == Deoptimization::Unpack_none || (deoptee_thread == thread),
363 "a frame can only be deoptimized by the owner thread");
364
365 GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects_to_rematerialize(deoptee, map);
366
367 // The flag return_oop() indicates call sites which return oop
368 // in compiled code. Such sites include java method calls,
369 // runtime calls (for example, used to allocate new objects/arrays
370 // on slow code path) and any other calls generated in compiled code.
371 // It is not guaranteed that we can get such information here only
372 // by analyzing bytecode in deoptimized frames. This is why this flag
373 // is set during method compilation (see Compile::Process_OopMap_Node()).
374 // If the previous frame was popped or if we are dispatching an exception,
375 // we don't have an oop result.
376 ScopeDesc* scope = chunk->at(0)->scope();
377 bool save_oop_result = scope->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt);
378 // In case of the return of multiple values, we must take care
379 // of all oop return values.
380 GrowableArray<Handle> return_oops;
381 InlineKlass* vk = nullptr;
382 if (save_oop_result && scope->return_scalarized()) {
383 vk = InlineKlass::returned_inline_klass(map);
384 if (vk != nullptr) {
385 vk->save_oop_fields(map, return_oops);
386 save_oop_result = false;
387 }
388 }
389 if (save_oop_result) {
390 // Reallocation may trigger GC. If deoptimization happened on return from
391 // call which returns oop we need to save it since it is not in oopmap.
392 oop result = deoptee.saved_oop_result(&map);
393 assert(oopDesc::is_oop_or_null(result), "must be oop");
394 return_oops.push(Handle(thread, result));
395 assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
396 if (TraceDeoptimization) {
397 tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread));
398 tty->cr();
399 }
400 }
401 if (objects != nullptr || vk != nullptr) {
402 if (exec_mode == Deoptimization::Unpack_none) {
403 assert(thread->thread_state() == _thread_in_vm, "assumption");
404 JavaThread* THREAD = thread; // For exception macros.
405 // Clear pending OOM if reallocation fails and return true indicating allocation failure
406 if (vk != nullptr) {
407 realloc_failures = Deoptimization::realloc_inline_type_result(vk, map, return_oops, CHECK_AND_CLEAR_(true));
408 }
409 if (objects != nullptr) {
410 realloc_failures = realloc_failures || Deoptimization::realloc_objects(thread, &deoptee, &map, objects, CHECK_AND_CLEAR_(true));
411 guarantee(compiled_method != nullptr, "deopt must be associated with an nmethod");
412 bool is_jvmci = compiled_method->is_compiled_by_jvmci();
413 Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, is_jvmci, CHECK_AND_CLEAR_(true));
414 }
415 deoptimized_objects = true;
416 } else {
417 JavaThread* current = thread; // For JRT_BLOCK
418 JRT_BLOCK
419 if (vk != nullptr) {
420 realloc_failures = Deoptimization::realloc_inline_type_result(vk, map, return_oops, THREAD);
421 }
422 if (objects != nullptr) {
423 realloc_failures = realloc_failures || Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD);
424 guarantee(compiled_method != nullptr, "deopt must be associated with an nmethod");
425 bool is_jvmci = compiled_method->is_compiled_by_jvmci();
426 Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, is_jvmci, THREAD);
427 }
428 JRT_END
429 }
430 if (TraceDeoptimization && objects != nullptr) {
431 print_objects(deoptee_thread, &deoptee, &map, objects, realloc_failures, thread);
432 }
433 }
434 if (save_oop_result || vk != nullptr) {
435 // Restore result.
436 assert(return_oops.length() == 1, "no inline type");
437 deoptee.set_saved_oop_result(&map, return_oops.pop()());
438 }
439 return realloc_failures;
440 }
441
442 static void restore_eliminated_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures,
443 frame& deoptee, int exec_mode, bool& deoptimized_objects) {
444 JavaThread* deoptee_thread = chunk->at(0)->thread();
445 assert(!EscapeBarrier::objs_are_deoptimized(deoptee_thread, deoptee.id()), "must relock just once");
446 assert(thread == Thread::current(), "should be");
447 HandleMark hm(thread);
448 #ifndef PRODUCT
449 bool first = true;
450 #endif // !PRODUCT
451 // Start locking from outermost/oldest frame
452 for (int i = (chunk->length() - 1); i >= 0; i--) {
453 compiledVFrame* cvf = chunk->at(i);
454 assert (cvf->scope() != nullptr,"expect only compiled java frames");
455 GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
456 if (monitors->is_nonempty()) {
457 bool relocked = Deoptimization::relock_objects(thread, monitors, deoptee_thread, deoptee,
752 // its caller's stack by. If the caller is a compiled frame then
753 // we pretend that the callee has no parameters so that the
754 // extension counts for the full amount of locals and not just
755 // locals-parms. This is because without a c2i adapter the parm
756 // area as created by the compiled frame will not be usable by
757 // the interpreter. (Depending on the calling convention there
758 // may not even be enough space).
759
760 // QQQ I'd rather see this pushed down into last_frame_adjust
761 // and have it take the sender (aka caller).
762
763 if (!deopt_sender.is_interpreted_frame() || caller_was_method_handle) {
764 caller_adjustment = last_frame_adjust(0, callee_locals);
765 } else if (callee_locals > callee_parameters) {
766 // The caller frame may need extending to accommodate
767 // non-parameter locals of the first unpacked interpreted frame.
768 // Compute that adjustment.
769 caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
770 }
771
772 // If the sender is deoptimized we must retrieve the address of the handler
773 // since the frame will "magically" show the original pc before the deopt
774 // and we'd undo the deopt.
775
776 frame_pcs[0] = Continuation::is_cont_barrier_frame(deoptee) ? StubRoutines::cont_returnBarrier() : deopt_sender.raw_pc();
777 if (Continuation::is_continuation_enterSpecial(deopt_sender)) {
778 ContinuationEntry::from_frame(deopt_sender)->set_argsize(0);
779 }
780
781 assert(CodeCache::find_blob(frame_pcs[0]) != nullptr, "bad pc");
782
783 #if INCLUDE_JVMCI
784 if (exceptionObject() != nullptr) {
785 current->set_exception_oop(exceptionObject());
786 exec_mode = Unpack_exception;
787 }
788 #endif
789
790 if (current->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) {
791 assert(current->has_pending_exception(), "should have thrown OOME");
792 current->set_exception_oop(current->pending_exception());
1268 case T_LONG: return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1269 default:;
1270 }
1271 }
1272 return nullptr;
1273 }
1274 #endif // INCLUDE_JVMCI
1275
1276 #if COMPILER2_OR_JVMCI
1277 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {
1278 Handle pending_exception(THREAD, thread->pending_exception());
1279 const char* exception_file = thread->exception_file();
1280 int exception_line = thread->exception_line();
1281 thread->clear_pending_exception();
1282
1283 bool failures = false;
1284
1285 for (int i = 0; i < objects->length(); i++) {
1286 assert(objects->at(i)->is_object(), "invalid debug information");
1287 ObjectValue* sv = (ObjectValue*) objects->at(i);
1288 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1289 k = get_refined_array_klass(k, fr, reg_map, sv, THREAD);
1290
1291 // Check if the object may be null and has an additional null_marker input that needs
1292 // to be checked before using the field values. Skip re-allocation if it is null.
1293 if (k->is_inline_klass() && sv->has_properties()) {
1294 jint null_marker = StackValue::create_stack_value(fr, reg_map, sv->properties())->get_jint();
1295 if (null_marker == 0) {
1296 continue;
1297 }
1298 }
1299
1300 oop obj = nullptr;
1301 bool cache_init_error = false;
1302 if (k->is_instance_klass()) {
1303 #if INCLUDE_JVMCI
1304 nmethod* nm = fr->cb()->as_nmethod_or_null();
1305 if (nm->is_compiled_by_jvmci() && sv->is_auto_box()) {
1306 AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv;
1307 obj = get_cached_box(abv, fr, reg_map, cache_init_error, THREAD);
1308 if (obj != nullptr) {
1309 // Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it.
1310 abv->set_cached(true);
1311 } else if (cache_init_error) {
1312 // Results in an OOME which is valid (as opposed to a class initialization error)
1313 // and is fine for the rare case a cache initialization failing.
1314 failures = true;
1315 }
1316 }
1317 #endif // INCLUDE_JVMCI
1318
1319 InstanceKlass* ik = InstanceKlass::cast(k);
1320 if (obj == nullptr && !cache_init_error) {
1321 InternalOOMEMark iom(THREAD);
1322 if (EnableVectorSupport && VectorSupport::is_vector(ik)) {
1323 obj = VectorSupport::allocate_vector(ik, fr, reg_map, sv, THREAD);
1324 } else {
1325 obj = ik->allocate_instance(THREAD);
1326 }
1327 }
1328 } else if (k->is_flatArray_klass()) {
1329 FlatArrayKlass* ak = FlatArrayKlass::cast(k);
1330 // Inline type array must be zeroed because not all memory is reassigned
1331 obj = ak->allocate_instance(sv->field_size(), ak->properties(), THREAD);
1332 } else if (k->is_typeArray_klass()) {
1333 TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1334 assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
1335 int len = sv->field_size() / type2size[ak->element_type()];
1336 InternalOOMEMark iom(THREAD);
1337 obj = ak->allocate_instance(len, THREAD);
1338 } else if (k->is_refArray_klass()) {
1339 RefArrayKlass* ak = RefArrayKlass::cast(k);
1340 InternalOOMEMark iom(THREAD);
1341 obj = ak->allocate_instance(sv->field_size(), ak->properties(), THREAD);
1342 }
1343
1344 if (obj == nullptr) {
1345 failures = true;
1346 }
1347
1348 assert(sv->value().is_null(), "redundant reallocation");
1349 assert(obj != nullptr || HAS_PENDING_EXCEPTION || cache_init_error, "allocation should succeed or we should get an exception");
1350 CLEAR_PENDING_EXCEPTION;
1351 sv->set_value(obj);
1352 }
1353
1354 if (failures) {
1355 THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
1356 } else if (pending_exception.not_null()) {
1357 thread->set_pending_exception(pending_exception(), exception_file, exception_line);
1358 }
1359
1360 return failures;
1361 }
1362
1363 // We're deoptimizing at the return of a call, inline type fields are
1364 // in registers. When we go back to the interpreter, it will expect a
1365 // reference to an inline type instance. Allocate and initialize it from
1366 // the register values here.
1367 bool Deoptimization::realloc_inline_type_result(InlineKlass* vk, const RegisterMap& map, GrowableArray<Handle>& return_oops, TRAPS) {
1368 oop new_vt = vk->realloc_result(map, return_oops, THREAD);
1369 if (new_vt == nullptr) {
1370 CLEAR_PENDING_EXCEPTION;
1371 THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), true);
1372 }
1373 return_oops.clear();
1374 return_oops.push(Handle(THREAD, new_vt));
1375 return false;
1376 }
1377
1378 #if INCLUDE_JVMCI
1379 /**
1380 * For primitive types whose kind gets "erased" at runtime (shorts become stack ints),
1381 * we need to somehow be able to recover the actual kind to be able to write the correct
1382 * amount of bytes.
1383 * For that purpose, this method assumes that, for an entry spanning n bytes at index i,
1384 * the entries at index n + 1 to n + i are 'markers'.
1385 * For example, if we were writing a short at index 4 of a byte array of size 8, the
1386 * expected form of the array would be:
1387 *
1388 * {b0, b1, b2, b3, INT, marker, b6, b7}
1389 *
1390 * Thus, in order to get back the size of the entry, we simply need to count the number
1391 * of marked entries
1392 *
1393 * @param virtualArray the virtualized byte array
1394 * @param i index of the virtual entry we are recovering
1395 * @return The number of bytes the entry spans
1396 */
1397 static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) {
1523 default:
1524 ShouldNotReachHere();
1525 }
1526 index++;
1527 }
1528 }
1529
1530 // restore fields of an eliminated object array
1531 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
1532 for (int i = 0; i < sv->field_size(); i++) {
1533 StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1534 assert(value->type() == T_OBJECT, "object element expected");
1535 obj->obj_at_put(i, value->get_obj()());
1536 }
1537 }
1538
1539 class ReassignedField {
1540 public:
1541 int _offset;
1542 BasicType _type;
1543 InstanceKlass* _klass;
1544 bool _is_flat;
1545 bool _is_null_free;
1546 public:
1547 ReassignedField() : _offset(0), _type(T_ILLEGAL), _klass(nullptr), _is_flat(false), _is_null_free(false) { }
1548 };
1549
1550 // Gets the fields of `klass` that are eliminated by escape analysis and need to be reassigned
1551 static GrowableArray<ReassignedField>* get_reassigned_fields(InstanceKlass* klass, GrowableArray<ReassignedField>* fields, bool is_jvmci) {
1552 InstanceKlass* super = klass->superklass();
1553 if (super != nullptr) {
1554 get_reassigned_fields(super, fields, is_jvmci);
1555 }
1556 for (AllFieldStream fs(klass); !fs.done(); fs.next()) {
1557 if (!fs.access_flags().is_static() && (is_jvmci || !fs.field_flags().is_injected())) {
1558 ReassignedField field;
1559 field._offset = fs.offset();
1560 field._type = Signature::basic_type(fs.signature());
1561 if (fs.is_flat()) {
1562 field._is_flat = true;
1563 field._is_null_free = fs.is_null_free_inline_type();
1564 // Resolve klass of flat inline type field
1565 field._klass = InlineKlass::cast(klass->get_inline_type_field_klass(fs.index()));
1566 }
1567 fields->append(field);
1568 }
1569 }
1570 return fields;
1571 }
1572
1573 // Restore fields of an eliminated instance object employing the same field order used by the
1574 // compiler when it scalarizes an object at safepoints.
1575 static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool is_jvmci, int base_offset, TRAPS) {
1576 GrowableArray<ReassignedField>* fields = get_reassigned_fields(klass, new GrowableArray<ReassignedField>(), is_jvmci);
1577 for (int i = 0; i < fields->length(); i++) {
1578 BasicType type = fields->at(i)._type;
1579 int offset = base_offset + fields->at(i)._offset;
1580 // Check for flat inline type field before accessing the ScopeValue because it might not have any fields
1581 if (fields->at(i)._is_flat) {
1582 // Recursively re-assign flat inline type fields
1583 InstanceKlass* vk = fields->at(i)._klass;
1584 assert(vk != nullptr, "must be resolved");
1585 offset -= InlineKlass::cast(vk)->payload_offset(); // Adjust offset to omit oop header
1586 svIndex = reassign_fields_by_klass(vk, fr, reg_map, sv, svIndex, obj, is_jvmci, offset, CHECK_0);
1587 if (!fields->at(i)._is_null_free) {
1588 ScopeValue* scope_field = sv->field_at(svIndex);
1589 StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1590 int nm_offset = offset + InlineKlass::cast(vk)->null_marker_offset();
1591 obj->bool_field_put(nm_offset, value->get_jint() & 1);
1592 svIndex++;
1593 }
1594 continue; // Continue because we don't need to increment svIndex
1595 }
1596
1597 ScopeValue* scope_field = sv->field_at(svIndex);
1598 StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1599 switch (type) {
1600 case T_OBJECT:
1601 case T_ARRAY:
1602 assert(value->type() == T_OBJECT, "Agreement.");
1603 obj->obj_field_put(offset, value->get_obj()());
1604 break;
1605
1606 case T_INT: case T_FLOAT: { // 4 bytes.
1607 assert(value->type() == T_INT, "Agreement.");
1608 bool big_value = false;
1609 if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {
1610 if (scope_field->is_location()) {
1611 Location::Type type = ((LocationValue*) scope_field)->location().type();
1612 if (type == Location::dbl || type == Location::lng) {
1613 big_value = true;
1614 }
1615 }
1616 if (scope_field->is_constant_int()) {
1617 ScopeValue* next_scope_field = sv->field_at(svIndex + 1);
1618 if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1619 big_value = true;
1620 }
1621 }
1652 case T_CHAR:
1653 assert(value->type() == T_INT, "Agreement.");
1654 obj->char_field_put(offset, (jchar)value->get_jint());
1655 break;
1656
1657 case T_BYTE:
1658 assert(value->type() == T_INT, "Agreement.");
1659 obj->byte_field_put(offset, (jbyte)value->get_jint());
1660 break;
1661
1662 case T_BOOLEAN:
1663 assert(value->type() == T_INT, "Agreement.");
1664 obj->bool_field_put(offset, (jboolean)value->get_jint());
1665 break;
1666
1667 default:
1668 ShouldNotReachHere();
1669 }
1670 svIndex++;
1671 }
1672
1673 return svIndex;
1674 }
1675
1676 // restore fields of an eliminated inline type array
1677 void Deoptimization::reassign_flat_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, flatArrayOop obj, FlatArrayKlass* vak, bool is_jvmci, TRAPS) {
1678 InlineKlass* vk = vak->element_klass();
1679 assert(vk->maybe_flat_in_array(), "should only be used for flat inline type arrays");
1680 // Adjust offset to omit oop header
1681 int base_offset = arrayOopDesc::base_offset_in_bytes(T_FLAT_ELEMENT) - InlineKlass::cast(vk)->payload_offset();
1682 // Initialize all elements of the flat inline type array
1683 for (int i = 0; i < sv->field_size(); i++) {
1684 ScopeValue* val = sv->field_at(i);
1685 int offset = base_offset + (i << Klass::layout_helper_log2_element_size(vak->layout_helper()));
1686 reassign_fields_by_klass(vk, fr, reg_map, val->as_ObjectValue(), 0, (oop)obj, is_jvmci, offset, CHECK);
1687 }
1688 }
1689
1690 // restore fields of all eliminated objects and arrays
1691 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool is_jvmci, TRAPS) {
1692 for (int i = 0; i < objects->length(); i++) {
1693 assert(objects->at(i)->is_object(), "invalid debug information");
1694 ObjectValue* sv = (ObjectValue*) objects->at(i);
1695 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1696 k = get_refined_array_klass(k, fr, reg_map, sv, THREAD);
1697
1698 Handle obj = sv->value();
1699 assert(obj.not_null() || realloc_failures || sv->has_properties(), "reallocation was missed");
1700 #ifndef PRODUCT
1701 if (PrintDeoptimizationDetails) {
1702 tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());
1703 }
1704 #endif // !PRODUCT
1705
1706 if (obj.is_null()) {
1707 continue;
1708 }
1709
1710 #if INCLUDE_JVMCI
1711 // Don't reassign fields of boxes that came from a cache. Caches may be in CDS.
1712 if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) {
1713 continue;
1714 }
1715 #endif // INCLUDE_JVMCI
1716 if (EnableVectorSupport && VectorSupport::is_vector(k)) {
1717 assert(sv->field_size() == 1, "%s not a vector", k->name()->as_C_string());
1718 ScopeValue* payload = sv->field_at(0);
1719 if (payload->is_location() &&
1720 payload->as_LocationValue()->location().type() == Location::vector) {
1721 #ifndef PRODUCT
1722 if (PrintDeoptimizationDetails) {
1723 tty->print_cr("skip field reassignment for this vector - it should be assigned already");
1724 if (Verbose) {
1725 Handle obj = sv->value();
1726 k->oop_print_on(obj(), tty);
1727 }
1728 }
1729 #endif // !PRODUCT
1730 continue; // Such vector's value was already restored in VectorSupport::allocate_vector().
1731 }
1732 // Else fall-through to do assignment for scalar-replaced boxed vector representation
1733 // which could be restored after vector object allocation.
1734 }
1735 if (k->is_instance_klass()) {
1736 InstanceKlass* ik = InstanceKlass::cast(k);
1737 reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), is_jvmci, 0, CHECK);
1738 } else if (k->is_flatArray_klass()) {
1739 FlatArrayKlass* vak = FlatArrayKlass::cast(k);
1740 reassign_flat_array_elements(fr, reg_map, sv, (flatArrayOop) obj(), vak, is_jvmci, CHECK);
1741 } else if (k->is_typeArray_klass()) {
1742 TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1743 reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
1744 } else if (k->is_refArray_klass()) {
1745 reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
1746 }
1747 }
1748 // These objects may escape when we return to Interpreter after deoptimization.
1749 // We need barrier so that stores that initialize these objects can't be reordered
1750 // with subsequent stores that make these objects accessible by other threads.
1751 OrderAccess::storestore();
1752 }
1753
1754
1755 // relock objects for which synchronization was eliminated
1756 bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors,
1757 JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) {
1758 bool relocked_objects = false;
1759 for (int i = 0; i < monitors->length(); i++) {
1760 MonitorInfo* mon_info = monitors->at(i);
1761 if (mon_info->eliminated()) {
1762 assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
1763 relocked_objects = true;
1764 if (!mon_info->owner_is_scalar_replaced()) {
1916 xtty->begin_head("deoptimized thread='%zu' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1917 nm->log_identity(xtty);
1918 xtty->end_head();
1919 for (ScopeDesc* sd = nm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1920 xtty->begin_elem("jvms bci='%d'", sd->bci());
1921 xtty->method(sd->method());
1922 xtty->end_elem();
1923 if (sd->is_top()) break;
1924 }
1925 xtty->tail("deoptimized");
1926 }
1927
1928 Continuation::notify_deopt(thread, fr.sp());
1929
1930 // Patch the compiled method so that when execution returns to it we will
1931 // deopt the execution state and return to the interpreter.
1932 fr.deoptimize(thread);
1933 }
1934
1935 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {
1936 // Deoptimize only if the frame comes from compiled code.
1937 // Do not deoptimize the frame which is already patched
1938 // during the execution of the loops below.
1939 if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1940 return;
1941 }
1942 ResourceMark rm;
1943 deoptimize_single_frame(thread, fr, reason);
1944 }
1945
1946 #if INCLUDE_JVMCI
1947 address Deoptimization::deoptimize_for_missing_exception_handler(nmethod* nm) {
1948 // there is no exception handler for this pc => deoptimize
1949 nm->make_not_entrant(nmethod::InvalidationReason::MISSING_EXCEPTION_HANDLER);
1950
1951 // Use Deoptimization::deoptimize for all of its side-effects:
1952 // gathering traps statistics, logging...
1953 // it also patches the return pc but we do not care about that
1954 // since we return a continuation to the deopt_blob below.
1955 JavaThread* thread = JavaThread::current();
1956 RegisterMap reg_map(thread,
|