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