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