1 /*
   2  * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   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 "classfile/javaClasses.inline.hpp"
  26 #include "classfile/symbolTable.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmClasses.hpp"
  29 #include "code/codeCache.hpp"
  30 #include "code/debugInfoRec.hpp"
  31 #include "code/nmethod.hpp"
  32 #include "code/pcDesc.hpp"
  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.inline.hpp"
  39 #include "interpreter/bytecodeStream.hpp"
  40 #include "interpreter/interpreter.hpp"
  41 #include "interpreter/oopMapCache.hpp"
  42 #include "jvm.h"
  43 #include "logging/log.hpp"
  44 #include "logging/logLevel.hpp"
  45 #include "logging/logMessage.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/allocation.inline.hpp"
  48 #include "memory/oopFactory.hpp"
  49 #include "memory/resourceArea.hpp"
  50 #include "memory/universe.hpp"
  51 #include "oops/arrayOop.inline.hpp"
  52 #include "oops/constantPool.hpp"
  53 #include "oops/fieldStreams.inline.hpp"
  54 #include "oops/flatArrayKlass.hpp"
  55 #include "oops/flatArrayOop.hpp"
  56 #include "oops/inlineKlass.inline.hpp"
  57 #include "oops/method.hpp"
  58 #include "oops/objArrayKlass.hpp"
  59 #include "oops/objArrayOop.inline.hpp"
  60 #include "oops/oop.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/arguments.hpp"
  69 #include "runtime/atomicAccess.hpp"
  70 #include "runtime/basicLock.inline.hpp"
  71 #include "runtime/continuation.hpp"
  72 #include "runtime/continuationEntry.inline.hpp"
  73 #include "runtime/deoptimization.hpp"
  74 #include "runtime/escapeBarrier.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"
  81 #include "runtime/keepStackGCProcessed.hpp"
  82 #include "runtime/lockStack.inline.hpp"
  83 #include "runtime/objectMonitor.inline.hpp"
  84 #include "runtime/osThread.hpp"
  85 #include "runtime/safepointVerifiers.hpp"
  86 #include "runtime/sharedRuntime.hpp"
  87 #include "runtime/signature.hpp"
  88 #include "runtime/stackFrameStream.inline.hpp"
  89 #include "runtime/stackValue.hpp"
  90 #include "runtime/stackWatermarkSet.hpp"
  91 #include "runtime/stubRoutines.hpp"
  92 #include "runtime/synchronizer.hpp"
  93 #include "runtime/threadSMR.hpp"
  94 #include "runtime/threadWXSetters.inline.hpp"
  95 #include "runtime/vframe.hpp"
  96 #include "runtime/vframe_hp.hpp"
  97 #include "runtime/vframeArray.hpp"
  98 #include "runtime/vmOperations.hpp"
  99 #include "utilities/checkedCast.hpp"
 100 #include "utilities/events.hpp"
 101 #include "utilities/growableArray.hpp"
 102 #include "utilities/macros.hpp"
 103 #include "utilities/preserveException.hpp"
 104 #include "utilities/xmlstream.hpp"
 105 #if INCLUDE_JFR
 106 #include "jfr/jfr.inline.hpp"
 107 #include "jfr/jfrEvents.hpp"
 108 #include "jfr/metadata/jfrSerializer.hpp"
 109 #endif
 110 
 111 uint64_t DeoptimizationScope::_committed_deopt_gen = 0;
 112 uint64_t DeoptimizationScope::_active_deopt_gen    = 1;
 113 bool     DeoptimizationScope::_committing_in_progress = false;
 114 
 115 DeoptimizationScope::DeoptimizationScope() : _required_gen(0) {
 116   DEBUG_ONLY(_deopted = false;)
 117 
 118   MutexLocker ml(NMethodState_lock, Mutex::_no_safepoint_check_flag);
 119   // If there is nothing to deopt _required_gen is the same as comitted.
 120   _required_gen = DeoptimizationScope::_committed_deopt_gen;
 121 }
 122 
 123 DeoptimizationScope::~DeoptimizationScope() {
 124   assert(_deopted, "Deopt not executed");
 125 }
 126 
 127 void DeoptimizationScope::mark(nmethod* nm, bool inc_recompile_counts) {
 128   if (!nm->can_be_deoptimized()) {
 129     return;
 130   }
 131 
 132   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 133 
 134   // If it's already marked but we still need it to be deopted.
 135   if (nm->is_marked_for_deoptimization()) {
 136     dependent(nm);
 137     return;
 138   }
 139 
 140   MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
 141   nmethod::DeoptimizationStatus status =
 142     inc_recompile_counts ? nmethod::deoptimize : nmethod::deoptimize_noupdate;
 143   AtomicAccess::store(&nm->_deoptimization_status, status);
 144 
 145   // Make sure active is not committed
 146   assert(DeoptimizationScope::_committed_deopt_gen < DeoptimizationScope::_active_deopt_gen, "Must be");
 147   assert(nm->_deoptimization_generation == 0, "Is already marked");
 148 
 149   nm->_deoptimization_generation = DeoptimizationScope::_active_deopt_gen;
 150   _required_gen                  = DeoptimizationScope::_active_deopt_gen;
 151 }
 152 
 153 void DeoptimizationScope::dependent(nmethod* nm) {
 154   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 155 
 156   // A method marked by someone else may have a _required_gen lower than what we marked with.
 157   // Therefore only store it if it's higher than _required_gen.
 158   if (_required_gen < nm->_deoptimization_generation) {
 159     _required_gen = nm->_deoptimization_generation;
 160   }
 161 }
 162 
 163 void DeoptimizationScope::deoptimize_marked() {
 164   assert(!_deopted, "Already deopted");
 165 
 166   // We are not alive yet.
 167   if (!Universe::is_fully_initialized()) {
 168     DEBUG_ONLY(_deopted = true;)
 169     return;
 170   }
 171 
 172   // Safepoints are a special case, handled here.
 173   if (SafepointSynchronize::is_at_safepoint()) {
 174     DeoptimizationScope::_committed_deopt_gen = DeoptimizationScope::_active_deopt_gen;
 175     DeoptimizationScope::_active_deopt_gen++;
 176     Deoptimization::deoptimize_all_marked();
 177     DEBUG_ONLY(_deopted = true;)
 178     return;
 179   }
 180 
 181   uint64_t comitting = 0;
 182   bool wait = false;
 183   while (true) {
 184     {
 185       ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 186 
 187       // First we check if we or someone else already deopted the gen we want.
 188       if (DeoptimizationScope::_committed_deopt_gen >= _required_gen) {
 189         DEBUG_ONLY(_deopted = true;)
 190         return;
 191       }
 192       if (!_committing_in_progress) {
 193         // The version we are about to commit.
 194         comitting = DeoptimizationScope::_active_deopt_gen;
 195         // Make sure new marks use a higher gen.
 196         DeoptimizationScope::_active_deopt_gen++;
 197         _committing_in_progress = true;
 198         wait = false;
 199       } else {
 200         // Another thread is handshaking and committing a gen.
 201         wait = true;
 202       }
 203     }
 204     if (wait) {
 205       // Wait and let the concurrent handshake be performed.
 206       ThreadBlockInVM tbivm(JavaThread::current());
 207       os::naked_yield();
 208     } else {
 209       // Performs the handshake.
 210       Deoptimization::deoptimize_all_marked(); // May safepoint and an additional deopt may have occurred.
 211       DEBUG_ONLY(_deopted = true;)
 212       {
 213         ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 214 
 215         // Make sure that committed doesn't go backwards.
 216         // Should only happen if we did a deopt during a safepoint above.
 217         if (DeoptimizationScope::_committed_deopt_gen < comitting) {
 218           DeoptimizationScope::_committed_deopt_gen = comitting;
 219         }
 220         _committing_in_progress = false;
 221 
 222         assert(DeoptimizationScope::_committed_deopt_gen >= _required_gen, "Must be");
 223 
 224         return;
 225       }
 226     }
 227   }
 228 }
 229 
 230 Deoptimization::UnrollBlock::UnrollBlock(int  size_of_deoptimized_frame,
 231                                          int  caller_adjustment,
 232                                          int  caller_actual_parameters,
 233                                          int  number_of_frames,
 234                                          intptr_t* frame_sizes,
 235                                          address* frame_pcs,
 236                                          BasicType return_type,
 237                                          int exec_mode) {
 238   _size_of_deoptimized_frame = size_of_deoptimized_frame;
 239   _caller_adjustment         = caller_adjustment;
 240   _caller_actual_parameters  = caller_actual_parameters;
 241   _number_of_frames          = number_of_frames;
 242   _frame_sizes               = frame_sizes;
 243   _frame_pcs                 = frame_pcs;
 244   _register_block            = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
 245   _return_type               = return_type;
 246   _initial_info              = 0;
 247   // PD (x86 only)
 248   _counter_temp              = 0;
 249   _unpack_kind               = exec_mode;
 250   _sender_sp_temp            = 0;
 251 
 252   _total_frame_sizes         = size_of_frames();
 253   assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode");
 254 }
 255 
 256 Deoptimization::UnrollBlock::~UnrollBlock() {
 257   FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes);
 258   FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs);
 259   FREE_C_HEAP_ARRAY(intptr_t, _register_block);
 260 }
 261 
 262 int Deoptimization::UnrollBlock::size_of_frames() const {
 263   // Account first for the adjustment of the initial frame
 264   intptr_t result = _caller_adjustment;
 265   for (int index = 0; index < number_of_frames(); index++) {
 266     result += frame_sizes()[index];
 267   }
 268   return checked_cast<int>(result);
 269 }
 270 
 271 void Deoptimization::UnrollBlock::print() {
 272   ResourceMark rm;
 273   stringStream st;
 274   st.print_cr("UnrollBlock");
 275   st.print_cr("  size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
 276   st.print(   "  frame_sizes: ");
 277   for (int index = 0; index < number_of_frames(); index++) {
 278     st.print("%zd ", frame_sizes()[index]);
 279   }
 280   st.cr();
 281   tty->print_raw(st.freeze());
 282 }
 283 
 284 // In order to make fetch_unroll_info work properly with escape
 285 // analysis, the method was changed from JRT_LEAF to JRT_BLOCK_ENTRY.
 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_unrefined_objArray_klass(), "Expected unrefined array 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       ArrayProperties props(checked_cast<ArrayProperties::Type>(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(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,
 458                                                      exec_mode, realloc_failures);
 459       deoptimized_objects = deoptimized_objects || relocked;
 460 #ifndef PRODUCT
 461       if (PrintDeoptimizationDetails) {
 462         ResourceMark rm;
 463         stringStream st;
 464         for (int j = 0; j < monitors->length(); j++) {
 465           MonitorInfo* mi = monitors->at(j);
 466           if (mi->eliminated()) {
 467             if (first) {
 468               first = false;
 469               st.print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, p2i(thread));
 470             }
 471             if (exec_mode == Deoptimization::Unpack_none) {
 472               ObjectMonitor* monitor = deoptee_thread->current_waiting_monitor();
 473               if (monitor != nullptr && monitor->object() == mi->owner()) {
 474                 st.print_cr("     object <" INTPTR_FORMAT "> DEFERRED relocking after wait", p2i(mi->owner()));
 475                 continue;
 476               }
 477             }
 478             if (mi->owner_is_scalar_replaced()) {
 479               Klass* k = java_lang_Class::as_Klass(mi->owner_klass());
 480               st.print_cr("     failed reallocation for klass %s", k->external_name());
 481             } else {
 482               st.print_cr("     object <" INTPTR_FORMAT "> locked", p2i(mi->owner()));
 483             }
 484           }
 485         }
 486         tty->print_raw(st.freeze());
 487       }
 488 #endif // !PRODUCT
 489     }
 490   }
 491 }
 492 
 493 // Deoptimize objects, that is reallocate and relock them, just before they escape through JVMTI.
 494 // The given vframes cover one physical frame.
 495 bool Deoptimization::deoptimize_objects_internal(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk,
 496                                                  bool& realloc_failures) {
 497   frame deoptee = chunk->at(0)->fr();
 498   JavaThread* deoptee_thread = chunk->at(0)->thread();
 499   nmethod* nm = deoptee.cb()->as_nmethod_or_null();
 500   RegisterMap map(chunk->at(0)->register_map());
 501   bool deoptimized_objects = false;
 502 
 503   bool const jvmci_enabled = JVMCI_ONLY(EnableJVMCI) NOT_JVMCI(false);
 504 
 505   // Reallocate the non-escaping objects and restore their fields.
 506   if (jvmci_enabled COMPILER2_PRESENT(|| ((DoEscapeAnalysis || Arguments::is_valhalla_enabled()) && EliminateAllocations)
 507                                       || EliminateAutoBox || EnableVectorAggressiveReboxing)) {
 508     realloc_failures = rematerialize_objects(thread, Unpack_none, nm, deoptee, map, chunk, deoptimized_objects);
 509   }
 510 
 511   // MonitorInfo structures used in eliminate_locks are not GC safe.
 512   NoSafepointVerifier no_safepoint;
 513 
 514   // Now relock objects if synchronization on them was eliminated.
 515   if (jvmci_enabled COMPILER2_PRESENT(|| ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks))) {
 516     restore_eliminated_locks(thread, chunk, realloc_failures, deoptee, Unpack_none, deoptimized_objects);
 517   }
 518   return deoptimized_objects;
 519 }
 520 #endif // COMPILER2_OR_JVMCI
 521 
 522 // This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
 523 Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* current, int exec_mode) {
 524   JFR_ONLY(Jfr::check_and_process_sample_request(current);)
 525   // When we get here we are about to unwind the deoptee frame. In order to
 526   // catch not yet safe to use frames, the following stack watermark barrier
 527   // poll will make such frames safe to use.
 528   StackWatermarkSet::before_unwind(current);
 529 
 530   // Note: there is a safepoint safety issue here. No matter whether we enter
 531   // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once
 532   // the vframeArray is created.
 533   //
 534 
 535   // Allocate our special deoptimization ResourceMark
 536   DeoptResourceMark* dmark = new DeoptResourceMark(current);
 537   assert(current->deopt_mark() == nullptr, "Pending deopt!");
 538   current->set_deopt_mark(dmark);
 539 
 540   frame stub_frame = current->last_frame(); // Makes stack walkable as side effect
 541   RegisterMap map(current,
 542                   RegisterMap::UpdateMap::include,
 543                   RegisterMap::ProcessFrames::include,
 544                   RegisterMap::WalkContinuation::skip);
 545   RegisterMap dummy_map(current,
 546                         RegisterMap::UpdateMap::skip,
 547                         RegisterMap::ProcessFrames::include,
 548                         RegisterMap::WalkContinuation::skip);
 549   // Now get the deoptee with a valid map
 550   frame deoptee = stub_frame.sender(&map);
 551   if (exec_mode == Unpack_deopt) {
 552     assert(deoptee.is_deoptimized_frame(), "frame is not marked for deoptimization");
 553   }
 554   // Set the deoptee nmethod
 555   assert(current->deopt_compiled_method() == nullptr, "Pending deopt!");
 556   nmethod* nm = deoptee.cb()->as_nmethod_or_null();
 557   current->set_deopt_compiled_method(nm);
 558 
 559   if (VerifyStack) {
 560     current->validate_frame_layout();
 561   }
 562 
 563   // Create a growable array of VFrames where each VFrame represents an inlined
 564   // Java frame.  This storage is allocated with the usual system arena.
 565   assert(deoptee.is_compiled_frame(), "Wrong frame type");
 566   GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
 567   vframe* vf = vframe::new_vframe(&deoptee, &map, current);
 568   while (!vf->is_top()) {
 569     assert(vf->is_compiled_frame(), "Wrong frame type");
 570     chunk->push(compiledVFrame::cast(vf));
 571     vf = vf->sender();
 572   }
 573   assert(vf->is_compiled_frame(), "Wrong frame type");
 574   chunk->push(compiledVFrame::cast(vf));
 575 
 576   bool realloc_failures = false;
 577 
 578 #if COMPILER2_OR_JVMCI
 579   bool const jvmci_enabled = JVMCI_ONLY(EnableJVMCI) NOT_JVMCI(false);
 580 
 581   // Reallocate the non-escaping objects and restore their fields. Then
 582   // relock objects if synchronization on them was eliminated.
 583   if (jvmci_enabled COMPILER2_PRESENT(|| ((DoEscapeAnalysis || Arguments::is_valhalla_enabled()) && EliminateAllocations)
 584                                       || EliminateAutoBox || EnableVectorAggressiveReboxing)) {
 585     bool unused;
 586     realloc_failures = rematerialize_objects(current, exec_mode, nm, deoptee, map, chunk, unused);
 587   }
 588 #endif // COMPILER2_OR_JVMCI
 589 
 590   // Ensure that no safepoint is taken after pointers have been stored
 591   // in fields of rematerialized objects.  If a safepoint occurs from here on
 592   // out the java state residing in the vframeArray will be missed.
 593   // Locks may be rebaised in a safepoint.
 594   NoSafepointVerifier no_safepoint;
 595 
 596 #if COMPILER2_OR_JVMCI
 597   if ((jvmci_enabled COMPILER2_PRESENT( || ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks) ))
 598       && !EscapeBarrier::objs_are_deoptimized(current, deoptee.id())) {
 599     bool unused = false;
 600     restore_eliminated_locks(current, chunk, realloc_failures, deoptee, exec_mode, unused);
 601   }
 602 #endif // COMPILER2_OR_JVMCI
 603 
 604   ScopeDesc* trap_scope = chunk->at(0)->scope();
 605   Handle exceptionObject;
 606   if (trap_scope->rethrow_exception()) {
 607 #ifndef PRODUCT
 608     if (PrintDeoptimizationDetails) {
 609       tty->print_cr("Exception to be rethrown in the interpreter for method %s::%s at bci %d", trap_scope->method()->method_holder()->name()->as_C_string(), trap_scope->method()->name()->as_C_string(), trap_scope->bci());
 610     }
 611 #endif // !PRODUCT
 612 
 613     GrowableArray<ScopeValue*>* expressions = trap_scope->expressions();
 614     guarantee(expressions != nullptr && expressions->length() == 1, "should have only exception on stack");
 615     guarantee(exec_mode != Unpack_exception, "rethrow_exception set with Unpack_exception");
 616     ScopeValue* topOfStack = expressions->top();
 617     exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj();
 618     guarantee(exceptionObject() != nullptr, "exception oop can not be null");
 619   }
 620 
 621   vframeArray* array = create_vframeArray(current, deoptee, &map, chunk, realloc_failures);
 622 #if COMPILER2_OR_JVMCI
 623   if (realloc_failures) {
 624     // This destroys all ScopedValue bindings.
 625     current->clear_scopedValueBindings();
 626     pop_frames_failed_reallocs(current, array);
 627   }
 628 #endif
 629 
 630   assert(current->vframe_array_head() == nullptr, "Pending deopt!");
 631   current->set_vframe_array_head(array);
 632 
 633   // Now that the vframeArray has been created if we have any deferred local writes
 634   // added by jvmti then we can free up that structure as the data is now in the
 635   // vframeArray
 636 
 637   JvmtiDeferredUpdates::delete_updates_for_frame(current, array->original().id());
 638 
 639   // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
 640   CodeBlob* cb = stub_frame.cb();
 641   // Verify we have the right vframeArray
 642   assert(cb->frame_size() >= 0, "Unexpected frame size");
 643   intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();
 644   assert(unpack_sp == deoptee.unextended_sp(), "must be");
 645 
 646 #ifdef ASSERT
 647   assert(cb->is_deoptimization_stub() ||
 648          cb->is_uncommon_trap_stub() ||
 649          strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 ||
 650          strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0,
 651          "unexpected code blob: %s", cb->name());
 652 #endif
 653 
 654   // This is a guarantee instead of an assert because if vframe doesn't match
 655   // we will unpack the wrong deoptimized frame and wind up in strange places
 656   // where it will be very difficult to figure out what went wrong. Better
 657   // to die an early death here than some very obscure death later when the
 658   // trail is cold.
 659   guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");
 660 
 661   int number_of_frames = array->frames();
 662 
 663   // Compute the vframes' sizes.  Note that frame_sizes[] entries are ordered from outermost to innermost
 664   // virtual activation, which is the reverse of the elements in the vframes array.
 665   intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
 666   // +1 because we always have an interpreter return address for the final slot.
 667   address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
 668   int popframe_extra_args = 0;
 669   // Create an interpreter return address for the stub to use as its return
 670   // address so the skeletal frames are perfectly walkable
 671   frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);
 672 
 673   // PopFrame requires that the preserved incoming arguments from the recently-popped topmost
 674   // activation be put back on the expression stack of the caller for reexecution
 675   if (JvmtiExport::can_pop_frame() && current->popframe_forcing_deopt_reexecution()) {
 676     popframe_extra_args = in_words(current->popframe_preserved_args_size_in_words());
 677   }
 678 
 679   // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
 680   // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
 681   // than simply use array->sender.pc(). This requires us to walk the current set of frames
 682   //
 683   frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
 684   deopt_sender = deopt_sender.sender(&dummy_map);     // Now deoptee caller
 685 
 686   // It's possible that the number of parameters at the call site is
 687   // different than number of arguments in the callee when method
 688   // handles are used.  If the caller is interpreted get the real
 689   // value so that the proper amount of space can be added to it's
 690   // frame.
 691   bool caller_was_method_handle = false;
 692   if (deopt_sender.is_interpreted_frame()) {
 693     methodHandle method(current, deopt_sender.interpreter_frame_method());
 694     Bytecode_invoke cur(method, deopt_sender.interpreter_frame_bci());
 695     if (cur.has_member_arg()) {
 696       // This should cover all real-world cases.  One exception is a pathological chain of
 697       // MH.linkToXXX() linker calls, which only trusted code could do anyway.  To handle that case, we
 698       // would need to get the size from the resolved method entry.  Another exception would
 699       // be an invokedynamic with an adapter that is really a MethodHandle linker.
 700       caller_was_method_handle = true;
 701     }
 702   }
 703 
 704   //
 705   // frame_sizes/frame_pcs[0] oldest frame (int or c2i)
 706   // frame_sizes/frame_pcs[1] next oldest frame (int)
 707   // frame_sizes/frame_pcs[n] youngest frame (int)
 708   //
 709   // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
 710   // owns the space for the return address to it's caller).  Confusing ain't it.
 711   //
 712   // The vframe array can address vframes with indices running from
 713   // 0.._frames-1. Index  0 is the youngest frame and _frame - 1 is the oldest (root) frame.
 714   // When we create the skeletal frames we need the oldest frame to be in the zero slot
 715   // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
 716   // so things look a little strange in this loop.
 717   //
 718   int callee_parameters = 0;
 719   int callee_locals = 0;
 720   for (int index = 0; index < array->frames(); index++ ) {
 721     // frame[number_of_frames - 1 ] = on_stack_size(youngest)
 722     // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
 723     // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
 724     frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,
 725                                                                                                     callee_locals,
 726                                                                                                     index == 0,
 727                                                                                                     popframe_extra_args);
 728     // This pc doesn't have to be perfect just good enough to identify the frame
 729     // as interpreted so the skeleton frame will be walkable
 730     // The correct pc will be set when the skeleton frame is completely filled out
 731     // The final pc we store in the loop is wrong and will be overwritten below
 732     frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;
 733 
 734     callee_parameters = array->element(index)->method()->size_of_parameters();
 735     callee_locals = array->element(index)->method()->max_locals();
 736     popframe_extra_args = 0;
 737   }
 738 
 739   // Compute whether the root vframe returns a float or double value.
 740   BasicType return_type;
 741   {
 742     methodHandle method(current, array->element(0)->method());
 743     Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
 744     return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
 745   }
 746 
 747   // Compute information for handling adapters and adjusting the frame size of the caller.
 748   int caller_adjustment = 0;
 749 
 750   // Compute the amount the oldest interpreter frame will have to adjust
 751   // its caller's stack by. If the caller is a compiled frame then
 752   // we pretend that the callee has no parameters so that the
 753   // extension counts for the full amount of locals and not just
 754   // locals-parms. This is because without a c2i adapter the parm
 755   // area as created by the compiled frame will not be usable by
 756   // the interpreter. (Depending on the calling convention there
 757   // may not even be enough space).
 758 
 759   // QQQ I'd rather see this pushed down into last_frame_adjust
 760   // and have it take the sender (aka caller).
 761 
 762   if (!deopt_sender.is_interpreted_frame() || caller_was_method_handle) {
 763     caller_adjustment = last_frame_adjust(0, callee_locals);
 764   } else if (callee_locals > callee_parameters) {
 765     // The caller frame may need extending to accommodate
 766     // non-parameter locals of the first unpacked interpreted frame.
 767     // Compute that adjustment.
 768     caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
 769   }
 770 
 771   // If the sender is deoptimized we must retrieve the address of the handler
 772   // since the frame will "magically" show the original pc before the deopt
 773   // and we'd undo the deopt.
 774 
 775   frame_pcs[0] = Continuation::is_cont_barrier_frame(deoptee) ? StubRoutines::cont_returnBarrier() : deopt_sender.raw_pc();
 776   if (Continuation::is_continuation_enterSpecial(deopt_sender)) {
 777     ContinuationEntry::from_frame(deopt_sender)->set_argsize(0);
 778   }
 779 
 780   assert(CodeCache::find_blob(frame_pcs[0]) != nullptr, "bad pc");
 781 
 782 #if INCLUDE_JVMCI
 783   if (exceptionObject() != nullptr) {
 784     current->set_exception_oop(exceptionObject());
 785     exec_mode = Unpack_exception;
 786     assert(array->element(0)->rethrow_exception(), "must be");
 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());
 793     current->clear_pending_exception();
 794     exec_mode = Unpack_exception;
 795   }
 796 
 797 #if INCLUDE_JVMCI
 798   if (current->frames_to_pop_failed_realloc() > 0) {
 799     current->set_pending_monitorenter(false);
 800   }
 801 #endif
 802 
 803   int caller_actual_parameters = -1; // value not used except for interpreted frames, see below
 804   if (deopt_sender.is_interpreted_frame()) {
 805     caller_actual_parameters = callee_parameters + (caller_was_method_handle ? 1 : 0);
 806   }
 807 
 808   UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
 809                                       caller_adjustment * BytesPerWord,
 810                                       caller_actual_parameters,
 811                                       number_of_frames,
 812                                       frame_sizes,
 813                                       frame_pcs,
 814                                       return_type,
 815                                       exec_mode);
 816   // On some platforms, we need a way to pass some platform dependent
 817   // information to the unpacking code so the skeletal frames come out
 818   // correct (initial fp value, unextended sp, ...)
 819   info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
 820 
 821   if (array->frames() > 1) {
 822     if (VerifyStack && TraceDeoptimization) {
 823       tty->print_cr("Deoptimizing method containing inlining");
 824     }
 825   }
 826 
 827   array->set_unroll_block(info);
 828   return info;
 829 }
 830 
 831 // Called to cleanup deoptimization data structures in normal case
 832 // after unpacking to stack and when stack overflow error occurs
 833 void Deoptimization::cleanup_deopt_info(JavaThread *thread,
 834                                         vframeArray *array) {
 835 
 836   // Get array if coming from exception
 837   if (array == nullptr) {
 838     array = thread->vframe_array_head();
 839   }
 840   thread->set_vframe_array_head(nullptr);
 841 
 842   // Free the previous UnrollBlock
 843   vframeArray* old_array = thread->vframe_array_last();
 844   thread->set_vframe_array_last(array);
 845 
 846   if (old_array != nullptr) {
 847     UnrollBlock* old_info = old_array->unroll_block();
 848     old_array->set_unroll_block(nullptr);
 849     delete old_info;
 850     delete old_array;
 851   }
 852 
 853   // Deallocate any resource creating in this routine and any ResourceObjs allocated
 854   // inside the vframeArray (StackValueCollections)
 855 
 856   delete thread->deopt_mark();
 857   thread->set_deopt_mark(nullptr);
 858   thread->set_deopt_compiled_method(nullptr);
 859 
 860 
 861   if (JvmtiExport::can_pop_frame()) {
 862     // Regardless of whether we entered this routine with the pending
 863     // popframe condition bit set, we should always clear it now
 864     thread->clear_popframe_condition();
 865   }
 866 
 867   // unpack_frames() is called at the end of the deoptimization handler
 868   // and (in C2) at the end of the uncommon trap handler. Note this fact
 869   // so that an asynchronous stack walker can work again. This counter is
 870   // incremented at the beginning of fetch_unroll_info() and (in C2) at
 871   // the beginning of uncommon_trap().
 872   thread->dec_in_deopt_handler();
 873 }
 874 
 875 // Moved from cpu directories because none of the cpus has callee save values.
 876 // If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp.
 877 void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) {
 878 
 879   // This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in
 880   // the days we had adapter frames. When we deoptimize a situation where a
 881   // compiled caller calls a compiled caller will have registers it expects
 882   // to survive the call to the callee. If we deoptimize the callee the only
 883   // way we can restore these registers is to have the oldest interpreter
 884   // frame that we create restore these values. That is what this routine
 885   // will accomplish.
 886 
 887   // At the moment we have modified c2 to not have any callee save registers
 888   // so this problem does not exist and this routine is just a place holder.
 889 
 890   assert(f->is_interpreted_frame(), "must be interpreted");
 891 }
 892 
 893 #ifndef PRODUCT
 894 #ifdef ASSERT
 895 // Return true if the execution after the provided bytecode continues at the
 896 // next bytecode in the code. This is not the case for gotos, returns, and
 897 // throws.
 898 static bool falls_through(Bytecodes::Code bc) {
 899   switch (bc) {
 900     case Bytecodes::_goto:
 901     case Bytecodes::_goto_w:
 902     case Bytecodes::_athrow:
 903     case Bytecodes::_areturn:
 904     case Bytecodes::_dreturn:
 905     case Bytecodes::_freturn:
 906     case Bytecodes::_ireturn:
 907     case Bytecodes::_lreturn:
 908     case Bytecodes::_jsr:
 909     case Bytecodes::_ret:
 910     case Bytecodes::_return:
 911     case Bytecodes::_lookupswitch:
 912     case Bytecodes::_tableswitch:
 913       return false;
 914     default:
 915       return true;
 916   }
 917 }
 918 #endif
 919 #endif
 920 
 921 // Return BasicType of value being returned
 922 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
 923   assert(thread == JavaThread::current(), "pre-condition");
 924 
 925   // We are already active in the special DeoptResourceMark any ResourceObj's we
 926   // allocate will be freed at the end of the routine.
 927 
 928   // JRT_LEAF methods don't normally allocate handles and there is a
 929   // NoHandleMark to enforce that. It is actually safe to use Handles
 930   // in a JRT_LEAF method, and sometimes desirable, but to do so we
 931   // must use ResetNoHandleMark to bypass the NoHandleMark, and
 932   // then use a HandleMark to ensure any Handles we do create are
 933   // cleaned up in this scope.
 934   ResetNoHandleMark rnhm;
 935   HandleMark hm(thread);
 936 
 937   frame stub_frame = thread->last_frame();
 938 
 939   Continuation::notify_deopt(thread, stub_frame.sp());
 940 
 941   // Since the frame to unpack is the top frame of this thread, the vframe_array_head
 942   // must point to the vframeArray for the unpack frame.
 943   vframeArray* array = thread->vframe_array_head();
 944   UnrollBlock* info = array->unroll_block();
 945 
 946   // We set the last_Java frame. But the stack isn't really parsable here. So we
 947   // clear it to make sure JFR understands not to try and walk stacks from events
 948   // in here.
 949   intptr_t* sp = thread->frame_anchor()->last_Java_sp();
 950   thread->frame_anchor()->set_last_Java_sp(nullptr);
 951 
 952   // Unpack the interpreter frames and any adapter frame (c2 only) we might create.
 953   array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
 954 
 955   thread->frame_anchor()->set_last_Java_sp(sp);
 956 
 957   BasicType bt = info->return_type();
 958 
 959   // If we have an exception pending, claim that the return type is an oop
 960   // so the deopt_blob does not overwrite the exception_oop.
 961 
 962   if (exec_mode == Unpack_exception)
 963     bt = T_OBJECT;
 964 
 965   // Cleanup thread deopt data
 966   cleanup_deopt_info(thread, array);
 967 
 968 #ifndef PRODUCT
 969   if (VerifyStack) {
 970     ResourceMark res_mark;
 971     // Clear pending exception to not break verification code (restored afterwards)
 972     PreserveExceptionMark pm(thread);
 973 
 974     thread->validate_frame_layout();
 975 
 976     // Verify that the just-unpacked frames match the interpreter's
 977     // notions of expression stack and locals
 978     vframeArray* cur_array = thread->vframe_array_last();
 979     RegisterMap rm(thread,
 980                    RegisterMap::UpdateMap::skip,
 981                    RegisterMap::ProcessFrames::include,
 982                    RegisterMap::WalkContinuation::skip);
 983     rm.set_include_argument_oops(false);
 984     int callee_size_of_parameters = 0;
 985     for (int frame_idx = 0; frame_idx < cur_array->frames(); frame_idx++) {
 986       bool is_top_frame = (frame_idx == 0);
 987       vframeArrayElement* el = cur_array->element(frame_idx);
 988       frame* iframe = el->iframe();
 989       guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
 990       methodHandle mh(thread, iframe->interpreter_frame_method());
 991       bool reexecute = el->should_reexecute();
 992 
 993       int cur_invoke_parameter_size = 0;
 994       int top_frame_expression_stack_adjustment = 0;
 995       int max_bci = mh->code_size();
 996       BytecodeStream str(mh, iframe->interpreter_frame_bci());
 997       assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
 998       Bytecodes::Code cur_code = str.next();
 999 
1000       if (!reexecute && !Bytecodes::is_invoke(cur_code)) {
1001         // We can only compute OopMaps for the before state, so we need to roll forward
1002         // to the next bytecode.
1003         assert(is_top_frame, "must be");
1004         assert(falls_through(cur_code), "must be");
1005         assert(cur_code != Bytecodes::_illegal, "illegal bytecode");
1006         assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
1007 
1008         // Need to subtract off the size of the result type of
1009         // the bytecode because this is not described in the
1010         // debug info but returned to the interpreter in the TOS
1011         // caching register
1012         BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
1013         if (bytecode_result_type != T_ILLEGAL) {
1014           top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
1015         }
1016         assert(top_frame_expression_stack_adjustment >= 0, "stack adjustment must be positive");
1017 
1018         cur_code = str.next();
1019         // Reflect the fact that we have rolled forward and now need
1020         // top_frame_expression_stack_adjustment
1021         reexecute = true;
1022       }
1023 
1024       assert(cur_code != Bytecodes::_illegal, "illegal bytecode");
1025       assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
1026 
1027       // Get the oop map for this bci
1028       InterpreterOopMap mask;
1029       OopMapCache::compute_one_oop_map(mh, str.bci(), &mask);
1030       // Check to see if we can grab the number of outgoing arguments
1031       // at an uncommon trap for an invoke (where the compiler
1032       // generates debug info before the invoke has executed)
1033       if (Bytecodes::is_invoke(cur_code)) {
1034         Bytecode_invoke invoke(mh, str.bci());
1035         cur_invoke_parameter_size = invoke.size_of_parameters();
1036         if (!is_top_frame && invoke.has_member_arg()) {
1037           callee_size_of_parameters++;
1038         }
1039       }
1040 
1041       // Verify stack depth and oops in frame
1042       auto match = [&]() {
1043         int iframe_expr_ssize = iframe->interpreter_frame_expression_stack_size();
1044 #if INCLUDE_JVMCI
1045         if (is_top_frame && el->rethrow_exception()) {
1046           return iframe_expr_ssize == 1;
1047         }
1048 #endif
1049         // This should only be needed for C1
1050         if (is_top_frame && exec_mode == Unpack_exception && iframe_expr_ssize == 0) {
1051           return true;
1052         }
1053         if (reexecute) {
1054           int expr_ssize_before = iframe_expr_ssize + top_frame_expression_stack_adjustment;
1055           int oopmap_expr_invoke_ssize = mask.expression_stack_size() + cur_invoke_parameter_size;
1056           return expr_ssize_before == oopmap_expr_invoke_ssize;
1057         } else {
1058           int oopmap_expr_callee_ssize = mask.expression_stack_size() + callee_size_of_parameters;
1059           return iframe_expr_ssize == oopmap_expr_callee_ssize;
1060         }
1061       };
1062       if (!match()) {
1063         // Print out some information that will help us debug the problem
1064         tty->print_cr("Wrong number of expression stack elements during deoptimization");
1065         tty->print_cr("  Error occurred while verifying frame %d (0..%d, 0 is topmost)", frame_idx, cur_array->frames() - 1);
1066         tty->print_cr("  Current code %s", Bytecodes::name(cur_code));
1067         tty->print_cr("  Fabricated interpreter frame had %d expression stack elements",
1068                       iframe->interpreter_frame_expression_stack_size());
1069         tty->print_cr("  Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
1070         tty->print_cr("  callee_size_of_parameters = %d", callee_size_of_parameters);
1071         tty->print_cr("  top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
1072         tty->print_cr("  exec_mode = %d", exec_mode);
1073         tty->print_cr("  original should_reexecute = %s", el->should_reexecute() ? "true" : "false");
1074         tty->print_cr("  reexecute = %s%s", reexecute ? "true" : "false",
1075                       (reexecute != el->should_reexecute()) ? " (changed)" : "");
1076 #if INCLUDE_JVMCI
1077         tty->print_cr("  rethrow_exception = %s", el->rethrow_exception() ? "true" : "false");
1078 #endif
1079         tty->print_cr("  cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
1080         tty->print_cr("  Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id());
1081         tty->print_cr("  Interpreted frames:");
1082         for (int k = 0; k < cur_array->frames(); k++) {
1083           vframeArrayElement* el = cur_array->element(k);
1084           tty->print_cr("    %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
1085         }
1086         cur_array->print_on_2(tty);
1087         guarantee(false, "wrong number of expression stack elements during deopt");
1088       }
1089       VerifyOopClosure verify;
1090       iframe->oops_interpreted_do(&verify, &rm, false);
1091       callee_size_of_parameters = mh->size_of_parameters();
1092     }
1093   }
1094 #endif // !PRODUCT
1095 
1096   return bt;
1097 JRT_END
1098 
1099 class DeoptimizeMarkedHandshakeClosure : public HandshakeClosure {
1100  public:
1101   DeoptimizeMarkedHandshakeClosure() : HandshakeClosure("Deoptimize") {}
1102   void do_thread(Thread* thread) {
1103     JavaThread* jt = JavaThread::cast(thread);
1104     jt->deoptimize_marked_methods();
1105   }
1106 };
1107 
1108 void Deoptimization::deoptimize_all_marked() {
1109   ResourceMark rm;
1110 
1111   // Make the dependent methods not entrant
1112   CodeCache::make_marked_nmethods_deoptimized();
1113 
1114   DeoptimizeMarkedHandshakeClosure deopt;
1115   if (SafepointSynchronize::is_at_safepoint()) {
1116     Threads::java_threads_do(&deopt);
1117   } else {
1118     Handshake::execute(&deopt);
1119   }
1120 }
1121 
1122 Deoptimization::DeoptAction Deoptimization::_unloaded_action
1123   = Deoptimization::Action_reinterpret;
1124 
1125 #if INCLUDE_JVMCI
1126 template<typename CacheType>
1127 class BoxCacheBase : public CHeapObj<mtCompiler> {
1128 protected:
1129   static InstanceKlass* find_cache_klass(Thread* thread, Symbol* klass_name) {
1130     ResourceMark rm(thread);
1131     char* klass_name_str = klass_name->as_C_string();
1132     InstanceKlass* ik = SystemDictionary::find_instance_klass(thread, klass_name, Handle());
1133     guarantee(ik != nullptr, "%s must be loaded", klass_name_str);
1134     if (!ik->is_in_error_state()) {
1135       guarantee(ik->is_initialized(), "%s must be initialized", klass_name_str);
1136       CacheType::compute_offsets(ik);
1137     }
1138     return ik;
1139   }
1140 };
1141 
1142 template<typename PrimitiveType, typename CacheType, typename BoxType> class BoxCache  : public BoxCacheBase<CacheType> {
1143   PrimitiveType _low;
1144   PrimitiveType _high;
1145   jobject _cache;
1146 protected:
1147   static BoxCache<PrimitiveType, CacheType, BoxType> *_singleton;
1148   BoxCache(Thread* thread) {
1149     assert(!Arguments::is_valhalla_enabled(), "Should not use box caches with enable preview");
1150     InstanceKlass* ik = BoxCacheBase<CacheType>::find_cache_klass(thread, CacheType::symbol());
1151     if (ik->is_in_error_state()) {
1152       _low = 1;
1153       _high = 0;
1154       _cache = nullptr;
1155     } else {
1156       refArrayOop cache = CacheType::cache(ik);
1157       assert(cache->length() > 0, "Empty cache");
1158       _low = BoxType::value(cache->obj_at(0));
1159       _high = checked_cast<PrimitiveType>(_low + cache->length() - 1);
1160       _cache = JNIHandles::make_global(Handle(thread, cache));
1161     }
1162   }
1163   ~BoxCache() {
1164     JNIHandles::destroy_global(_cache);
1165   }
1166 public:
1167   static BoxCache<PrimitiveType, CacheType, BoxType>* singleton(Thread* thread) {
1168     if (_singleton == nullptr) {
1169       BoxCache<PrimitiveType, CacheType, BoxType>* s = new BoxCache<PrimitiveType, CacheType, BoxType>(thread);
1170       if (!AtomicAccess::replace_if_null(&_singleton, s)) {
1171         delete s;
1172       }
1173     }
1174     return _singleton;
1175   }
1176   oop lookup(PrimitiveType value) {
1177     if (_low <= value && value <= _high) {
1178       int offset = checked_cast<int>(value - _low);
1179       return refArrayOop(JNIHandles::resolve_non_null(_cache))->obj_at(offset);
1180     }
1181     return nullptr;
1182   }
1183   oop lookup_raw(intptr_t raw_value, bool& cache_init_error) {
1184     if (_cache == nullptr) {
1185       cache_init_error = true;
1186       return nullptr;
1187     }
1188     // Have to cast to avoid little/big-endian problems.
1189     if (sizeof(PrimitiveType) > sizeof(jint)) {
1190       jlong value = (jlong)raw_value;
1191       return lookup(value);
1192     }
1193     PrimitiveType value = (PrimitiveType)*((jint*)&raw_value);
1194     return lookup(value);
1195   }
1196 };
1197 
1198 typedef BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer> IntegerBoxCache;
1199 typedef BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long> LongBoxCache;
1200 typedef BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character> CharacterBoxCache;
1201 typedef BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short> ShortBoxCache;
1202 typedef BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte> ByteBoxCache;
1203 
1204 template<> BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>* BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>::_singleton = nullptr;
1205 template<> BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>* BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>::_singleton = nullptr;
1206 template<> BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>* BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>::_singleton = nullptr;
1207 template<> BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>* BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>::_singleton = nullptr;
1208 template<> BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>* BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>::_singleton = nullptr;
1209 
1210 class BooleanBoxCache : public BoxCacheBase<java_lang_Boolean> {
1211   jobject _true_cache;
1212   jobject _false_cache;
1213 protected:
1214   static BooleanBoxCache *_singleton;
1215   BooleanBoxCache(Thread *thread) {
1216     InstanceKlass* ik = find_cache_klass(thread, java_lang_Boolean::symbol());
1217     if (ik->is_in_error_state()) {
1218       _true_cache = nullptr;
1219       _false_cache = nullptr;
1220     } else {
1221       _true_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_TRUE(ik)));
1222       _false_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_FALSE(ik)));
1223     }
1224   }
1225   ~BooleanBoxCache() {
1226     JNIHandles::destroy_global(_true_cache);
1227     JNIHandles::destroy_global(_false_cache);
1228   }
1229 public:
1230   static BooleanBoxCache* singleton(Thread* thread) {
1231     if (_singleton == nullptr) {
1232       BooleanBoxCache* s = new BooleanBoxCache(thread);
1233       if (!AtomicAccess::replace_if_null(&_singleton, s)) {
1234         delete s;
1235       }
1236     }
1237     return _singleton;
1238   }
1239   oop lookup_raw(intptr_t raw_value, bool& cache_in_error) {
1240     if (_true_cache == nullptr) {
1241       cache_in_error = true;
1242       return nullptr;
1243     }
1244     // Have to cast to avoid little/big-endian problems.
1245     jboolean value = (jboolean)*((jint*)&raw_value);
1246     return lookup(value);
1247   }
1248   oop lookup(jboolean value) {
1249     if (value != 0) {
1250       return JNIHandles::resolve_non_null(_true_cache);
1251     }
1252     return JNIHandles::resolve_non_null(_false_cache);
1253   }
1254 };
1255 
1256 BooleanBoxCache* BooleanBoxCache::_singleton = nullptr;
1257 
1258 oop Deoptimization::get_cached_box(AutoBoxObjectValue* bv, frame* fr, RegisterMap* reg_map, bool& cache_init_error, TRAPS) {
1259   if (Arguments::enable_preview()) {
1260     // Box caches are not used with enable preview.
1261     return nullptr;
1262   }
1263    Klass* k = java_lang_Class::as_Klass(bv->klass()->as_ConstantOopReadValue()->value()());
1264    BasicType box_type = vmClasses::box_klass_type(k);
1265    if (box_type != T_OBJECT) {
1266      StackValue* value = StackValue::create_stack_value(fr, reg_map, bv->field_at(box_type == T_LONG ? 1 : 0));
1267      switch(box_type) {
1268        case T_INT:     return IntegerBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1269        case T_CHAR:    return CharacterBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1270        case T_SHORT:   return ShortBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1271        case T_BYTE:    return ByteBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1272        case T_BOOLEAN: return BooleanBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1273        case T_LONG:    return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_intptr(), cache_init_error);
1274        default:;
1275      }
1276    }
1277    return nullptr;
1278 }
1279 #endif // INCLUDE_JVMCI
1280 
1281 #if COMPILER2_OR_JVMCI
1282 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {
1283   Handle pending_exception(THREAD, thread->pending_exception());
1284   const char* exception_file = thread->exception_file();
1285   int exception_line = thread->exception_line();
1286   thread->clear_pending_exception();
1287 
1288   bool failures = false;
1289 
1290   for (int i = 0; i < objects->length(); i++) {
1291     assert(objects->at(i)->is_object(), "invalid debug information");
1292     ObjectValue* sv = (ObjectValue*) objects->at(i);
1293 
1294     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1295 
1296     k = get_refined_array_klass(k, fr, reg_map, sv, THREAD);
1297 
1298     // Check if the object may be null and has an additional null_marker input that needs
1299     // to be checked before using the field values. Skip re-allocation if it is null.
1300     if (k->is_inline_klass() && sv->has_properties()) {
1301       jint null_marker = StackValue::create_stack_value(fr, reg_map, sv->properties())->get_jint();
1302       if (null_marker == 0) {
1303         continue;
1304       }
1305     }
1306 
1307     oop obj = nullptr;
1308     bool cache_init_error = false;
1309     if (k->is_instance_klass()) {
1310 #if INCLUDE_JVMCI
1311       nmethod* nm = fr->cb()->as_nmethod_or_null();
1312       if (nm->is_compiled_by_jvmci() && sv->is_auto_box()) {
1313         AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv;
1314         obj = get_cached_box(abv, fr, reg_map, cache_init_error, THREAD);
1315         if (obj != nullptr) {
1316           // Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it.
1317           abv->set_cached(true);
1318         } else if (cache_init_error) {
1319           // Results in an OOME which is valid (as opposed to a class initialization error)
1320           // and is fine for the rare case a cache initialization failing.
1321           failures = true;
1322         }
1323       }
1324 #endif // INCLUDE_JVMCI
1325 
1326       InstanceKlass* ik = InstanceKlass::cast(k);
1327       if (obj == nullptr && !cache_init_error) {
1328         InternalOOMEMark iom(THREAD);
1329         if (EnableVectorSupport && VectorSupport::is_vector(ik)) {
1330           obj = VectorSupport::allocate_vector(ik, fr, reg_map, sv, THREAD);
1331         } else {
1332           obj = ik->allocate_instance(THREAD);
1333         }
1334       }
1335     } else if (k->is_flatArray_klass()) {
1336       FlatArrayKlass* ak = FlatArrayKlass::cast(k);
1337       // Inline type array must be zeroed because not all memory is reassigned
1338       InternalOOMEMark iom(THREAD);
1339       obj = ak->allocate_instance(sv->field_size(), THREAD);
1340     } else if (k->is_typeArray_klass()) {
1341       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1342       assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
1343       int len = sv->field_size() / type2size[ak->element_type()];
1344       InternalOOMEMark iom(THREAD);
1345       obj = ak->allocate_instance(len, THREAD);
1346     } else if (k->is_refArray_klass()) {
1347       RefArrayKlass* ak = RefArrayKlass::cast(k);
1348       InternalOOMEMark iom(THREAD);
1349       obj = ak->allocate_instance(sv->field_size(), THREAD);
1350     }
1351 
1352     if (obj == nullptr) {
1353       failures = true;
1354     }
1355 
1356     assert(sv->value().is_null(), "redundant reallocation");
1357     assert(obj != nullptr || HAS_PENDING_EXCEPTION || cache_init_error, "allocation should succeed or we should get an exception");
1358     CLEAR_PENDING_EXCEPTION;
1359     sv->set_value(obj);
1360   }
1361 
1362   if (failures) {
1363     THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
1364   } else if (pending_exception.not_null()) {
1365     thread->set_pending_exception(pending_exception(), exception_file, exception_line);
1366   }
1367 
1368   return failures;
1369 }
1370 
1371 // We're deoptimizing at the return of a call, inline type fields are
1372 // in registers. When we go back to the interpreter, it will expect a
1373 // reference to an inline type instance. Allocate and initialize it from
1374 // the register values here.
1375 bool Deoptimization::realloc_inline_type_result(InlineKlass* vk, const RegisterMap& map, GrowableArray<Handle>& return_oops, TRAPS) {
1376   oop new_vt = vk->realloc_result(map, return_oops, THREAD);
1377   if (new_vt == nullptr) {
1378     CLEAR_PENDING_EXCEPTION;
1379     THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), true);
1380   }
1381   return_oops.clear();
1382   return_oops.push(Handle(THREAD, new_vt));
1383   return false;
1384 }
1385 
1386 #if INCLUDE_JVMCI
1387 /**
1388  * For primitive types whose kind gets "erased" at runtime (shorts become stack ints),
1389  * we need to somehow be able to recover the actual kind to be able to write the correct
1390  * amount of bytes.
1391  * For that purpose, this method assumes that, for an entry spanning n bytes at index i,
1392  * the entries at index n + 1 to n + i are 'markers'.
1393  * For example, if we were writing a short at index 4 of a byte array of size 8, the
1394  * expected form of the array would be:
1395  *
1396  * {b0, b1, b2, b3, INT, marker, b6, b7}
1397  *
1398  * Thus, in order to get back the size of the entry, we simply need to count the number
1399  * of marked entries
1400  *
1401  * @param virtualArray the virtualized byte array
1402  * @param i index of the virtual entry we are recovering
1403  * @return The number of bytes the entry spans
1404  */
1405 static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) {
1406   int index = i;
1407   while (++index < virtualArray->field_size() &&
1408            virtualArray->field_at(index)->is_marker()) {}
1409   return index - i;
1410 }
1411 
1412 /**
1413  * If there was a guarantee for byte array to always start aligned to a long, we could
1414  * do a simple check on the parity of the index. Unfortunately, that is not always the
1415  * case. Thus, we check alignment of the actual address we are writing to.
1416  * In the unlikely case index 0 is 5-aligned for example, it would then be possible to
1417  * write a long to index 3.
1418  */
1419 static jbyte* check_alignment_get_addr(typeArrayOop obj, int index, int expected_alignment) {
1420     jbyte* res = obj->byte_at_addr(index);
1421     assert((((intptr_t) res) % expected_alignment) == 0, "Non-aligned write");
1422     return res;
1423 }
1424 
1425 static void byte_array_put(typeArrayOop obj, StackValue* value, int index, int byte_count) {
1426   switch (byte_count) {
1427     case 1:
1428       obj->byte_at_put(index, (jbyte) value->get_jint());
1429       break;
1430     case 2:
1431       *((jshort *) check_alignment_get_addr(obj, index, 2)) = (jshort) value->get_jint();
1432       break;
1433     case 4:
1434       *((jint *) check_alignment_get_addr(obj, index, 4)) = value->get_jint();
1435       break;
1436     case 8:
1437       *((jlong *) check_alignment_get_addr(obj, index, 8)) = (jlong) value->get_intptr();
1438       break;
1439     default:
1440       ShouldNotReachHere();
1441   }
1442 }
1443 #endif // INCLUDE_JVMCI
1444 
1445 
1446 // restore elements of an eliminated type array
1447 void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
1448   int index = 0;
1449 
1450   for (int i = 0; i < sv->field_size(); i++) {
1451     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1452     switch(type) {
1453     case T_LONG: case T_DOUBLE: {
1454       assert(value->type() == T_INT, "Agreement.");
1455       StackValue* low =
1456         StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1457 #ifdef _LP64
1458       jlong res = (jlong)low->get_intptr();
1459 #else
1460       jlong res = jlong_from(value->get_jint(), low->get_jint());
1461 #endif
1462       obj->long_at_put(index, res);
1463       break;
1464     }
1465 
1466     case T_INT: case T_FLOAT: { // 4 bytes.
1467       assert(value->type() == T_INT, "Agreement.");
1468 #if INCLUDE_JVMCI
1469       // big_value allows encoding double/long value as e.g. [int = 0, long], and storing
1470       // the value in two array elements.
1471       bool big_value = false;
1472       if (i + 1 < sv->field_size() && type == T_INT) {
1473         if (sv->field_at(i)->is_location()) {
1474           Location::Type type = ((LocationValue*) sv->field_at(i))->location().type();
1475           if (type == Location::dbl || type == Location::lng) {
1476             big_value = true;
1477           }
1478         } else if (sv->field_at(i)->is_constant_int()) {
1479           ScopeValue* next_scope_field = sv->field_at(i + 1);
1480           if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1481             big_value = true;
1482           }
1483         }
1484       }
1485 
1486       if (big_value) {
1487         StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1488   #ifdef _LP64
1489         jlong res = (jlong)low->get_intptr();
1490   #else
1491         jlong res = jlong_from(value->get_jint(), low->get_jint());
1492   #endif
1493         obj->int_at_put(index, *(jint*)&res);
1494         obj->int_at_put(++index, *((jint*)&res + 1));
1495       } else {
1496         obj->int_at_put(index, value->get_jint());
1497       }
1498 #else // not INCLUDE_JVMCI
1499       obj->int_at_put(index, value->get_jint());
1500 #endif // INCLUDE_JVMCI
1501       break;
1502     }
1503 
1504     case T_SHORT:
1505       assert(value->type() == T_INT, "Agreement.");
1506       obj->short_at_put(index, (jshort)value->get_jint());
1507       break;
1508 
1509     case T_CHAR:
1510       assert(value->type() == T_INT, "Agreement.");
1511       obj->char_at_put(index, (jchar)value->get_jint());
1512       break;
1513 
1514     case T_BYTE: {
1515       assert(value->type() == T_INT, "Agreement.");
1516 #if INCLUDE_JVMCI
1517       // The value we get is erased as a regular int. We will need to find its actual byte count 'by hand'.
1518       int byte_count = count_number_of_bytes_for_entry(sv, i);
1519       byte_array_put(obj, value, index, byte_count);
1520       // According to byte_count contract, the values from i + 1 to i + byte_count are illegal values. Skip.
1521       i += byte_count - 1; // Balance the loop counter.
1522       index += byte_count;
1523       // index has been updated so continue at top of loop
1524       continue;
1525 #else
1526       obj->byte_at_put(index, (jbyte)value->get_jint());
1527       break;
1528 #endif // INCLUDE_JVMCI
1529     }
1530 
1531     case T_BOOLEAN: {
1532       assert(value->type() == T_INT, "Agreement.");
1533       obj->bool_at_put(index, (jboolean)value->get_jint());
1534       break;
1535     }
1536 
1537       default:
1538         ShouldNotReachHere();
1539     }
1540     index++;
1541   }
1542 }
1543 
1544 // restore fields of an eliminated object array
1545 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
1546   for (int i = 0; i < sv->field_size(); i++) {
1547     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1548     assert(value->type() == T_OBJECT, "object element expected");
1549     obj->obj_at_put(i, value->get_obj()());
1550   }
1551 }
1552 
1553 class ReassignedField {
1554 public:
1555   int _offset;
1556   BasicType _type;
1557   InstanceKlass* _klass;
1558   bool _is_flat;
1559   bool _is_null_free;
1560 public:
1561   ReassignedField() : _offset(0), _type(T_ILLEGAL), _klass(nullptr), _is_flat(false), _is_null_free(false) { }
1562 };
1563 
1564 // Gets the fields of `klass` that are eliminated by escape analysis and need to be reassigned
1565 static GrowableArray<ReassignedField>* get_reassigned_fields(InstanceKlass* klass, GrowableArray<ReassignedField>* fields, bool is_jvmci) {
1566   InstanceKlass* super = klass->super();
1567   if (super != nullptr) {
1568     get_reassigned_fields(super, fields, is_jvmci);
1569   }
1570   for (AllFieldStream fs(klass); !fs.done(); fs.next()) {
1571     if (!fs.access_flags().is_static() && (is_jvmci || !fs.field_flags().is_injected())) {
1572       ReassignedField field;
1573       field._offset = fs.offset();
1574       field._type = Signature::basic_type(fs.signature());
1575       if (fs.is_flat()) {
1576         field._is_flat = true;
1577         field._is_null_free = fs.is_null_free_inline_type();
1578         // Resolve klass of flat inline type field
1579         field._klass = InlineKlass::cast(klass->get_inline_type_field_klass(fs.index()));
1580       }
1581       fields->append(field);
1582     }
1583   }
1584   return fields;
1585 }
1586 
1587 // Restore fields of an eliminated instance object employing the same field order used by the
1588 // compiler when it scalarizes an object at safepoints.
1589 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) {
1590   GrowableArray<ReassignedField>* fields = get_reassigned_fields(klass, new GrowableArray<ReassignedField>(), is_jvmci);
1591   for (int i = 0; i < fields->length(); i++) {
1592     BasicType type = fields->at(i)._type;
1593     int offset = base_offset + fields->at(i)._offset;
1594     // Check for flat inline type field before accessing the ScopeValue because it might not have any fields
1595     if (fields->at(i)._is_flat) {
1596       // Recursively re-assign flat inline type fields
1597       InstanceKlass* vk = fields->at(i)._klass;
1598       assert(vk != nullptr, "must be resolved");
1599       offset -= InlineKlass::cast(vk)->payload_offset(); // Adjust offset to omit oop header
1600       svIndex = reassign_fields_by_klass(vk, fr, reg_map, sv, svIndex, obj, is_jvmci, offset, CHECK_0);
1601       if (!fields->at(i)._is_null_free) {
1602         ScopeValue* scope_field = sv->field_at(svIndex);
1603         StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1604         int nm_offset = offset + InlineKlass::cast(vk)->null_marker_offset();
1605         obj->bool_field_put(nm_offset, value->get_jint() & 1);
1606         svIndex++;
1607       }
1608       continue; // Continue because we don't need to increment svIndex
1609     }
1610 
1611     ScopeValue* scope_field = sv->field_at(svIndex);
1612     StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1613     switch (type) {
1614       case T_OBJECT: case T_ARRAY:
1615         assert(value->type() == T_OBJECT, "Agreement.");
1616         obj->obj_field_put(offset, value->get_obj()());
1617         break;
1618 
1619       case T_INT: case T_FLOAT: { // 4 bytes.
1620         assert(value->type() == T_INT, "Agreement.");
1621         bool big_value = false;
1622         if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {
1623           if (scope_field->is_location()) {
1624             Location::Type type = ((LocationValue*) scope_field)->location().type();
1625             if (type == Location::dbl || type == Location::lng) {
1626               big_value = true;
1627             }
1628           }
1629           if (scope_field->is_constant_int()) {
1630             ScopeValue* next_scope_field = sv->field_at(svIndex + 1);
1631             if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1632               big_value = true;
1633             }
1634           }
1635         }
1636 
1637         if (big_value) {
1638           i++;
1639           assert(i < fields->length(), "second T_INT field needed");
1640           assert(fields->at(i)._type == T_INT, "T_INT field needed");
1641         } else {
1642           obj->int_field_put(offset, value->get_jint());
1643           break;
1644         }
1645       }
1646         /* no break */
1647 
1648       case T_LONG: case T_DOUBLE: {
1649         assert(value->type() == T_INT, "Agreement.");
1650         StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex));
1651 #ifdef _LP64
1652         jlong res = (jlong)low->get_intptr();
1653 #else
1654         jlong res = jlong_from(value->get_jint(), low->get_jint());
1655 #endif
1656         obj->long_field_put(offset, res);
1657         break;
1658       }
1659 
1660       case T_SHORT:
1661         assert(value->type() == T_INT, "Agreement.");
1662         obj->short_field_put(offset, (jshort)value->get_jint());
1663         break;
1664 
1665       case T_CHAR:
1666         assert(value->type() == T_INT, "Agreement.");
1667         obj->char_field_put(offset, (jchar)value->get_jint());
1668         break;
1669 
1670       case T_BYTE:
1671         assert(value->type() == T_INT, "Agreement.");
1672         obj->byte_field_put(offset, (jbyte)value->get_jint());
1673         break;
1674 
1675       case T_BOOLEAN:
1676         assert(value->type() == T_INT, "Agreement.");
1677         obj->bool_field_put(offset, (jboolean)value->get_jint());
1678         break;
1679 
1680       default:
1681         ShouldNotReachHere();
1682     }
1683     svIndex++;
1684   }
1685   return svIndex;
1686 }
1687 
1688 // restore fields of an eliminated inline type array
1689 void Deoptimization::reassign_flat_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, flatArrayOop obj, FlatArrayKlass* vak, bool is_jvmci, TRAPS) {
1690   InlineKlass* vk = vak->element_klass();
1691   assert(vk->maybe_flat_in_array(), "should only be used for flat inline type arrays");
1692   // Adjust offset to omit oop header
1693   int base_offset = arrayOopDesc::base_offset_in_bytes(T_FLAT_ELEMENT) - vk->payload_offset();
1694   // Initialize all elements of the flat inline type array
1695   for (int i = 0; i < sv->field_size(); i++) {
1696     ObjectValue* val = sv->field_at(i)->as_ObjectValue();
1697     int offset = base_offset + (i << Klass::layout_helper_log2_element_size(vak->layout_helper()));
1698     reassign_fields_by_klass(vk, fr, reg_map, val, 0, (oop)obj, is_jvmci, offset, CHECK);
1699     if (!obj->is_null_free_array()) {
1700       jboolean null_marker_value;
1701       if (val->has_properties()) {
1702         null_marker_value = StackValue::create_stack_value(fr, reg_map, val->properties())->get_jint() & 1;
1703       } else {
1704         null_marker_value = 1;
1705       }
1706       obj->bool_field_put(offset + vk->null_marker_offset(), null_marker_value);
1707     }
1708   }
1709 }
1710 
1711 // restore fields of all eliminated objects and arrays
1712 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool is_jvmci, TRAPS) {
1713   for (int i = 0; i < objects->length(); i++) {
1714     assert(objects->at(i)->is_object(), "invalid debug information");
1715     ObjectValue* sv = (ObjectValue*) objects->at(i);
1716     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1717     k = get_refined_array_klass(k, fr, reg_map, sv, THREAD);
1718 
1719     Handle obj = sv->value();
1720     assert(obj.not_null() || realloc_failures || sv->has_properties(), "reallocation was missed");
1721 #ifndef PRODUCT
1722     if (PrintDeoptimizationDetails) {
1723       tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());
1724     }
1725 #endif // !PRODUCT
1726 
1727     if (obj.is_null()) {
1728       continue;
1729     }
1730 
1731 #if INCLUDE_JVMCI
1732     // Don't reassign fields of boxes that came from a cache. Caches may be in CDS.
1733     if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) {
1734       continue;
1735     }
1736 #endif // INCLUDE_JVMCI
1737     if (EnableVectorSupport && VectorSupport::is_vector(k)) {
1738       assert(sv->field_size() == 1, "%s not a vector", k->name()->as_C_string());
1739       ScopeValue* payload = sv->field_at(0);
1740       if (payload->is_location() &&
1741           payload->as_LocationValue()->location().type() == Location::vector) {
1742 #ifndef PRODUCT
1743         if (PrintDeoptimizationDetails) {
1744           tty->print_cr("skip field reassignment for this vector - it should be assigned already");
1745           if (Verbose) {
1746             Handle obj = sv->value();
1747             k->oop_print_on(obj(), tty);
1748           }
1749         }
1750 #endif // !PRODUCT
1751         continue; // Such vector's value was already restored in VectorSupport::allocate_vector().
1752       }
1753       // Else fall-through to do assignment for scalar-replaced boxed vector representation
1754       // which could be restored after vector object allocation.
1755     }
1756     if (k->is_instance_klass()) {
1757       InstanceKlass* ik = InstanceKlass::cast(k);
1758       reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), is_jvmci, 0, CHECK);
1759     } else if (k->is_flatArray_klass()) {
1760       FlatArrayKlass* vak = FlatArrayKlass::cast(k);
1761       reassign_flat_array_elements(fr, reg_map, sv, (flatArrayOop) obj(), vak, is_jvmci, CHECK);
1762     } else if (k->is_typeArray_klass()) {
1763       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1764       reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
1765     } else if (k->is_refArray_klass()) {
1766       reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
1767     }
1768   }
1769   // These objects may escape when we return to Interpreter after deoptimization.
1770   // We need barrier so that stores that initialize these objects can't be reordered
1771   // with subsequent stores that make these objects accessible by other threads.
1772   OrderAccess::storestore();
1773 }
1774 
1775 
1776 // relock objects for which synchronization was eliminated
1777 bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors,
1778                                     JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) {
1779   bool relocked_objects = false;
1780   for (int i = 0; i < monitors->length(); i++) {
1781     MonitorInfo* mon_info = monitors->at(i);
1782     if (mon_info->eliminated()) {
1783       assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
1784       relocked_objects = true;
1785       if (!mon_info->owner_is_scalar_replaced()) {
1786         Handle obj(thread, mon_info->owner());
1787         markWord mark = obj->mark();
1788         if (exec_mode == Unpack_none) {
1789           if (mark.has_monitor()) {
1790             // defer relocking if the deoptee thread is currently waiting for obj
1791             ObjectMonitor* waiting_monitor = deoptee_thread->current_waiting_monitor();
1792             if (waiting_monitor != nullptr && waiting_monitor->object() == obj()) {
1793               assert(fr.is_deoptimized_frame(), "frame must be scheduled for deoptimization");
1794               if (UseObjectMonitorTable) {
1795                 mon_info->lock()->clear_object_monitor_cache();
1796               }
1797 #ifdef ASSERT
1798               else {
1799                 assert(!UseObjectMonitorTable, "must be");
1800                 mon_info->lock()->set_bad_monitor_deopt();
1801               }
1802 #endif
1803               JvmtiDeferredUpdates::inc_relock_count_after_wait(deoptee_thread);
1804               continue;
1805             }
1806           }
1807         }
1808         BasicLock* lock = mon_info->lock();
1809         // We have lost information about the correct state of the lock stack.
1810         // Entering may create an invalid lock stack. Inflate the lock if it
1811         // was fast_locked to restore the valid lock stack.
1812         if (UseObjectMonitorTable) {
1813           // UseObjectMonitorTable expects the BasicLock cache to be either a
1814           // valid ObjectMonitor* or nullptr. Right now it is garbage, set it
1815           // to nullptr.
1816           lock->clear_object_monitor_cache();
1817         }
1818         ObjectSynchronizer::enter_for(obj, lock, deoptee_thread);
1819         if (deoptee_thread->lock_stack().contains(obj())) {
1820             ObjectSynchronizer::inflate_fast_locked_object(obj(), ObjectSynchronizer::InflateCause::inflate_cause_vm_internal,
1821                                                            deoptee_thread, thread);
1822         }
1823         assert(mon_info->owner()->is_locked(), "object must be locked now");
1824         assert(obj->mark().has_monitor(), "must be");
1825         assert(!deoptee_thread->lock_stack().contains(obj()), "must be");
1826         assert(ObjectSynchronizer::read_monitor(obj(), obj->mark())->has_owner(deoptee_thread), "must be");
1827       }
1828     }
1829   }
1830   return relocked_objects;
1831 }
1832 #endif // COMPILER2_OR_JVMCI
1833 
1834 vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {
1835   Events::log_deopt_message(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp()));
1836 
1837   // Register map for next frame (used for stack crawl).  We capture
1838   // the state of the deopt'ing frame's caller.  Thus if we need to
1839   // stuff a C2I adapter we can properly fill in the callee-save
1840   // register locations.
1841   frame caller = fr.sender(reg_map);
1842   int frame_size = pointer_delta_as_int(caller.sp(), fr.sp());
1843 
1844   frame sender = caller;
1845 
1846   // Since the Java thread being deoptimized will eventually adjust it's own stack,
1847   // the vframeArray containing the unpacking information is allocated in the C heap.
1848   // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
1849   vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);
1850 
1851   // Compare the vframeArray to the collected vframes
1852   assert(array->structural_compare(thread, chunk), "just checking");
1853 
1854   if (TraceDeoptimization) {
1855     ResourceMark rm;
1856     stringStream st;
1857     st.print_cr("DEOPT PACKING thread=" INTPTR_FORMAT " vframeArray=" INTPTR_FORMAT, p2i(thread), p2i(array));
1858     st.print("   ");
1859     fr.print_on(&st);
1860     st.print_cr("   Virtual frames (innermost/newest first):");
1861     for (int index = 0; index < chunk->length(); index++) {
1862       compiledVFrame* vf = chunk->at(index);
1863       int bci = vf->raw_bci();
1864       const char* code_name;
1865       if (bci == SynchronizationEntryBCI) {
1866         code_name = "sync entry";
1867       } else {
1868         Bytecodes::Code code = vf->method()->code_at(bci);
1869         code_name = Bytecodes::name(code);
1870       }
1871 
1872       st.print("      VFrame %d (" INTPTR_FORMAT ")", index, p2i(vf));
1873       st.print(" - %s", vf->method()->name_and_sig_as_C_string());
1874       st.print(" - %s", code_name);
1875       st.print_cr(" @ bci=%d ", bci);
1876     }
1877     tty->print_raw(st.freeze());
1878     tty->cr();
1879   }
1880 
1881   return array;
1882 }
1883 
1884 #if COMPILER2_OR_JVMCI
1885 void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {
1886   // Reallocation of some scalar replaced objects failed. Record
1887   // that we need to pop all the interpreter frames for the
1888   // deoptimized compiled frame.
1889   assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");
1890   thread->set_frames_to_pop_failed_realloc(array->frames());
1891   // Unlock all monitors here otherwise the interpreter will see a
1892   // mix of locked and unlocked monitors (because of failed
1893   // reallocations of synchronized objects) and be confused.
1894   for (int i = 0; i < array->frames(); i++) {
1895     MonitorChunk* monitors = array->element(i)->monitors();
1896     if (monitors != nullptr) {
1897       // Unlock in reverse order starting from most nested monitor.
1898       for (int j = (monitors->number_of_monitors() - 1); j >= 0; j--) {
1899         BasicObjectLock* src = monitors->at(j);
1900         if (src->obj() != nullptr) {
1901           ObjectSynchronizer::exit(src->obj(), src->lock(), thread);
1902         }
1903       }
1904       array->element(i)->free_monitors();
1905 #ifdef ASSERT
1906       array->element(i)->set_removed_monitors();
1907 #endif
1908     }
1909   }
1910 }
1911 #endif
1912 
1913 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) {
1914   assert(fr.can_be_deoptimized(), "checking frame type");
1915 
1916   gather_statistics(reason, Action_none, Bytecodes::_illegal);
1917 
1918   if (LogCompilation && xtty != nullptr) {
1919     nmethod* nm = fr.cb()->as_nmethod_or_null();
1920     assert(nm != nullptr, "only compiled methods can deopt");
1921 
1922     ttyLocker ttyl;
1923     xtty->begin_head("deoptimized thread='%zu' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1924     nm->log_identity(xtty);
1925     xtty->end_head();
1926     for (ScopeDesc* sd = nm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1927       xtty->begin_elem("jvms bci='%d'", sd->bci());
1928       xtty->method(sd->method());
1929       xtty->end_elem();
1930       if (sd->is_top())  break;
1931     }
1932     xtty->tail("deoptimized");
1933   }
1934 
1935   Continuation::notify_deopt(thread, fr.sp());
1936 
1937   // Patch the compiled method so that when execution returns to it we will
1938   // deopt the execution state and return to the interpreter.
1939   fr.deoptimize(thread);
1940 }
1941 
1942 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {
1943   // Deoptimize only if the frame comes from compiled code.
1944   // Do not deoptimize the frame which is already patched
1945   // during the execution of the loops below.
1946   if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1947     return;
1948   }
1949   ResourceMark rm;
1950   deoptimize_single_frame(thread, fr, reason);
1951 }
1952 
1953 address Deoptimization::deoptimize_for_missing_exception_handler(nmethod* nm, bool make_not_entrant) {
1954   // there is no exception handler for this pc => deoptimize
1955   if (make_not_entrant) {
1956     nm->make_not_entrant(nmethod::InvalidationReason::MISSING_EXCEPTION_HANDLER);
1957   }
1958 
1959   // Use Deoptimization::deoptimize for all of its side-effects:
1960   // gathering traps statistics, logging...
1961   // it also patches the return pc but we do not care about that
1962   // since we return a continuation to the deopt_blob below.
1963   JavaThread* thread = JavaThread::current();
1964   RegisterMap reg_map(thread,
1965                       RegisterMap::UpdateMap::skip,
1966                       RegisterMap::ProcessFrames::include,
1967                       RegisterMap::WalkContinuation::skip);
1968   frame runtime_frame = thread->last_frame();
1969   frame caller_frame = runtime_frame.sender(&reg_map);
1970   assert(caller_frame.cb()->as_nmethod_or_null() == nm, "expect top frame compiled method");
1971 
1972   Deoptimization::deoptimize(thread, caller_frame, Deoptimization::Reason_not_compiled_exception_handler);
1973 
1974   if (!nm->is_compiled_by_jvmci()) {
1975     return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
1976   }
1977 
1978 #if INCLUDE_JVMCI
1979   // JVMCI support
1980   vframe* vf = vframe::new_vframe(&caller_frame, &reg_map, thread);
1981   compiledVFrame* cvf = compiledVFrame::cast(vf);
1982   ScopeDesc* imm_scope = cvf->scope();
1983   MethodData* imm_mdo = get_method_data(thread, methodHandle(thread, imm_scope->method()), true);
1984   if (imm_mdo != nullptr) {
1985     // Lock to read ProfileData, and ensure lock is not broken by a safepoint
1986     MutexLocker ml(imm_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
1987 
1988     ProfileData* pdata = imm_mdo->allocate_bci_to_data(imm_scope->bci(), nullptr);
1989     if (pdata != nullptr && pdata->is_BitData()) {
1990       BitData* bit_data = (BitData*) pdata;
1991       bit_data->set_exception_seen();
1992     }
1993   }
1994 
1995 
1996   MethodData* trap_mdo = get_method_data(thread, methodHandle(thread, nm->method()), true);
1997   if (trap_mdo != nullptr) {
1998     trap_mdo->inc_trap_count(Deoptimization::Reason_not_compiled_exception_handler);
1999   }
2000 #endif
2001 
2002   return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
2003 }
2004 
2005 void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) {
2006   assert(thread == Thread::current() ||
2007          thread->is_handshake_safe_for(Thread::current()) ||
2008          SafepointSynchronize::is_at_safepoint(),
2009          "can only deoptimize other thread at a safepoint/handshake");
2010   // Compute frame and register map based on thread and sp.
2011   RegisterMap reg_map(thread,
2012                       RegisterMap::UpdateMap::skip,
2013                       RegisterMap::ProcessFrames::include,
2014                       RegisterMap::WalkContinuation::skip);
2015   frame fr = thread->last_frame();
2016   while (fr.id() != id) {
2017     fr = fr.sender(&reg_map);
2018   }
2019   deoptimize(thread, fr, reason);
2020 }
2021 
2022 
2023 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) {
2024   Thread* current = Thread::current();
2025   if (thread == current || thread->is_handshake_safe_for(current)) {
2026     Deoptimization::deoptimize_frame_internal(thread, id, reason);
2027   } else {
2028     VM_DeoptimizeFrame deopt(thread, id, reason);
2029     VMThread::execute(&deopt);
2030   }
2031 }
2032 
2033 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
2034   deoptimize_frame(thread, id, Reason_constraint);
2035 }
2036 
2037 // JVMTI PopFrame support
2038 JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
2039 {
2040   assert(thread == JavaThread::current(), "pre-condition");
2041   thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
2042 }
2043 JRT_END
2044 
2045 MethodData*
2046 Deoptimization::get_method_data(JavaThread* thread, const methodHandle& m,
2047                                 bool create_if_missing) {
2048   JavaThread* THREAD = thread; // For exception macros.
2049   MethodData* mdo = m()->method_data();
2050   if (mdo == nullptr && create_if_missing && !HAS_PENDING_EXCEPTION) {
2051     // Build an MDO.  Ignore errors like OutOfMemory;
2052     // that simply means we won't have an MDO to update.
2053     Method::build_profiling_method_data(m, THREAD);
2054     if (HAS_PENDING_EXCEPTION) {
2055       // Only metaspace OOM is expected. No Java code executed.
2056       assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here");
2057       CLEAR_PENDING_EXCEPTION;
2058     }
2059     mdo = m()->method_data();
2060   }
2061   return mdo;
2062 }
2063 
2064 #if COMPILER2_OR_JVMCI
2065 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) {
2066   // In case of an unresolved klass entry, load the class.
2067   // This path is exercised from case _ldc in Parse::do_one_bytecode,
2068   // and probably nowhere else.
2069   // Even that case would benefit from simply re-interpreting the
2070   // bytecode, without paying special attention to the class index.
2071   // So this whole "class index" feature should probably be removed.
2072 
2073   if (constant_pool->tag_at(index).is_unresolved_klass()) {
2074     Klass* tk = constant_pool->klass_at(index, THREAD);
2075     if (HAS_PENDING_EXCEPTION) {
2076       // Exception happened during classloading. We ignore the exception here, since it
2077       // is going to be rethrown since the current activation is going to be deoptimized and
2078       // the interpreter will re-execute the bytecode.
2079       // Do not clear probable Async Exceptions.
2080       CLEAR_PENDING_NONASYNC_EXCEPTION;
2081       // Class loading called java code which may have caused a stack
2082       // overflow. If the exception was thrown right before the return
2083       // to the runtime the stack is no longer guarded. Reguard the
2084       // stack otherwise if we return to the uncommon trap blob and the
2085       // stack bang causes a stack overflow we crash.
2086       JavaThread* jt = THREAD;
2087       bool guard_pages_enabled = jt->stack_overflow_state()->reguard_stack_if_needed();
2088       assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");
2089     }
2090     return;
2091   }
2092 
2093   assert(!constant_pool->tag_at(index).is_symbol(),
2094          "no symbolic names here, please");
2095 }
2096 
2097 #if INCLUDE_JFR
2098 
2099 class DeoptReasonSerializer : public JfrSerializer {
2100  public:
2101   void serialize(JfrCheckpointWriter& writer) {
2102     writer.write_count((u4)(Deoptimization::Reason_LIMIT + 1)); // + Reason::many (-1)
2103     for (int i = -1; i < Deoptimization::Reason_LIMIT; ++i) {
2104       writer.write_key((u8)i);
2105       writer.write(Deoptimization::trap_reason_name(i));
2106     }
2107   }
2108 };
2109 
2110 class DeoptActionSerializer : public JfrSerializer {
2111  public:
2112   void serialize(JfrCheckpointWriter& writer) {
2113     static const u4 nof_actions = Deoptimization::Action_LIMIT;
2114     writer.write_count(nof_actions);
2115     for (u4 i = 0; i < Deoptimization::Action_LIMIT; ++i) {
2116       writer.write_key(i);
2117       writer.write(Deoptimization::trap_action_name((int)i));
2118     }
2119   }
2120 };
2121 
2122 static void register_serializers() {
2123   static int critical_section = 0;
2124   if (1 == critical_section || AtomicAccess::cmpxchg(&critical_section, 0, 1) == 1) {
2125     return;
2126   }
2127   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONREASON, true, new DeoptReasonSerializer());
2128   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONACTION, true, new DeoptActionSerializer());
2129 }
2130 
2131 static void post_deoptimization_event(nmethod* nm,
2132                                       const Method* method,
2133                                       int trap_bci,
2134                                       int instruction,
2135                                       Deoptimization::DeoptReason reason,
2136                                       Deoptimization::DeoptAction action) {
2137   assert(nm != nullptr, "invariant");
2138   assert(method != nullptr, "invariant");
2139   if (EventDeoptimization::is_enabled()) {
2140     static bool serializers_registered = false;
2141     if (!serializers_registered) {
2142       register_serializers();
2143       serializers_registered = true;
2144     }
2145     EventDeoptimization event;
2146     event.set_compileId(nm->compile_id());
2147     event.set_compiler(nm->compiler_type());
2148     event.set_method(method);
2149     event.set_lineNumber(method->line_number_from_bci(trap_bci));
2150     event.set_bci(trap_bci);
2151     event.set_instruction(instruction);
2152     event.set_reason(reason);
2153     event.set_action(action);
2154     event.commit();
2155   }
2156 }
2157 
2158 #endif // INCLUDE_JFR
2159 
2160 static void log_deopt(nmethod* nm, Method* tm, intptr_t pc, frame& fr, int trap_bci,
2161                       const char* reason_name, const char* reason_action, const char* class_name) {
2162   LogTarget(Debug, deoptimization) lt;
2163   if (lt.is_enabled()) {
2164     LogStream ls(lt);
2165     bool is_osr = nm->is_osr_method();
2166     ls.print("cid=%4d %s level=%d",
2167              nm->compile_id(), (is_osr ? "osr" : "   "), nm->comp_level());
2168     ls.print(" %s", tm->name_and_sig_as_C_string());
2169     ls.print(" trap_bci=%d ", trap_bci);
2170     if (is_osr) {
2171       ls.print("osr_bci=%d ", nm->osr_entry_bci());
2172     }
2173     ls.print("%s ", reason_name);
2174     ls.print("%s ", reason_action);
2175     if (class_name != nullptr) {
2176       ls.print("%s ", class_name);
2177     }
2178     ls.print_cr("pc=" INTPTR_FORMAT " relative_pc=" INTPTR_FORMAT,
2179              pc, fr.pc() - nm->code_begin());
2180   }
2181 }
2182 
2183 JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* current, jint trap_request)) {
2184   HandleMark hm(current);
2185 
2186   // uncommon_trap() is called at the beginning of the uncommon trap
2187   // handler. Note this fact before we start generating temporary frames
2188   // that can confuse an asynchronous stack walker. This counter is
2189   // decremented at the end of unpack_frames().
2190 
2191   current->inc_in_deopt_handler();
2192 
2193 #if INCLUDE_JVMCI
2194   // JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid
2195   RegisterMap reg_map(current,
2196                       RegisterMap::UpdateMap::include,
2197                       RegisterMap::ProcessFrames::include,
2198                       RegisterMap::WalkContinuation::skip);
2199 #else
2200   RegisterMap reg_map(current,
2201                       RegisterMap::UpdateMap::skip,
2202                       RegisterMap::ProcessFrames::include,
2203                       RegisterMap::WalkContinuation::skip);
2204 #endif
2205   frame stub_frame = current->last_frame();
2206   frame fr = stub_frame.sender(&reg_map);
2207 
2208   // Log a message
2209   Events::log_deopt_message(current, "Uncommon trap: trap_request=" INT32_FORMAT_X_0 " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT,
2210               trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin());
2211 
2212   {
2213     ResourceMark rm;
2214 
2215     DeoptReason reason = trap_request_reason(trap_request);
2216     DeoptAction action = trap_request_action(trap_request);
2217 #if INCLUDE_JVMCI
2218     int debug_id = trap_request_debug_id(trap_request);
2219 #endif
2220     jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1
2221 
2222     vframe*  vf  = vframe::new_vframe(&fr, &reg_map, current);
2223     compiledVFrame* cvf = compiledVFrame::cast(vf);
2224 
2225     nmethod* nm = cvf->code();
2226 
2227     ScopeDesc*      trap_scope  = cvf->scope();
2228 
2229     bool is_receiver_constraint_failure = COMPILER2_PRESENT(VerifyReceiverTypes &&) (reason == Deoptimization::Reason_receiver_constraint);
2230 
2231     if (is_receiver_constraint_failure) {
2232       tty->print_cr("  bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT ", method=%s" JVMCI_ONLY(", debug_id=%d"),
2233                     trap_scope->bci(), p2i(fr.pc()), fr.pc() - nm->code_begin(), trap_scope->method()->name_and_sig_as_C_string()
2234                     JVMCI_ONLY(COMMA debug_id));
2235     }
2236 
2237     methodHandle    trap_method(current, trap_scope->method());
2238     int             trap_bci    = trap_scope->bci();
2239 #if INCLUDE_JVMCI
2240     jlong           speculation = current->pending_failed_speculation();
2241     if (nm->is_compiled_by_jvmci()) {
2242       nm->update_speculation(current);
2243     } else {
2244       assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers");
2245     }
2246 
2247     if (trap_bci == SynchronizationEntryBCI) {
2248       trap_bci = 0;
2249       current->set_pending_monitorenter(true);
2250     }
2251 
2252     if (reason == Deoptimization::Reason_transfer_to_interpreter) {
2253       current->set_pending_transfer_to_interpreter(true);
2254     }
2255 #endif
2256 
2257     Bytecodes::Code trap_bc     = trap_method->java_code_at(trap_bci);
2258     // Record this event in the histogram.
2259     gather_statistics(reason, action, trap_bc);
2260 
2261     // Ensure that we can record deopt. history:
2262     bool create_if_missing = ProfileTraps;
2263 
2264     methodHandle profiled_method;
2265 #if INCLUDE_JVMCI
2266     if (nm->is_compiled_by_jvmci()) {
2267       profiled_method = methodHandle(current, nm->method());
2268     } else {
2269       profiled_method = trap_method;
2270     }
2271 #else
2272     profiled_method = trap_method;
2273 #endif
2274 
2275     MethodData* trap_mdo =
2276       get_method_data(current, profiled_method, create_if_missing);
2277 
2278     Symbol* class_name = nullptr;
2279     bool unresolved = false;
2280     if (unloaded_class_index >= 0) {
2281       constantPoolHandle constants (current, trap_method->constants());
2282       if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
2283         class_name = constants->klass_name_at(unloaded_class_index);
2284         unresolved = true;
2285       } else if (constants->tag_at(unloaded_class_index).is_symbol()) {
2286         class_name = constants->symbol_at(unloaded_class_index);
2287       }
2288     }
2289     { // Log Deoptimization event for JFR, UL and event system
2290       Method* tm = trap_method();
2291       const char* reason_name = trap_reason_name(reason);
2292       const char* reason_action = trap_action_name(action);
2293       intptr_t pc = p2i(fr.pc());
2294 
2295       JFR_ONLY(post_deoptimization_event(nm, tm, trap_bci, trap_bc, reason, action);)
2296 
2297       ResourceMark rm;
2298 
2299       const char* class_name_str = nullptr;
2300       const char* class_name_msg = nullptr;
2301       stringStream st, stm;
2302       if (class_name != nullptr) {
2303         class_name->print_symbol_on(&st);
2304         class_name_str = st.freeze();
2305         stm.print("class=%s ", class_name_str);
2306         class_name_msg = stm.freeze();
2307       } else {
2308         class_name_msg = "";
2309       }
2310       log_deopt(nm, tm, pc, fr, trap_bci, reason_name, reason_action, class_name_str);
2311       Events::log_deopt_message(current, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s%s",
2312                                 reason_name, reason_action, pc,
2313                                 tm->name_and_sig_as_C_string(), trap_bci, class_name_msg, nm->compiler_name());
2314     }
2315 
2316     // Print a bunch of diagnostics, if requested.
2317     if (TraceDeoptimization || LogCompilation || is_receiver_constraint_failure) {
2318       ResourceMark rm;
2319 
2320       // Lock to read ProfileData, and ensure lock is not broken by a safepoint
2321       // We must do this already now, since we cannot acquire this lock while
2322       // holding the tty lock (lock ordering by rank).
2323       ConditionalMutexLocker ml((trap_mdo != nullptr) ? trap_mdo->extra_data_lock() : nullptr,
2324                                 (trap_mdo != nullptr),
2325                                 Mutex::_no_safepoint_check_flag);
2326 
2327       ttyLocker ttyl;
2328 
2329       char buf[100];
2330       if (xtty != nullptr) {
2331         xtty->begin_head("uncommon_trap thread='%zu' %s",
2332                          os::current_thread_id(),
2333                          format_trap_request(buf, sizeof(buf), trap_request));
2334 #if INCLUDE_JVMCI
2335         if (speculation != 0) {
2336           xtty->print(" speculation='" JLONG_FORMAT "'", speculation);
2337         }
2338 #endif
2339         nm->log_identity(xtty);
2340       }
2341       if (class_name != nullptr) {
2342         if (xtty != nullptr) {
2343           if (unresolved) {
2344             xtty->print(" unresolved='1'");
2345           }
2346           xtty->name(class_name);
2347         }
2348       }
2349       if (xtty != nullptr && trap_mdo != nullptr && (int)reason < (int)MethodData::_trap_hist_limit) {
2350         // Dump the relevant MDO state.
2351         // This is the deopt count for the current reason, any previous
2352         // reasons or recompiles seen at this point.
2353         int dcnt = trap_mdo->trap_count(reason);
2354         if (dcnt != 0)
2355           xtty->print(" count='%d'", dcnt);
2356 
2357         // We need to lock to read the ProfileData. But to keep the locks ordered, we need to
2358         // lock extra_data_lock before the tty lock.
2359         ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
2360         int dos = (pdata == nullptr)? 0: pdata->trap_state();
2361         if (dos != 0) {
2362           xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
2363           if (trap_state_is_recompiled(dos)) {
2364             int recnt2 = trap_mdo->overflow_recompile_count();
2365             if (recnt2 != 0)
2366               xtty->print(" recompiles2='%d'", recnt2);
2367           }
2368         }
2369       }
2370       if (xtty != nullptr) {
2371         xtty->stamp();
2372         xtty->end_head();
2373       }
2374       if (TraceDeoptimization) {  // make noise on the tty
2375         stringStream st;
2376         st.print("UNCOMMON TRAP method=%s", trap_scope->method()->name_and_sig_as_C_string());
2377         st.print("  bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT JVMCI_ONLY(", debug_id=%d"),
2378                  trap_scope->bci(), p2i(fr.pc()), fr.pc() - nm->code_begin() JVMCI_ONLY(COMMA debug_id));
2379         st.print(" compiler=%s compile_id=%d", nm->compiler_name(), nm->compile_id());
2380 #if INCLUDE_JVMCI
2381         if (nm->is_compiled_by_jvmci()) {
2382           const char* installed_code_name = nm->jvmci_name();
2383           if (installed_code_name != nullptr) {
2384             st.print(" (JVMCI: installed code name=%s) ", installed_code_name);
2385           }
2386         }
2387 #endif
2388         st.print(" (@" INTPTR_FORMAT ") thread=%zu reason=%s action=%s unloaded_class_index=%d" JVMCI_ONLY(" debug_id=%d"),
2389                    p2i(fr.pc()),
2390                    os::current_thread_id(),
2391                    trap_reason_name(reason),
2392                    trap_action_name(action),
2393                    unloaded_class_index
2394 #if INCLUDE_JVMCI
2395                    , debug_id
2396 #endif
2397                    );
2398         if (class_name != nullptr) {
2399           st.print(unresolved ? " unresolved class: " : " symbol: ");
2400           class_name->print_symbol_on(&st);
2401         }
2402         st.cr();
2403         tty->print_raw(st.freeze());
2404       }
2405       if (xtty != nullptr) {
2406         // Log the precise location of the trap.
2407         for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
2408           xtty->begin_elem("jvms bci='%d'", sd->bci());
2409           xtty->method(sd->method());
2410           xtty->end_elem();
2411           if (sd->is_top())  break;
2412         }
2413         xtty->tail("uncommon_trap");
2414       }
2415     }
2416     // (End diagnostic printout.)
2417 
2418     if (is_receiver_constraint_failure) {
2419       fatal("missing receiver type check");
2420     }
2421 
2422     // Load class if necessary
2423     if (unloaded_class_index >= 0) {
2424       constantPoolHandle constants(current, trap_method->constants());
2425       load_class_by_index(constants, unloaded_class_index, THREAD);
2426     }
2427 
2428     // Flush the nmethod if necessary and desirable.
2429     //
2430     // We need to avoid situations where we are re-flushing the nmethod
2431     // because of a hot deoptimization site.  Repeated flushes at the same
2432     // point need to be detected by the compiler and avoided.  If the compiler
2433     // cannot avoid them (or has a bug and "refuses" to avoid them), this
2434     // module must take measures to avoid an infinite cycle of recompilation
2435     // and deoptimization.  There are several such measures:
2436     //
2437     //   1. If a recompilation is ordered a second time at some site X
2438     //   and for the same reason R, the action is adjusted to 'reinterpret',
2439     //   to give the interpreter time to exercise the method more thoroughly.
2440     //   If this happens, the method's overflow_recompile_count is incremented.
2441     //
2442     //   2. If the compiler fails to reduce the deoptimization rate, then
2443     //   the method's overflow_recompile_count will begin to exceed the set
2444     //   limit PerBytecodeRecompilationCutoff.  If this happens, the action
2445     //   is adjusted to 'make_not_compilable', and the method is abandoned
2446     //   to the interpreter.  This is a performance hit for hot methods,
2447     //   but is better than a disastrous infinite cycle of recompilations.
2448     //   (Actually, only the method containing the site X is abandoned.)
2449     //
2450     //   3. In parallel with the previous measures, if the total number of
2451     //   recompilations of a method exceeds the much larger set limit
2452     //   PerMethodRecompilationCutoff, the method is abandoned.
2453     //   This should only happen if the method is very large and has
2454     //   many "lukewarm" deoptimizations.  The code which enforces this
2455     //   limit is elsewhere (class nmethod, class Method).
2456     //
2457     // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
2458     // to recompile at each bytecode independently of the per-BCI cutoff.
2459     //
2460     // The decision to update code is up to the compiler, and is encoded
2461     // in the Action_xxx code.  If the compiler requests Action_none
2462     // no trap state is changed, no compiled code is changed, and the
2463     // computation suffers along in the interpreter.
2464     //
2465     // The other action codes specify various tactics for decompilation
2466     // and recompilation.  Action_maybe_recompile is the loosest, and
2467     // allows the compiled code to stay around until enough traps are seen,
2468     // and until the compiler gets around to recompiling the trapping method.
2469     //
2470     // The other actions cause immediate removal of the present code.
2471 
2472     // Traps caused by injected profile shouldn't pollute trap counts.
2473     bool injected_profile_trap = trap_method->has_injected_profile() &&
2474                                  (reason == Reason_intrinsic || reason == Reason_unreached);
2475 
2476     bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap;
2477     bool make_not_entrant = false;
2478     bool make_not_compilable = false;
2479     bool reprofile = false;
2480     switch (action) {
2481     case Action_none:
2482       // Keep the old code.
2483       update_trap_state = false;
2484       break;
2485     case Action_maybe_recompile:
2486       // Do not need to invalidate the present code, but we can
2487       // initiate another
2488       // Start compiler without (necessarily) invalidating the nmethod.
2489       // The system will tolerate the old code, but new code should be
2490       // generated when possible.
2491       break;
2492     case Action_reinterpret:
2493       // Go back into the interpreter for a while, and then consider
2494       // recompiling form scratch.
2495       make_not_entrant = true;
2496       // Reset invocation counter for outer most method.
2497       // This will allow the interpreter to exercise the bytecodes
2498       // for a while before recompiling.
2499       // By contrast, Action_make_not_entrant is immediate.
2500       //
2501       // Note that the compiler will track null_check, null_assert,
2502       // range_check, and class_check events and log them as if they
2503       // had been traps taken from compiled code.  This will update
2504       // the MDO trap history so that the next compilation will
2505       // properly detect hot trap sites.
2506       reprofile = true;
2507       break;
2508     case Action_make_not_entrant:
2509       // Request immediate recompilation, and get rid of the old code.
2510       // Make them not entrant, so next time they are called they get
2511       // recompiled.  Unloaded classes are loaded now so recompile before next
2512       // time they are called.  Same for uninitialized.  The interpreter will
2513       // link the missing class, if any.
2514       make_not_entrant = true;
2515       break;
2516     case Action_make_not_compilable:
2517       // Give up on compiling this method at all.
2518       make_not_entrant = true;
2519       make_not_compilable = true;
2520       break;
2521     default:
2522       ShouldNotReachHere();
2523     }
2524 
2525 #if INCLUDE_JVMCI
2526     // Deoptimization count is used by the CompileBroker to reason about compilations
2527     // it requests so do not pollute the count for deoptimizations in non-default (i.e.
2528     // non-CompilerBroker) compilations.
2529     if (nm->jvmci_skip_profile_deopt()) {
2530       update_trap_state = false;
2531     }
2532 #endif
2533     // Setting +ProfileTraps fixes the following, on all platforms:
2534     // The result is infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
2535     // recompile relies on a MethodData* to record heroic opt failures.
2536 
2537     // Whether the interpreter is producing MDO data or not, we also need
2538     // to use the MDO to detect hot deoptimization points and control
2539     // aggressive optimization.
2540     bool inc_recompile_count = false;
2541 
2542     // Lock to read ProfileData, and ensure lock is not broken by a safepoint
2543     ConditionalMutexLocker ml((trap_mdo != nullptr) ? trap_mdo->extra_data_lock() : nullptr,
2544                               (trap_mdo != nullptr),
2545                               Mutex::_no_safepoint_check_flag);
2546     ProfileData* pdata = nullptr;
2547     if (ProfileTraps && CompilerConfig::is_c2_or_jvmci_compiler_enabled() && update_trap_state && trap_mdo != nullptr) {
2548       assert(trap_mdo == get_method_data(current, profiled_method, false), "sanity");
2549       uint this_trap_count = 0;
2550       bool maybe_prior_trap = false;
2551       bool maybe_prior_recompile = false;
2552 
2553       pdata = query_update_method_data(trap_mdo, trap_bci, reason, true,
2554 #if INCLUDE_JVMCI
2555                                    nm->is_compiled_by_jvmci() && nm->is_osr_method(),
2556 #endif
2557                                    nm->method(),
2558                                    //outputs:
2559                                    this_trap_count,
2560                                    maybe_prior_trap,
2561                                    maybe_prior_recompile);
2562       // Because the interpreter also counts null, div0, range, and class
2563       // checks, these traps from compiled code are double-counted.
2564       // This is harmless; it just means that the PerXTrapLimit values
2565       // are in effect a little smaller than they look.
2566 
2567       DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2568       if (per_bc_reason != Reason_none) {
2569         // Now take action based on the partially known per-BCI history.
2570         if (maybe_prior_trap
2571             && this_trap_count >= (uint)PerBytecodeTrapLimit) {
2572           // If there are too many traps at this BCI, force a recompile.
2573           // This will allow the compiler to see the limit overflow, and
2574           // take corrective action, if possible.  The compiler generally
2575           // does not use the exact PerBytecodeTrapLimit value, but instead
2576           // changes its tactics if it sees any traps at all.  This provides
2577           // a little hysteresis, delaying a recompile until a trap happens
2578           // several times.
2579           //
2580           // Actually, since there is only one bit of counter per BCI,
2581           // the possible per-BCI counts are {0,1,(per-method count)}.
2582           // This produces accurate results if in fact there is only
2583           // one hot trap site, but begins to get fuzzy if there are
2584           // many sites.  For example, if there are ten sites each
2585           // trapping two or more times, they each get the blame for
2586           // all of their traps.
2587           make_not_entrant = true;
2588         }
2589 
2590         // Detect repeated recompilation at the same BCI, and enforce a limit.
2591         if (make_not_entrant && maybe_prior_recompile) {
2592           // More than one recompile at this point.
2593           inc_recompile_count = maybe_prior_trap;
2594         }
2595       } else {
2596         // For reasons which are not recorded per-bytecode, we simply
2597         // force recompiles unconditionally.
2598         // (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
2599         make_not_entrant = true;
2600       }
2601 
2602       // Go back to the compiler if there are too many traps in this method.
2603       if (this_trap_count >= per_method_trap_limit(reason)) {
2604         // If there are too many traps in this method, force a recompile.
2605         // This will allow the compiler to see the limit overflow, and
2606         // take corrective action, if possible.
2607         // (This condition is an unlikely backstop only, because the
2608         // PerBytecodeTrapLimit is more likely to take effect first,
2609         // if it is applicable.)
2610         make_not_entrant = true;
2611       }
2612 
2613       // Here's more hysteresis:  If there has been a recompile at
2614       // this trap point already, run the method in the interpreter
2615       // for a while to exercise it more thoroughly.
2616       if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
2617         reprofile = true;
2618       }
2619     }
2620 
2621     // Take requested actions on the method:
2622 
2623     // Recompile
2624     if (make_not_entrant) {
2625       if (!nm->make_not_entrant(nmethod::InvalidationReason::UNCOMMON_TRAP)) {
2626         return; // the call did not change nmethod's state
2627       }
2628 
2629       if (pdata != nullptr) {
2630         // Record the recompilation event, if any.
2631         int tstate0 = pdata->trap_state();
2632         int tstate1 = trap_state_set_recompiled(tstate0, true);
2633         if (tstate1 != tstate0)
2634           pdata->set_trap_state(tstate1);
2635       }
2636 
2637       // For code aging we count traps separately here, using make_not_entrant()
2638       // as a guard against simultaneous deopts in multiple threads.
2639       if (reason == Reason_tenured && trap_mdo != nullptr) {
2640         trap_mdo->inc_tenure_traps();
2641       }
2642     }
2643     if (inc_recompile_count) {
2644       trap_mdo->inc_overflow_recompile_count();
2645       if ((uint)trap_mdo->overflow_recompile_count() >
2646           (uint)PerBytecodeRecompilationCutoff) {
2647         // Give up on the method containing the bad BCI.
2648         if (trap_method() == nm->method()) {
2649           make_not_compilable = true;
2650         } else {
2651           trap_method->set_not_compilable("overflow_recompile_count > PerBytecodeRecompilationCutoff", CompLevel_full_optimization);
2652           // But give grace to the enclosing nm->method().
2653         }
2654       }
2655     }
2656 
2657     // Reprofile
2658     if (reprofile) {
2659       CompilationPolicy::reprofile(trap_scope, nm->is_osr_method());
2660     }
2661 
2662     // Give up compiling
2663     if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
2664       assert(make_not_entrant, "consistent");
2665       nm->method()->set_not_compilable("give up compiling", CompLevel_full_optimization);
2666     }
2667 
2668     if (ProfileExceptionHandlers && trap_mdo != nullptr) {
2669       BitData* exception_handler_data = trap_mdo->exception_handler_bci_to_data_or_null(trap_bci);
2670       if (exception_handler_data != nullptr) {
2671         // uncommon trap at the start of an exception handler.
2672         // C2 generates these for un-entered exception handlers.
2673         // mark the handler as entered to avoid generating
2674         // another uncommon trap the next time the handler is compiled
2675         exception_handler_data->set_exception_handler_entered();
2676       }
2677     }
2678 
2679   } // Free marked resources
2680 
2681 }
2682 JRT_END
2683 
2684 ProfileData*
2685 Deoptimization::query_update_method_data(MethodData* trap_mdo,
2686                                          int trap_bci,
2687                                          Deoptimization::DeoptReason reason,
2688                                          bool update_total_trap_count,
2689 #if INCLUDE_JVMCI
2690                                          bool is_osr,
2691 #endif
2692                                          Method* compiled_method,
2693                                          //outputs:
2694                                          uint& ret_this_trap_count,
2695                                          bool& ret_maybe_prior_trap,
2696                                          bool& ret_maybe_prior_recompile) {
2697   trap_mdo->check_extra_data_locked();
2698 
2699   bool maybe_prior_trap = false;
2700   bool maybe_prior_recompile = false;
2701   uint this_trap_count = 0;
2702   if (update_total_trap_count) {
2703     uint idx = reason;
2704 #if INCLUDE_JVMCI
2705     if (is_osr) {
2706       // Upper half of history array used for traps in OSR compilations
2707       idx += Reason_TRAP_HISTORY_LENGTH;
2708     }
2709 #endif
2710     uint prior_trap_count = trap_mdo->trap_count(idx);
2711     this_trap_count  = trap_mdo->inc_trap_count(idx);
2712 
2713     // If the runtime cannot find a place to store trap history,
2714     // it is estimated based on the general condition of the method.
2715     // If the method has ever been recompiled, or has ever incurred
2716     // a trap with the present reason , then this BCI is assumed
2717     // (pessimistically) to be the culprit.
2718     maybe_prior_trap      = (prior_trap_count != 0);
2719     maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
2720   }
2721   ProfileData* pdata = nullptr;
2722 
2723 
2724   // For reasons which are recorded per bytecode, we check per-BCI data.
2725   DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2726   assert(per_bc_reason != Reason_none || update_total_trap_count, "must be");
2727   if (per_bc_reason != Reason_none) {
2728     // Find the profile data for this BCI.  If there isn't one,
2729     // try to allocate one from the MDO's set of spares.
2730     // This will let us detect a repeated trap at this point.
2731     pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : nullptr);
2732 
2733     if (pdata != nullptr) {
2734       if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {
2735         if (LogCompilation && xtty != nullptr) {
2736           ttyLocker ttyl;
2737           // no more room for speculative traps in this MDO
2738           xtty->elem("speculative_traps_oom");
2739         }
2740       }
2741       // Query the trap state of this profile datum.
2742       int tstate0 = pdata->trap_state();
2743       if (!trap_state_has_reason(tstate0, per_bc_reason))
2744         maybe_prior_trap = false;
2745       if (!trap_state_is_recompiled(tstate0))
2746         maybe_prior_recompile = false;
2747 
2748       // Update the trap state of this profile datum.
2749       int tstate1 = tstate0;
2750       // Record the reason.
2751       tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
2752       // Store the updated state on the MDO, for next time.
2753       if (tstate1 != tstate0)
2754         pdata->set_trap_state(tstate1);
2755     } else {
2756       if (LogCompilation && xtty != nullptr) {
2757         ttyLocker ttyl;
2758         // Missing MDP?  Leave a small complaint in the log.
2759         xtty->elem("missing_mdp bci='%d'", trap_bci);
2760       }
2761     }
2762   }
2763 
2764   // Return results:
2765   ret_this_trap_count = this_trap_count;
2766   ret_maybe_prior_trap = maybe_prior_trap;
2767   ret_maybe_prior_recompile = maybe_prior_recompile;
2768   return pdata;
2769 }
2770 
2771 void
2772 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2773   ResourceMark rm;
2774   // Ignored outputs:
2775   uint ignore_this_trap_count;
2776   bool ignore_maybe_prior_trap;
2777   bool ignore_maybe_prior_recompile;
2778   assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
2779   // JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts
2780   bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler);
2781 
2782   // Lock to read ProfileData, and ensure lock is not broken by a safepoint
2783   MutexLocker ml(trap_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
2784 
2785   query_update_method_data(trap_mdo, trap_bci,
2786                            (DeoptReason)reason,
2787                            update_total_counts,
2788 #if INCLUDE_JVMCI
2789                            false,
2790 #endif
2791                            nullptr,
2792                            ignore_this_trap_count,
2793                            ignore_maybe_prior_trap,
2794                            ignore_maybe_prior_recompile);
2795 }
2796 
2797 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* current, jint trap_request, jint exec_mode) {
2798   // Enable WXWrite: current function is called from methods compiled by C2 directly
2799   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
2800 
2801   // Still in Java no safepoints
2802   {
2803     // This enters VM and may safepoint
2804     uncommon_trap_inner(current, trap_request);
2805   }
2806   HandleMark hm(current);
2807   return fetch_unroll_info_helper(current, exec_mode);
2808 }
2809 
2810 // Local derived constants.
2811 // Further breakdown of DataLayout::trap_state, as promised by DataLayout.
2812 const int DS_REASON_MASK   = ((uint)DataLayout::trap_mask) >> 1;
2813 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
2814 
2815 //---------------------------trap_state_reason---------------------------------
2816 Deoptimization::DeoptReason
2817 Deoptimization::trap_state_reason(int trap_state) {
2818   // This assert provides the link between the width of DataLayout::trap_bits
2819   // and the encoding of "recorded" reasons.  It ensures there are enough
2820   // bits to store all needed reasons in the per-BCI MDO profile.
2821   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2822   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2823   trap_state -= recompile_bit;
2824   if (trap_state == DS_REASON_MASK) {
2825     return Reason_many;
2826   } else {
2827     assert((int)Reason_none == 0, "state=0 => Reason_none");
2828     return (DeoptReason)trap_state;
2829   }
2830 }
2831 //-------------------------trap_state_has_reason-------------------------------
2832 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2833   assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
2834   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2835   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2836   trap_state -= recompile_bit;
2837   if (trap_state == DS_REASON_MASK) {
2838     return -1;  // true, unspecifically (bottom of state lattice)
2839   } else if (trap_state == reason) {
2840     return 1;   // true, definitely
2841   } else if (trap_state == 0) {
2842     return 0;   // false, definitely (top of state lattice)
2843   } else {
2844     return 0;   // false, definitely
2845   }
2846 }
2847 //-------------------------trap_state_add_reason-------------------------------
2848 int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
2849   assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
2850   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2851   trap_state -= recompile_bit;
2852   if (trap_state == DS_REASON_MASK) {
2853     return trap_state + recompile_bit;     // already at state lattice bottom
2854   } else if (trap_state == reason) {
2855     return trap_state + recompile_bit;     // the condition is already true
2856   } else if (trap_state == 0) {
2857     return reason + recompile_bit;          // no condition has yet been true
2858   } else {
2859     return DS_REASON_MASK + recompile_bit;  // fall to state lattice bottom
2860   }
2861 }
2862 //-----------------------trap_state_is_recompiled------------------------------
2863 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2864   return (trap_state & DS_RECOMPILE_BIT) != 0;
2865 }
2866 //-----------------------trap_state_set_recompiled-----------------------------
2867 int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
2868   if (z)  return trap_state |  DS_RECOMPILE_BIT;
2869   else    return trap_state & ~DS_RECOMPILE_BIT;
2870 }
2871 //---------------------------format_trap_state---------------------------------
2872 // This is used for debugging and diagnostics, including LogFile output.
2873 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2874                                               int trap_state) {
2875   assert(buflen > 0, "sanity");
2876   DeoptReason reason      = trap_state_reason(trap_state);
2877   bool        recomp_flag = trap_state_is_recompiled(trap_state);
2878   // Re-encode the state from its decoded components.
2879   int decoded_state = 0;
2880   if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
2881     decoded_state = trap_state_add_reason(decoded_state, reason);
2882   if (recomp_flag)
2883     decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
2884   // If the state re-encodes properly, format it symbolically.
2885   // Because this routine is used for debugging and diagnostics,
2886   // be robust even if the state is a strange value.
2887   size_t len;
2888   if (decoded_state != trap_state) {
2889     // Random buggy state that doesn't decode??
2890     len = jio_snprintf(buf, buflen, "#%d", trap_state);
2891   } else {
2892     len = jio_snprintf(buf, buflen, "%s%s",
2893                        trap_reason_name(reason),
2894                        recomp_flag ? " recompiled" : "");
2895   }
2896   return buf;
2897 }
2898 
2899 
2900 //--------------------------------statics--------------------------------------
2901 const char* Deoptimization::_trap_reason_name[] = {
2902   // Note:  Keep this in sync. with enum DeoptReason.
2903   "none",
2904   "null_check",
2905   "null_assert" JVMCI_ONLY("_or_unreached0"),
2906   "range_check",
2907   "class_check",
2908   "array_check",
2909   "intrinsic" JVMCI_ONLY("_or_type_checked_inlining"),
2910   "bimorphic" JVMCI_ONLY("_or_optimized_type_check"),
2911   "profile_predicate",
2912   "auto_vectorization_check",
2913   "unloaded",
2914   "uninitialized",
2915   "initialized",
2916   "unreached",
2917   "unhandled",
2918   "constraint",
2919   "div0_check",
2920   "age",
2921   "predicate",
2922   "loop_limit_check",
2923   "speculate_class_check",
2924   "speculate_null_check",
2925   "speculate_null_assert",
2926   "unstable_if",
2927   "unstable_fused_if",
2928   "receiver_constraint",
2929   "not_compiled_exception_handler",
2930   "short_running_loop" JVMCI_ONLY("_or_aliasing"),
2931 #if INCLUDE_JVMCI
2932   "transfer_to_interpreter",
2933   "unresolved",
2934   "jsr_mismatch",
2935 #endif
2936   "tenured"
2937 };
2938 const char* Deoptimization::_trap_action_name[] = {
2939   // Note:  Keep this in sync. with enum DeoptAction.
2940   "none",
2941   "maybe_recompile",
2942   "reinterpret",
2943   "make_not_entrant",
2944   "make_not_compilable"
2945 };
2946 
2947 const char* Deoptimization::trap_reason_name(int reason) {
2948   // Check that every reason has a name
2949   STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT);
2950 
2951   if (reason == Reason_many)  return "many";
2952   if ((uint)reason < Reason_LIMIT)
2953     return _trap_reason_name[reason];
2954   static char buf[20];
2955   os::snprintf_checked(buf, sizeof(buf), "reason%d", reason);
2956   return buf;
2957 }
2958 const char* Deoptimization::trap_action_name(int action) {
2959   // Check that every action has a name
2960   STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT);
2961 
2962   if ((uint)action < Action_LIMIT)
2963     return _trap_action_name[action];
2964   static char buf[20];
2965   os::snprintf_checked(buf, sizeof(buf), "action%d", action);
2966   return buf;
2967 }
2968 
2969 // This is used for debugging and diagnostics, including LogFile output.
2970 const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
2971                                                 int trap_request) {
2972   jint unloaded_class_index = trap_request_index(trap_request);
2973   const char* reason = trap_reason_name(trap_request_reason(trap_request));
2974   const char* action = trap_action_name(trap_request_action(trap_request));
2975 #if INCLUDE_JVMCI
2976   int debug_id = trap_request_debug_id(trap_request);
2977 #endif
2978   size_t len;
2979   if (unloaded_class_index < 0) {
2980     len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"),
2981                        reason, action
2982 #if INCLUDE_JVMCI
2983                        ,debug_id
2984 #endif
2985                        );
2986   } else {
2987     len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"),
2988                        reason, action, unloaded_class_index
2989 #if INCLUDE_JVMCI
2990                        ,debug_id
2991 #endif
2992                        );
2993   }
2994   return buf;
2995 }
2996 
2997 juint Deoptimization::_deoptimization_hist
2998         [Deoptimization::Reason_LIMIT]
2999     [1 + Deoptimization::Action_LIMIT]
3000         [Deoptimization::BC_CASE_LIMIT]
3001   = {0};
3002 
3003 enum {
3004   LSB_BITS = 8,
3005   LSB_MASK = right_n_bits(LSB_BITS)
3006 };
3007 
3008 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
3009                                        Bytecodes::Code bc) {
3010   assert(reason >= 0 && reason < Reason_LIMIT, "oob");
3011   assert(action >= 0 && action < Action_LIMIT, "oob");
3012   _deoptimization_hist[Reason_none][0][0] += 1;  // total
3013   _deoptimization_hist[reason][0][0]      += 1;  // per-reason total
3014   juint* cases = _deoptimization_hist[reason][1+action];
3015   juint* bc_counter_addr = nullptr;
3016   juint  bc_counter      = 0;
3017   // Look for an unused counter, or an exact match to this BC.
3018   if (bc != Bytecodes::_illegal) {
3019     for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
3020       juint* counter_addr = &cases[bc_case];
3021       juint  counter = *counter_addr;
3022       if ((counter == 0 && bc_counter_addr == nullptr)
3023           || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
3024         // this counter is either free or is already devoted to this BC
3025         bc_counter_addr = counter_addr;
3026         bc_counter = counter | bc;
3027       }
3028     }
3029   }
3030   if (bc_counter_addr == nullptr) {
3031     // Overflow, or no given bytecode.
3032     bc_counter_addr = &cases[BC_CASE_LIMIT-1];
3033     bc_counter = (*bc_counter_addr & ~LSB_MASK);  // clear LSB
3034   }
3035   *bc_counter_addr = bc_counter + (1 << LSB_BITS);
3036 }
3037 
3038 jint Deoptimization::total_deoptimization_count() {
3039   return _deoptimization_hist[Reason_none][0][0];
3040 }
3041 
3042 // Get the deopt count for a specific reason and a specific action. If either
3043 // one of 'reason' or 'action' is null, the method returns the sum of all
3044 // deoptimizations with the specific 'action' or 'reason' respectively.
3045 // If both arguments are null, the method returns the total deopt count.
3046 jint Deoptimization::deoptimization_count(const char *reason_str, const char *action_str) {
3047   if (reason_str == nullptr && action_str == nullptr) {
3048     return total_deoptimization_count();
3049   }
3050   juint counter = 0;
3051   for (int reason = 0; reason < Reason_LIMIT; reason++) {
3052     if (reason_str == nullptr || !strcmp(reason_str, trap_reason_name(reason))) {
3053       for (int action = 0; action < Action_LIMIT; action++) {
3054         if (action_str == nullptr || !strcmp(action_str, trap_action_name(action))) {
3055           juint* cases = _deoptimization_hist[reason][1+action];
3056           for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
3057             counter += cases[bc_case] >> LSB_BITS;
3058           }
3059         }
3060       }
3061     }
3062   }
3063   return counter;
3064 }
3065 
3066 void Deoptimization::print_statistics() {
3067   juint total = total_deoptimization_count();
3068   juint account = total;
3069   if (total != 0) {
3070     ttyLocker ttyl;
3071     if (xtty != nullptr)  xtty->head("statistics type='deoptimization'");
3072     tty->print_cr("Deoptimization traps recorded:");
3073     #define PRINT_STAT_LINE(name, r) \
3074       tty->print_cr("  %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
3075     PRINT_STAT_LINE("total", total);
3076     // For each non-zero entry in the histogram, print the reason,
3077     // the action, and (if specifically known) the type of bytecode.
3078     for (int reason = 0; reason < Reason_LIMIT; reason++) {
3079       for (int action = 0; action < Action_LIMIT; action++) {
3080         juint* cases = _deoptimization_hist[reason][1+action];
3081         for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
3082           juint counter = cases[bc_case];
3083           if (counter != 0) {
3084             char name[1*K];
3085             Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
3086             os::snprintf_checked(name, sizeof(name), "%s/%s/%s",
3087                     trap_reason_name(reason),
3088                     trap_action_name(action),
3089                     Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
3090             juint r = counter >> LSB_BITS;
3091             tty->print_cr("  %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
3092             account -= r;
3093           }
3094         }
3095       }
3096     }
3097     if (account != 0) {
3098       PRINT_STAT_LINE("unaccounted", account);
3099     }
3100     #undef PRINT_STAT_LINE
3101     if (xtty != nullptr)  xtty->tail("statistics");
3102   }
3103 }
3104 
3105 #else // COMPILER2_OR_JVMCI
3106 
3107 
3108 // Stubs for C1 only system.
3109 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
3110   return false;
3111 }
3112 
3113 const char* Deoptimization::trap_reason_name(int reason) {
3114   return "unknown";
3115 }
3116 
3117 jint Deoptimization::total_deoptimization_count() {
3118   return 0;
3119 }
3120 
3121 jint Deoptimization::deoptimization_count(const char *reason_str, const char *action_str) {
3122   return 0;
3123 }
3124 
3125 void Deoptimization::print_statistics() {
3126   // no output
3127 }
3128 
3129 void
3130 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
3131   // no update
3132 }
3133 
3134 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
3135   return 0;
3136 }
3137 
3138 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
3139                                        Bytecodes::Code bc) {
3140   // no update
3141 }
3142 
3143 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
3144                                               int trap_state) {
3145   jio_snprintf(buf, buflen, "#%d", trap_state);
3146   return buf;
3147 }
3148 
3149 #endif // COMPILER2_OR_JVMCI